Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 61 additions & 11 deletions chatbot/src/useChat.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ export function useChat() {
[error, setError] = useState(""),
[ready, setReady] = useState(false),
[submitting, setSubmitting] = useState(false),
[steerOnSend, setSteerOnSend] = useState(false),
// Messages sent while a reply runs, per conversation (see message-queue.js).
[queues, setQueues] = useState(readQueues),
// The generation whose final transcript has been loaded. A queued message
Expand Down Expand Up @@ -232,6 +233,37 @@ export function useChat() {
setDraftIssueId("");
open(null);
}, [open]);
useEffect(() => {
if (!user?.id || user.isGuest) {
setSteerOnSend(false);
return;
}
let current = true, revision = 0;
const refresh = () => {
const requested = ++revision;
return api("/api/assistant/preferences")
.then((prefs) => {
if (current && requested === revision) setSteerOnSend(!!prefs?.steerOnSend);
})
.catch(() => {});
};
const onMessage = (event) => {
if (event.source === window.parent && event.origin === location.origin &&
event.data?.type === "agentflow-assistant-preferences-changed")
void refresh();
};
const onVisibilityChange = () => {
if (document.visibilityState === "visible") void refresh();
};
void refresh();
document.addEventListener("visibilitychange", onVisibilityChange);
window.addEventListener("message", onMessage);
return () => {
current = false;
document.removeEventListener("visibilitychange", onVisibilityChange);
window.removeEventListener("message", onMessage);
};
}, [user?.id, user?.isGuest]);
useEffect(() => {
let current = true,
timer,
Expand Down Expand Up @@ -684,6 +716,8 @@ export function useChat() {
if (generation?.id !== s.generationId || generation.status === "running") return;
if (settledId !== s.generationId) return;
if (!generation.steer) {
// The POST can still reject the message after the reply finishes.
if (s.pending) return;
// The reply ended before the message was taken: send it next instead.
done();
setQueues((old) => restoreQueued(old, s.sessionId, s.item, false));
Expand Down Expand Up @@ -748,8 +782,12 @@ export function useChat() {
dispatchingRef.current = false;
}
}
return steerMessage(id, item);
}
async function steerMessage(id, item) {
const from = generation.id;
steeringRef.current = { sessionId: id, generationId: from, item };
const request = { sessionId: id, generationId: from, item, pending: true };
steeringRef.current = request;
setSteering({ sessionId: id, item });
setQueues((old) => removeQueued(old, id, item.id));
setError("");
Expand All @@ -765,13 +803,19 @@ export function useChat() {
approvalMode: item.approvalMode || "confirm",
},
);
request.pending = false;
if (steeringRef.current === request) setSteering({ sessionId: id, item });
return true;
} catch (e) {
steeringRef.current = null;
setSteering(null);
// If the reply just ended, the message simply goes out next.
setQueues((old) => restoreQueued(old, id, item, false));
if (!/没有进行中|已经结束|已结束/.test(e.message || "")) setError(e.message);
if (steeringRef.current === request) {
steeringRef.current = null;
setSteering(null);
}
const turnEnded = e.status === 409 &&
/^(当前没有进行中的回复|这一轮已经结束,请重新发送|生成已结束或不存在)$/.test(e.message);
const held = !turnEnded && e.status >= 400 && e.status < 500;
setQueues((old) => restoreQueued(old, id, item, held));
if (!turnEnded && currentId.current === id) setError(e.message);
return false;
}
}
Expand All @@ -793,16 +837,22 @@ export function useChat() {
generation?.status === "running" ||
steeringRef.current?.sessionId === currentId.current
) {
// Like Codex, a message sent during a reply waits its turn instead of
// stopping the reply. Internal follow-ups (confirmed drafts) never queue.
// Internal follow-ups (confirmed drafts) never queue or interrupt.
if (messagesOverride || fromQueue || !currentId.current) {
setError("当前回复仍在生成,请稍后再试。");
return false;
}
const id = currentId.current;
setQueues((old) =>
enqueue(old, id, queuedMessage({ text, attachments, references, approvalMode })),
);
const item = queuedMessage({ text, attachments, references, approvalMode });
if (steerOnSend && generation?.status === "running" && generation.id &&
!submittingRef.current && !steeringRef.current && !dispatchingRef.current &&
!stopRequestRef.current) {
// Failed steering restores the message to the queue, so the composer
// can clear without losing it. Further sends wait for this handoff.
await steerMessage(id, item);
return true;
}
setQueues((old) => enqueue(old, id, item));
setError("");
return true;
}
Expand Down
123 changes: 121 additions & 2 deletions chatbot/tests/message-queue-hook.test.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";

const state = vi.hoisted(() => ({ transcript: [], generation: null, generationGate: null }));
const state = vi.hoisted(() => ({ transcript: [], generation: null, generationGate: null, preferences: {} }));
const { apiMock, writeMock } = vi.hoisted(() => {
const apiMock = vi.fn(async (path) => {
if (path === "/api/auth/current")
return { user: { id: 1, loginName: "tester", codeBuddyApiKeyConfigured: true } };
if (path === "/api/projects") return [{ id: "p1", name: "项目一", ownerId: 1, members: [1] }];
if (path === "/api/assistant/models")
return { default: "m1", sponsoredModel: "m1", models: [{ id: "m1", name: "模型一" }] };
if (path === "/api/assistant/preferences") return structuredClone(state.preferences);
if (path === "/api/users") return [{ id: 1, loginName: "tester", codeBuddyApiKeyConfigured: true }];
if (path === "/api/assistant/sessions") return [];
if (path.startsWith("/api/assistant/sessions/s2")) {
Expand Down Expand Up @@ -91,6 +92,7 @@ describe("sending while a reply runs", () => {
state.transcript = [{ role: "user", content: "查失败节点" }];
state.generation = { id: "g-running", status: "running", events: [{ sequence: 1, data: { kind: "tool", tool: "runs_get" } }] };
state.generationGate = null;
state.preferences = {};
globalThis.EventSource = FakeEventSource;
});
afterEach(() => {
Expand Down Expand Up @@ -139,6 +141,123 @@ describe("sending while a reply runs", () => {
unmount();
});

test("the saved immediate-send preference steers with attachments and queues later sends during handoff", async () => {
state.preferences = { steerOnSend: true };
const { result, unmount } = await openRunning();
const attachments = [{ id: "screenshot", name: "image.png", mimeType: "image/png" }];
const references = [{ type: "issue", id: "issue-1" }];
await act(async () => {
expect(await result.current.send({ text: "立即看这里", attachments, references, approvalMode: "assisted" })).toBe(true);
expect(await result.current.send({ text: "下一条补充" })).toBe(true);
});
expect(steerPosts()).toHaveLength(1);
expect(steerPosts()[0][1]).toMatchObject({
content: "立即看这里", model: "m1", attachments, references, approvalMode: "assisted",
});
expect(result.current.steering?.text).toBe("立即看这里");
expect(result.current.queue.map((m) => m.text)).toEqual(["下一条补充"]);
expect(generationPosts()).toHaveLength(0);
unmount();
});

test.each([
[400, "请先配置 API Key"],
[409, "这个对话由 Codex 回复,不能中途切换 CLI"],
])("an immediate send rejected with %i holds the queue", async (status, error) => {
state.preferences = { steerOnSend: true };
const { result, unmount } = await openRunning();
writeMock.mockRejectedValueOnce(Object.assign(new Error(error), { status }));
await act(async () => {
expect(await result.current.send({ text: "不能丢失" })).toBe(true);
});
expect(steerPosts()).toHaveLength(1);
expect(result.current.steering).toBe(null);
expect(result.current.queue.map((m) => m.text)).toEqual(["不能丢失"]);
expect(result.current.error).toBe(error);
expect(result.current.queueHeld).toBe(true);
await finish("completed");
await waitFor(() => expect(result.current.session?.messages).toHaveLength(2));
expect(generationPosts()).toHaveLength(0);
expect(result.current.queue.map((m) => m.text)).toEqual(["不能丢失"]);
unmount();
});

test("a reply ending before the steer response does not retry a rejected message", async () => {
state.preferences = { steerOnSend: true };
const { result, unmount } = await openRunning();
let rejectSteer;
writeMock.mockImplementationOnce(() => new Promise((_, reject) => { rejectSteer = reject; }));
let sent;
act(() => { sent = result.current.send({ text: "等待引导结果" }); });

await finish("completed");
await waitFor(() => expect(result.current.session?.messages).toHaveLength(2));
expect(generationPosts()).toHaveLength(0);
await act(async () => {
rejectSteer(Object.assign(new Error("请先配置 API Key"), { status: 400 }));
expect(await sent).toBe(true);
});
expect(result.current.queueHeld).toBe(true);
expect(result.current.queue.map((m) => m.text)).toEqual(["等待引导结果"]);
expect(generationPosts()).toHaveLength(0);
unmount();
});

test("saving the setting updates an already open chat", async () => {
const { result, unmount } = await openRunning();
state.preferences = { steerOnSend: true };
await act(async () => {
window.dispatchEvent(new MessageEvent("message", {
source: window.parent, origin: location.origin,
data: { type: "agentflow-assistant-preferences-changed" },
}));
});
await act(async () => { await result.current.send({ text: "使用新设置" }); });
expect(steerPosts()).toHaveLength(1);
expect(result.current.queue).toHaveLength(0);
expect(result.current.steering?.text).toBe("使用新设置");
unmount();
});

test("a slow initial preferences read cannot overwrite a newly saved setting", async () => {
let release;
const original = apiMock.getMockImplementation();
apiMock.mockImplementation((path) => path === "/api/assistant/preferences"
? new Promise((resolve) => { release = resolve; }) : original(path));
const { result, unmount } = await openRunning();
apiMock.mockImplementation(original);
state.preferences = { steerOnSend: true };
await act(async () => {
window.dispatchEvent(new MessageEvent("message", {
source: window.parent, origin: location.origin,
data: { type: "agentflow-assistant-preferences-changed" },
}));
});
await act(async () => { release({ steerOnSend: false }); });
await act(async () => { await result.current.send({ text: "按最新设置发送" }); });
expect(steerPosts()).toHaveLength(1);
unmount();
});

test("returning to a hidden tab picks up the saved send preference", async () => {
const { result, unmount } = await openRunning();
const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
const preferenceReads = () => apiMock.mock.calls.filter(([path]) => path === "/api/assistant/preferences").length;
const initialReads = preferenceReads();
try {
await act(async () => { document.dispatchEvent(new Event("visibilitychange")); });
expect(preferenceReads()).toBe(initialReads);
state.preferences = { steerOnSend: true };
visibility.mockReturnValue("visible");
await act(async () => { document.dispatchEvent(new Event("visibilitychange")); });
await act(async () => { await result.current.send({ text: "切回后使用新设置" }); });
expect(steerPosts()).toHaveLength(1);
} finally {
visibility.mockRestore();
unmount();
}
});

test("prevents repeated stop requests and waits for actual process exit", async () => {
const { result, unmount } = await openRunning();
let resolve;
Expand Down Expand Up @@ -253,7 +372,7 @@ describe("sending while a reply runs", () => {
await result.current.send({ text: "补充一句" });
});
writeMock.mockImplementationOnce(async () => {
throw new Error("生成已结束或不存在");
throw Object.assign(new Error("生成已结束或不存在"), { status: 409 });
});
await act(async () => {
await result.current.sendNow(result.current.queue[0].id);
Expand Down
4 changes: 3 additions & 1 deletion design.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,9 @@ Bot 管理页(`#botsView`)按需求列表与运行记录列表的 Harness

界面上称「AI 助手」,避免和「Bot 管理」里的企业微信机器人混淆。设置页、SOP 建议卡片和子 Agent 面板都用这个名字。

AI 助手页(`#assistantView`,路由 `#/assistant`)在设置导航「管理与记录」下紧跟 Bot 管理,图标为 Harness `sparkles`。页头只有 H1 和一句说明(先讲它是谁,再讲能设置什么);内容和其他设置页一样铺满 1200px 居中容器,两块 14px 圆角面板:「主动派发」里是「主动派角色」「主动走 SOP」两行(默认关闭,面板说明写明打开后更主动,以及角色直接派、SOP 先确认),左侧标题 + 说明,右侧 `role="switch"` 开关;「自定义规则」是一个可纵向拉伸的输入框,右下角显示「N / 4000」。底部「保存」是页面唯一的实心按钮,没有改动或保存中时禁用;未登录只显示提示。样式在 `web/app/assistant-settings.css`,规则限定在 `#assistantView` 内,只引用 `--hui-*` 令牌。
AI 助手页(`#assistantView`,路由 `#/assistant`)在设置导航「管理与记录」下紧跟 Bot 管理,图标为 Harness `sparkles`。页头只有 H1 和一句说明(先讲它是谁,再讲能设置什么);内容和其他设置页一样铺满 1200px 居中容器,使用三块 14px 圆角面板:「消息发送」提供「生成中发送消息」下拉选项,默认「排队」,也可选「立即发送」,说明会打断当前回复、保留已输出内容并继续处理新消息;「主动派发」里是「主动派角色」「主动走 SOP」两行(默认关闭,面板说明写明打开后更主动,以及角色直接派、SOP 先确认),左侧标题 + 说明,右侧 `role="switch"` 开关;「自定义规则」是一个可纵向拉伸的输入框,右下角显示「N / 4000」。底部「保存」是页面唯一的实心按钮,没有改动或保存中时禁用;未登录只显示提示。样式在 `web/app/assistant-settings.css`,规则限定在 `#assistantView` 内,只引用 `--hui-*` 令牌。

发送方式按用户保存为 `steerOnSend`,设置保存后通知已打开的工作台即时刷新。立即发送复用排队消息的「引导」操作;引导切换期间再次发送的消息先排队,引导请求失败也保留消息。手动「引导」仍可用于排队模式。

没有 @ SOP、也没有点名要走 SOP 时,AI 助手自己决定交给 SOP 的事是建议。每次批准由用户在卡片上确认;帮我批准由独立审查决定,未通过时同样变成建议卡片;完全权限下直接启动。角色始终直接派发,不弹卡片。`timing=start` 的建议 3 分钟无人处理就超时,服务端把事情交回 AI 助手自己做,不依赖浏览器还开着。决定通过 `POST /api/assistant/sessions/{id}/proposals` 提交。开关和自定义规则按用户存在 `assistant_preferences`,由 AutoMigrate 建表,接口是 `GET` / `PUT /api/assistant/preferences`。

Expand Down
2 changes: 2 additions & 0 deletions internal/domain/assistant_generation.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ type AssistantSteer struct {
ActorName string `json:"actorName,omitempty"`
// Trigger marks the follow-up message; empty means the user steered.
Trigger string `json:"trigger,omitempty"`
// TriggerID identifies the accepted steer in the saved transcript.
TriggerID string `json:"triggerId,omitempty"`
}

// A bounded projection survives eviction of old token events and reconnects.
Expand Down
4 changes: 3 additions & 1 deletion internal/domain/assistant_preferences.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ const AssistantPreferencesInstructionsMax = 4000

// AssistantPreferences is how one user wants Main Bot to work: whether it
// hands work to roles and SOPs more readily (off by default), and extra
// rules added to every turn.
// rules added to every turn. SteerOnSend interrupts a running reply when
// sending a message; the default queues it until the reply finishes.
type AssistantPreferences struct {
ProactiveRoles bool `json:"proactiveRoles"`
ProactiveSOPs bool `json:"proactiveSops"`
SteerOnSend bool `json:"steerOnSend"`
Instructions string `json:"instructions"`
UpdatedAt time.Time `json:"updatedAt,omitempty"`
}
Loading
Loading