Skip to content

Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.

feat: ask before handing a requirement to an SOP (#157)

crispinhu27deca63ab1423
diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsx
index a70dee72..bae07622 100644
--- a/chatbot/src/App.jsx
+++ b/chatbot/src/App.jsx
@@ -27,6 +27,7 @@ import {
elapsedSeconds,
formatElapsed,
confirmationCaption,
+ isProposalTimeout,
canChatInProject,
projectPickerOptions,
} from "./api";
@@ -1470,7 +1471,7 @@ export default function App() {
<div className="loading-session">正在恢复对话…</div>
) : null}
{messages.map((message, index) =>
- confirmationCaption(message, messages[index - 1]) ? (
+ isProposalTimeout(message, messages[index - 1]) ? null : confirmationCaption(message, messages[index - 1]) ? (
<div
key={index}
className="confirmation-note"
@@ -1598,6 +1599,12 @@ export default function App() {
artifact={a}
context={operationContext}
onApply={chat.readOnly ? null : chat.applyDraft}
+ onDecide={
+ chat.readOnly
+ ? null
+ : (messageIndex, draftIndex, decision) =>
+ chat.decideProposal(messageIndex, draftIndex, decision, approval)
+ }
onPreview={openArtifact}
/>
))}
diff --git a/chatbot/src/SidePanel.jsx b/chatbot/src/SidePanel.jsx
index 0f909022..a26839c7 100644
--- a/chatbot/src/SidePanel.jsx
+++ b/chatbot/src/SidePanel.jsx
@@ -32,11 +32,57 @@ const ExternalLink = (props) => (
<HarnessIcon name="preview-expand" {...props} />
);
-export function DraftCard({ artifact, onApply, onPreview, context = {} }) {
+function useCountdown(expiresAt) {
+ const deadline = expiresAt ? Date.parse(expiresAt) : NaN;
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (Number.isNaN(deadline)) return undefined;
+ setNow(Date.now());
+ const timer = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(timer);
+ }, [deadline]);
+ if (Number.isNaN(deadline)) return null;
+ return Math.max(0, Math.ceil((deadline - now) / 1000));
+}
+
+function formatCountdown(seconds) {
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
+}
+
+export function DraftCard({
+ artifact,
+ onApply,
+ onDecide,
+ onPreview,
+ context = {},
+}) {
const [busy, setBusy] = useState(false),
[uncertain, setUncertain] = useState(false),
[error, setError] = useState("");
const draft = artifact.draft;
+ const declined = ["declined", "muted", "expired"].includes(draft.decision);
+ const answerable =
+ !!draft.proposal &&
+ !draft.inherited &&
+ !draft.saved &&
+ !draft.decision &&
+ !!onDecide;
+ const remaining = useCountdown(
+ answerable && draft.proposal.timing === "start"
+ ? draft.proposal.expiresAt
+ : "",
+ );
+ const decide = async (decision) => {
+ setBusy(true);
+ setError("");
+ try {
+ await onDecide(artifact.messageIndex, artifact.draftIndex, decision);
+ } catch (e) {
+ setError(operationError(e));
+ } finally {
+ setBusy(false);
+ }
+ };
const [repositories, setRepositories] = useState([]),
[selectedRepositories, setSelectedRepositories] = useState(null),
[repositoryError, setRepositoryError] = useState(""),
@@ -114,18 +160,41 @@ export function DraftCard({ artifact, onApply, onPreview, context = {} }) {
{artifact.name !== actionName(draft.tool)
? `${actionName(draft.tool)} · `
: ""}
- {draft.saved
+ {declined
+ ? draft.decision === "muted"
+ ? "未采纳,本会话不再建议"
+ : draft.decision === "expired"
+ ? "已超时"
+ : "未采纳"
+ : draft.saved
? "已执行"
: draft.resolved
? "已完成"
: draft.inherited
? "继承的历史记录"
- : "待确认"}
+ : draft.proposal
+ ? "AI 助手的建议"
+ : "待确认"}
</small>
</span>
{target ? <ExternalLink size={16} /> : <ChevronRight size={16} />}
</Title>
<div className="operation-summary">
+ {draft.proposal?.reason ? (
+ <p className="proposal-reason">
+ {draft.proposal.timing !== "start"
+ ? "可选的后续工作"
+ : "建议整件事走 SOP"}
+ :{draft.proposal.reason}
+ </p>
+ ) : null}
+ {remaining !== null ? (
+ <p className="proposal-countdown" role="timer">
+ {remaining > 0
+ ? `${formatCountdown(remaining)} 后未确认,AI 助手将直接执行`
+ : "已超时,AI 助手即将直接执行"}
+ </p>
+ ) : null}
{draft.review ? (
<p className="muted">帮我批准 · {draft.review.model || "AI 审查"}:{draft.review.rationale}</p>
) : null}
@@ -207,7 +276,12 @@ export function DraftCard({ artifact, onApply, onPreview, context = {} }) {
</p>
))}
{error ? <p className="error">{error}</p> : null}
- {!draft.inherited && !target && onApply ? (
+ {draft.decision === "expired" && !draft.inherited ? (
+ <button type="button" className="quiet-button" disabled>
+ 已超时,AI 助手直接执行
+ </button>
+ ) : null}
+ {!draft.inherited && !target && onApply && !declined ? (
<button
className={draft.saved ? "quiet-button" : "primary-button"}
disabled={
@@ -243,11 +317,33 @@ export function DraftCard({ artifact, onApply, onPreview, context = {} }) {
</>
) : busy ? (
"执行中…"
+ ) : draft.proposal ? (
+ draft.tool === "issues_save" ? "建需求并走 SOP" : "走 SOP"
) : (
`确认${summary.title}`
)}
</button>
) : null}
+ {answerable ? (
+ <div className="proposal-actions">
+ <button
+ type="button"
+ className="quiet-button"
+ disabled={busy}
+ onClick={() => decide("declined")}
+ >
+ {draft.proposal.timing === "start" ? "让 AI 助手自己做" : "不需要"}
+ </button>
+ <button
+ type="button"
+ className="proposal-mute"
+ disabled={busy}
+ onClick={() => decide("muted")}
+ >
+ 本会话不再建议
+ </button>
+ </div>
+ ) : null}
{savedIssue?.id &&
context.onLinkIssue &&
!context.runId &&
diff --git a/chatbot/src/SubagentSession.jsx b/chatbot/src/SubagentSession.jsx
index 755afe04..642e7af5 100644
--- a/chatbot/src/SubagentSession.jsx
+++ b/chatbot/src/SubagentSession.jsx
@@ -92,7 +92,7 @@ export function SubagentSession({ agent, live = false, artifacts = [], onOpenArt
className="node-message node-message-user"
aria-label="收到的任务"
>
- <span className="node-message-sender">Main Bot</span>
+ <span className="node-message-sender">AI 助手</span>
<RichContent message={step.input || step.detail} />
</article>
) : null}
diff --git a/chatbot/src/api.js b/chatbot/src/api.js
index 39838a9a..b2313b52 100644
--- a/chatbot/src/api.js
+++ b/chatbot/src/api.js
@@ -390,8 +390,31 @@ export function restoreStream(snapshot) {
// Keep the confirmation acknowledgement visible without presenting an internal
// model-resume instruction as something the user typed. Validate the preceding
// saved receipt; ordinary user text must never be hidden by a prefix match.
+// Mirrors assistantProposalDeclinedText and assistantProposalExpiredText.
+const PROPOSAL_DECLINED = "不走 SOP,这件事由你直接完成。";
+const PROPOSAL_EXPIRED = "SOP 建议超时未确认,这件事由你直接完成。";
+// The card already says it timed out, so the turn that hands the work back
+// is not shown.
+export function isProposalTimeout(message, previous) {
+ return (
+ message?.role === "user" &&
+ message.trigger === "proposal_timeout" &&
+ message.content === PROPOSAL_EXPIRED &&
+ previous?.role === "assistant" &&
+ (parseReply(previous).drafts || []).some(
+ (d) => d.proposal && d.decision === "expired",
+ )
+ );
+}
+
export function confirmationCaption(message, previous) {
if (message?.role !== "user" || previous?.role !== "assistant") return "";
+ if (message.content === PROPOSAL_DECLINED)
+ return (parseReply(previous).drafts || []).some(
+ (d) => d.proposal && ["declined", "muted"].includes(d.decision),
+ )
+ ? "不走 SOP,让 AI 助手自己做"
+ : "";
const match =
/^已确认并执行 ([a-z_]+)。请核对这条草稿的保存回执,继续完成原始请求;不要重复刚才的写入,下一项需要确认时提交草稿,全部完成时总结实际结果。$/.exec(
message.content || "",
diff --git a/chatbot/src/styles.css b/chatbot/src/styles.css
index 04f201b5..b66f489b 100644
--- a/chatbot/src/styles.css
+++ b/chatbot/src/styles.css
@@ -2314,11 +2314,33 @@ a.project-entry {
font-size: 10px;
}
.draft-card > .primary-button,
-.draft-card > .quiet-button {
+.draft-card > .quiet-button,
+.proposal-actions > .quiet-button {
min-height: 29px;
padding: 5px 9px;
font-size: 11px;
}
+.proposal-reason {
+ color: var(--muted);
+}
+.proposal-countdown {
+ color: var(--accent);
+ font-variant-numeric: tabular-nums;
+}
+.proposal-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ margin-left: 8px;
+}
+.proposal-mute {
+ font-size: 11px;
+ color: var(--muted);
+ padding: 4px 2px;
+}
+.proposal-mute:hover {
+ color: var(--text);
+}
.run-row {
border: 1px solid var(--line);
border-radius: 9px;
diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js
index 2c82c7e0..90fb2be0 100644
--- a/chatbot/src/useChat.js
+++ b/chatbot/src/useChat.js
@@ -927,18 +927,42 @@ export function useChat() {
applyingRef.current.add(key);
let executed = false;
try {
- const stored = await api(sessionPath(id));
- const reply = JSON.parse(stored.messages[messageIndex].content);
- const draft = reply.drafts[draftIndex];
+ let stored = await api(sessionPath(id));
+ let reply = JSON.parse(stored.messages[messageIndex].content);
+ let draft = reply.drafts[draftIndex];
if (draft.saved || draft.inherited) return null;
+ if (generation?.status === "running")
+ throw Error("请等待回复结束后再确认操作。");
+ if (draft.proposal && !draft.decision) {
+ // Accept before running it: once the timeout has handed the work to
+ // the assistant, the accept fails and the operation must not run.
+ try {
+ stored = (
+ await write(`${sessionPath(id)}/proposals`, {
+ messageIndex,
+ draftIndex,
+ decision: "accepted",
+ })
+ ).session;
+ } catch (error) {
+ void api(sessionPath(id))
+ .then((latest) => currentId.current === id && setSession(latest))
+ .catch(() => {});
+ throw error;
+ }
+ reply = JSON.parse(stored.messages[messageIndex].content);
+ draft = reply.drafts[draftIndex];
+ }
+ if (draft.proposal && draft.decision !== "accepted") {
+ if (currentId.current === id) setSession(stored);
+ throw Error("这条建议已经处理过,不能执行。");
+ }
try {
Object.assign(draft, reviewedOperation(draft, review));
} catch (error) {
if (error.draftChanged && currentId.current === id) setSession(stored);
throw error;
}
- if (generation?.status === "running")
- throw Error("请等待回复结束后再确认操作。");
// The session header lets a confirmed SOP continue in this
// conversation's workspace.
const result = await api("/mcp", {
@@ -1005,6 +1029,36 @@ export function useChat() {
applyingRef.current.delete(key);
}
}
+ // Answers an assistant proposal card. Declining work the assistant had not
+ // started continues with the turn the server returns.
+ async function decideProposal(messageIndex, draftIndex, decision, approvalMode = "confirm") {
+ const id = activeId;
+ if (generation?.status === "running")
+ throw Error("请等待回复结束后再处理建议。");
+ const key = `${id}:${messageIndex}:${draftIndex}`;
+ if (applyingRef.current.has(key)) throw Error("这条建议正在处理,请稍候。");
+ applyingRef.current.add(key);
+ try {
+ const result = await write(`${sessionPath(id)}/proposals`, {
+ messageIndex,
+ draftIndex,
+ decision,
+ });
+ if (currentId.current !== id) return;
+ setSession(result.session);
+ if (result.followUp)
+ await send({
+ text: result.followUp.text,
+ messagesOverride: result.session.messages,
+ approvalMode,
+ });
+ } catch (e) {
+ setError(e.message);
+ throw e;
+ } finally {
+ applyingRef.current.delete(key);
+ }
+ }
async function linkIssue(issueId) {
if (submittingRef.current || generation?.status === "running") {
setError("请等待回复结束或停止生成,再关联需求。");
@@ -1134,6 +1188,7 @@ export function useChat() {
edit,
regenerate,
applyDraft,
+ decideProposal,
refresh,
refreshSessions,
};
diff --git a/chatbot/tests/components.test.jsx b/chatbot/tests/components.test.jsx
index 9ce8ae11..77cc4fae 100644
--- a/chatbot/tests/components.test.jsx
+++ b/chatbot/tests/components.test.jsx
@@ -531,6 +531,122 @@ describe("content and panels", () => {
expect(screen.getByText("导入前请检查")).toBeInTheDocument();
});
+ test("an SOP proposal is declined or muted from its card", async () => {
+ const user = userEvent.setup();
+ const decide = vi.fn(async () => ({}));
+ const artifact = (draft) => ({
+ id: "sop2",
+ messageIndex: 3,
+ draftIndex: 0,
+ name: "积分排行榜",
+ kind: "operation",
+ draft: {
+ tool: "issues_save",
+ body: { projectId: "p1", title: "积分排行榜", kind: "requirement", workflowId: "delivery" },
+ proposal: { reason: "后续可以走 SOP 完整交付", timing: "end" },
+ ...draft,
+ },
+ });
+ const context = { projectId: "p1", projects: chat.projects, references: [] };
+ const { rerender } = render(
+ <DraftCard artifact={artifact({})} onApply={vi.fn()} onDecide={decide} onPreview={vi.fn()} context={context} />,
+ );
+ expect(screen.getByText(/可选的后续工作:后续可以走 SOP/)).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "不需要" }));
+ expect(decide).toHaveBeenLastCalledWith(3, 0, "declined");
+ await user.click(screen.getByRole("button", { name: "本会话不再建议" }));
+ expect(decide).toHaveBeenLastCalledWith(3, 0, "muted");
+
+ rerender(
+ <DraftCard
+ artifact={artifact({ proposal: { reason: "整件需求走 SOP", timing: "start" } })}
+ onApply={vi.fn()}
+ onDecide={decide}
+ onPreview={vi.fn()}
+ context={context}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "让 AI 助手自己做" })).toBeInTheDocument();
+ expect(screen.queryByRole("timer")).not.toBeInTheDocument();
+
+ const expiresAt = new Date(Date.now() + 125_000).toISOString();
+ rerender(
+ <DraftCard
+ artifact={artifact({ proposal: { reason: "整件需求走 SOP", timing: "start", expiresAt } })}
+ onApply={vi.fn()}
+ onDecide={decide}
+ onPreview={vi.fn()}
+ context={context}
+ />,
+ );
+ expect(screen.getByRole("timer")).toHaveTextContent(/^2:0[45] 后未确认,AI 助手将直接执行$/);
+
+ rerender(
+ <DraftCard
+ artifact={artifact({
+ proposal: { reason: "整件需求走 SOP", timing: "start", expiresAt: new Date(Date.now() - 1000).toISOString() },
+ })}
+ onApply={vi.fn()}
+ onDecide={decide}
+ onPreview={vi.fn()}
+ context={context}
+ />,
+ );
+ expect(screen.getByRole("timer")).toHaveTextContent("已超时,AI 助手即将直接执行");
+
+ rerender(
+ <DraftCard
+ artifact={artifact({ proposal: { reason: "整件需求走 SOP", timing: "start", expiresAt }, decision: "expired" })}
+ onApply={vi.fn()}
+ onDecide={decide}
+ onPreview={vi.fn()}
+ context={context}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "已超时,AI 助手直接执行" })).toBeDisabled();
+ expect(screen.queryByRole("button", { name: "建需求并走 SOP" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("timer")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "让 AI 助手自己做" })).not.toBeInTheDocument();
+
+ rerender(
+ <DraftCard artifact={artifact({ decision: "declined" })} onApply={vi.fn()} onDecide={decide} onPreview={vi.fn()} context={context} />,
+ );
+ expect(screen.getByText(/未采纳/)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "建需求并走 SOP" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "本会话不再建议" })).not.toBeInTheDocument();
+ });
+
+ test("an SOP proposal card names the SOP route", async () => {
+ const user = userEvent.setup();
+ const apply = vi.fn(async () => ({}));
+ const decide = vi.fn(async () => ({}));
+ render(
+ <DraftCard
+ artifact={{
+ id: "sop1",
+ messageIndex: 1,
+ draftIndex: 0,
+ name: "积分排行榜",
+ kind: "operation",
+ draft: {
+ tool: "issues_save",
+ body: { projectId: "p1", title: "积分排行榜", kind: "requirement", workflowId: "delivery" },
+ proposal: { reason: "新功能,SOP 用途对得上", timing: "start" },
+ },
+ }}
+ onApply={apply}
+ onDecide={decide}
+ onPreview={vi.fn()}
+ context={{ projectId: "p1", projects: [{ id: "p1", name: "项目一" }], references: [] }}
+ />,
+ );
+ expect(screen.getByText(/建议整件事走 SOP:新功能/)).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "建需求并走 SOP" }));
+ expect(apply).toHaveBeenCalledWith(1, 0, expect.anything());
+ await user.click(screen.getByRole("button", { name: "让 AI 助手自己做" }));
+ expect(decide).toHaveBeenLastCalledWith(1, 0, "declined");
+ });
+
test("opens SOP node conversation and its artifacts", async () => {
const user = userEvent.setup();
render(<SopRunPanel runs={[run]} onClose={vi.fn()} />);
diff --git a/chatbot/tests/conversation-navigation.test.mjs b/chatbot/tests/conversation-navigation.test.mjs
index 6a97552c..9a04bdef 100644
--- a/chatbot/tests/conversation-navigation.test.mjs
+++ b/chatbot/tests/conversation-navigation.test.mjs
@@ -176,6 +176,34 @@ test("internal resume prompts render as acknowledgements only with a matching sa
"",
);
});
+test("answered SOP proposals render as short acknowledgements", async () => {
+ const { confirmationCaption, isProposalTimeout } = await import("../src/api.js");
+ const reply = (draft) => ({
+ role: "assistant",
+ content: JSON.stringify({ message: "", drafts: [draft] }),
+ });
+ const dispatch = {
+ tool: "issues_dispatch",
+ path: { id: "i1" },
+ proposal: { reason: "整件需求走 SOP", timing: "start" },
+ };
+ const declined = { role: "user", content: "不走 SOP,这件事由你直接完成。" };
+ assert.equal(
+ confirmationCaption(declined, reply({ ...dispatch, decision: "declined" })),
+ "不走 SOP,让 AI 助手自己做",
+ );
+ assert.equal(confirmationCaption(declined, reply(dispatch)), "");
+ const expired = {
+ role: "user",
+ trigger: "proposal_timeout",
+ content: "SOP 建议超时未确认,这件事由你直接完成。",
+ };
+ const timedOut = reply({ ...dispatch, decision: "expired" });
+ assert.equal(confirmationCaption(expired, timedOut), "");
+ assert.equal(isProposalTimeout(expired, timedOut), true);
+ assert.equal(isProposalTimeout({ ...expired, trigger: "" }, timedOut), false);
+ assert.equal(isProposalTimeout(expired, reply(dispatch)), false);
+});
test("a project created from another project's chat links to the new project", () => {
const draft = {
tool: "projects_save",
diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsx
index 8301bc80..f20eb7c5 100644
--- a/chatbot/tests/hooks.test.jsx
+++ b/chatbot/tests/hooks.test.jsx
@@ -212,6 +212,67 @@ describe("conversation hooks", () => {
}
});
+ test("a proposal card accepts before it runs, and a timed-out one never runs", async () => {
+ const { result } = renderHook(() => useChat());
+ await waitFor(() => expect(result.current.ready).toBe(true));
+ act(() => result.current.open("s1"));
+ await waitFor(() => expect(result.current.session?.id).toBe("s1"));
+ const draft = { tool: "issues_dispatch", path: { id: "i1" }, proposal: { reason: "走 SOP", timing: "start" } };
+ const withDraft = (extra = {}) => ({
+ id: "s1",
+ projectId: "p1",
+ messages: [{ role: "assistant", content: JSON.stringify({ message: "建议", drafts: [{ ...draft, ...extra }] }) }],
+ });
+ const original = writeMock.getMockImplementation();
+ const mcpCalls = () => apiMock.mock.calls.filter(([path]) => path === "/mcp");
+ try {
+ writeMock.mockImplementation((path, body, method) =>
+ path.endsWith("/proposals")
+ ? Promise.reject(Object.assign(Error("这条建议已经处理过"), { status: 409 }))
+ : original(path, body, method),
+ );
+ apiMock.mockResolvedValueOnce(withDraft());
+ await act(() => expect(result.current.applyDraft(0, 0, { approved: true })).rejects.toThrow("已经处理过"));
+ expect(mcpCalls()).toHaveLength(0);
+
+ writeMock.mockImplementation((path, body, method) =>
+ path.endsWith("/proposals")
+ ? Promise.resolve({ session: withDraft({ decision: "accepted" }), followUp: null })
+ : original(path, body, method),
+ );
+ apiMock.mockResolvedValueOnce(withDraft());
+ await act(() => result.current.applyDraft(0, 0, { approved: true }));
+ const accept = writeMock.mock.calls.findIndex(([path]) => path.endsWith("/proposals"));
+ const mcp = apiMock.mock.calls.findIndex(([path]) => path === "/mcp");
+ expect(writeMock.mock.invocationCallOrder[accept]).toBeLessThan(apiMock.mock.invocationCallOrder[mcp]);
+ const saved = writeMock.mock.calls.find(([path, , method]) => path === "/api/assistant/sessions/s1" && method === "PUT");
+ expect(JSON.parse(saved[1].messages[0].content).drafts[0]).toMatchObject({ decision: "accepted", saved: true });
+ } finally {
+ writeMock.mockImplementation(original);
+ }
+ });
+
+ test.each(["declined", "muted", "expired"])("a %s proposal decision refreshes a stale card without writing", async (decision) => {
+ const { result } = renderHook(() => useChat());
+ await waitFor(() => expect(result.current.ready).toBe(true));
+ act(() => result.current.open("s1"));
+ await waitFor(() => expect(result.current.session?.id).toBe("s1"));
+ const draft = { tool: "issues_dispatch", path: { id: "i1" }, proposal: { reason: "走 SOP", timing: "start" } };
+ const withDraft = (value) => ({
+ ...result.current.session,
+ messages: [{ role: "assistant", content: JSON.stringify({ message: "建议", drafts: [value] }) }],
+ });
+ act(() => result.current.setSession(withDraft(draft)));
+ const latest = withDraft({ ...draft, decision });
+ apiMock.mockResolvedValueOnce(latest);
+
+ await act(() => expect(result.current.applyDraft(0, 0, { approved: true })).rejects.toThrow("这条建议已经处理过"));
+
+ expect(apiMock).not.toHaveBeenCalledWith("/mcp", expect.anything());
+ expect(writeMock).not.toHaveBeenCalled();
+ expect(result.current.session).toEqual(latest);
+ });
+
test("provides local fixture conversations and completes a local reply", async () => {
history.replaceState({}, "", "/?localPreview=1");
vi.useFakeTimers();
diff --git a/design.md b/design.md
index 9e9b4519..ff0c1a07 100644
--- a/design.md
+++ b/design.md
@@ -132,7 +132,7 @@
### 启用视图与设置区容器
-按钮、页头、输入的映射只对登记视图生效:`#issuesView`、`#approvalsView`、`#assetsView`、`#mcpView`、`#botsView`、`#knowledgeView` 以及设置区各视图(`#settingsView`、`#projectsView`、`#runnersView`、`#agentsView`、`#metricsView`、`#businessDomainsView`、`#guideView`、`#platformView`、`#businessDomainManagementView`),外加挂到 `<body>` 的 `#agentModal`、`#customMcpModal`、`.pw-root`、`#kbDrawer`。
+按钮、页头、输入的映射只对登记视图生效:`#issuesView`、`#approvalsView`、`#assetsView`、`#mcpView`、`#botsView`、`#assistantView`、`#knowledgeView` 以及设置区各视图(`#settingsView`、`#projectsView`、`#runnersView`、`#agentsView`、`#metricsView`、`#businessDomainsView`、`#guideView`、`#platformView`、`#businessDomainManagementView`),外加挂到 `<body>` 的 `#agentModal`、`#customMcpModal`、`.pw-root`、`#kbDrawer`。
设置区视图的外层内容统一居中、最大宽 1200px(`.page-view.active` 的直接子元素),页面不再各自限宽。流程设计(`#flowView`)、工作区页面、图标栏、侧栏与顶栏不受影响。
@@ -362,6 +362,14 @@ Bot 管理页(`#botsView`)按需求列表与运行记录列表的 Harness
发送状态轮询(`botPatchDeliveryRow`)保留原徽标节点,只替换 `data-tone` 和内部图形,颜色因此可以过渡。
+## AI 助手设置
+
+界面上称「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-*` 令牌。
+
+没有 @ SOP、也没有点名要走 SOP 时,AI 助手自己决定交给 SOP 的事是建议。每次批准由用户在卡片上确认;帮我批准由独立审查决定,未通过时同样变成建议卡片;完全权限下直接启动。角色始终直接派发,不弹卡片。`timing=start` 的建议 3 分钟无人处理就超时,服务端把事情交回 AI 助手自己做,不依赖浏览器还开着。决定通过 `POST /api/assistant/sessions/{id}/proposals` 提交。开关和自定义规则按用户存在 `assistant_preferences`,由 AutoMigrate 建表,接口是 `GET` / `PUT /api/assistant/preferences`。
+
## 角色定义弹窗
角色定义的新建与编辑共用 `#agentModal`(`web/index.html`,面板在 `web/app/flows.js`、`web/app/agents.js`),样式在 `web/product-v4.css` 的 `#agentModal` 段。
@@ -454,6 +462,7 @@ Bot 管理页(`#botsView`)按需求列表与运行记录列表的 Harness
| `web/knowledge.js`、`web/knowledge.css` | 知识中心的概览指标(`kbMetricsHTML`)、四个标签的面板与行模板(`kbPanel`、`kbRow`、`kbBadge`)、通用右侧抽屉 |
| `web/app/runs.js`、`web/product-v4.css`(运行记录列表区段) | 运行记录列表的面板、标签计数、状态徽标和行模板 |
| `web/app.js`(视图切换)、`web/product-v4.css`(`.page-context`) | 按视图是否自带页头切换 `body.view-has-heading`,隐藏重复的顶栏标题 |
+| `web/app/assistant-settings.js`、`web/app/assistant-settings.css` | AI 助手设置页的开关、自定义规则与保存 |
| `web/app/bots.js`、`web/bots.css` | Bot 管理页的面板头(标签 / 面包屑)、列表行、状态徽标、引导编辑器与记录 |
| `web/app/hui-controls.css` | Selector 面板,复选 / 单选 / 开关,确认对话框,日期浮层,上传区和 Tooltip 样式 |
| `web/app/hui-date.js`、`hui-upload.js`、`hui-tooltip.js` | 日期浮层、上传拖拽区、`title` 接管的 Tooltip |
diff --git a/e2e/api/70-assistant-proposals.test.mjs b/e2e/api/70-assistant-proposals.test.mjs
new file mode 100644
index 00000000..297e0305
--- /dev/null
+++ b/e2e/api/70-assistant-proposals.test.mjs
@@ -0,0 +1,110 @@
+// SOP proposals and AI assistant preferences against a real MySQL platform.
+import {test, before, after} from 'node:test';
+import assert from 'node:assert/strict';
+import {api, get, post, put, del, track, cleanup, ensureProject} from '../lib/api.mjs';
+import {cfg, uid} from '../lib/env.mjs';
+
+before(ensureProject);
+after(cleanup);
+
+function proposalSession(draft) {
+ return {
+ projectId: cfg.projectId,
+ title: 'SOP proposal',
+ messages: [
+ {role: 'user', content: '做一个积分排行榜'},
+ {role: 'assistant', content: JSON.stringify({message: '建议走 SOP', drafts: [draft]})},
+ ],
+ };
+}
+
+const startProposal = {
+ tool: 'issues_dispatch',
+ path: {id: 'issue-1'},
+ proposal: {reason: '整件需求走 SOP', timing: 'start'},
+};
+
+test('assistant preferences persist and reject an oversized rule', async () => {
+ const initial = await get('/api/assistant/preferences');
+ assert.equal(initial.proactiveRoles, false);
+ assert.equal(initial.proactiveSops, false);
+ const saved = await put('/api/assistant/preferences', {
+ proactiveRoles: true,
+ proactiveSops: false,
+ instructions: '回复先给结论',
+ });
+ assert.equal(saved.proactiveRoles, true);
+ assert.equal(saved.proactiveSops, false);
+ assert.equal(saved.instructions, '回复先给结论');
+ const again = await get('/api/assistant/preferences');
+ assert.deepEqual(
+ {proactiveRoles: again.proactiveRoles, proactiveSops: again.proactiveSops, instructions: again.instructions},
+ {proactiveRoles: true, proactiveSops: false, instructions: '回复先给结论'},
+ );
+ await api('PUT', '/api/assistant/preferences', {proactiveRoles: false, proactiveSops: false, instructions: '字'.repeat(4001)}, {expect: 400});
+ const kept = await get('/api/assistant/preferences');
+ assert.equal(kept.instructions, '回复先给结论');
+ await put('/api/assistant/preferences', {proactiveRoles: false, proactiveSops: false, instructions: ''});
+});
+
+test('declining a start proposal returns one follow-up and then stays closed', async () => {
+ const id = uid('proposal');
+ track(`session ${id}`, () => del(`/api/assistant/sessions/${id}`));
+ await put(`/api/assistant/sessions/${id}`, proposalSession(startProposal));
+ const declined = await post(`/api/assistant/sessions/${id}/proposals`, {
+ messageIndex: 1,
+ draftIndex: 0,
+ decision: 'declined',
+ });
+ assert.equal(declined.followUp.text, '不走 SOP,这件事由你直接完成。');
+ assert.equal(JSON.parse(declined.session.messages[1].content).drafts[0].decision, 'declined');
+ await api('POST', `/api/assistant/sessions/${id}/proposals`, {
+ messageIndex: 1,
+ draftIndex: 0,
+ decision: 'accepted',
+ }, {expect: 409});
+});
+
+test('accepting a proposal records the decision without a follow-up', async () => {
+ const id = uid('proposal');
+ track(`session ${id}`, () => del(`/api/assistant/sessions/${id}`));
+ await put(`/api/assistant/sessions/${id}`, proposalSession(startProposal));
+ const accepted = await post(`/api/assistant/sessions/${id}/proposals`, {
+ messageIndex: 1,
+ draftIndex: 0,
+ decision: 'accepted',
+ });
+ assert.equal(accepted.followUp, null);
+ assert.equal(JSON.parse(accepted.session.messages[1].content).drafts[0].decision, 'accepted');
+});
+
+test('muting an optional proposal does not continue the turn, and a plain draft is rejected', async () => {
+ const id = uid('proposal');
+ track(`session ${id}`, () => del(`/api/assistant/sessions/${id}`));
+ await put(`/api/assistant/sessions/${id}`, proposalSession({
+ tool: 'issues_save',
+ body: {projectId: cfg.projectId, title: '积分排行榜', kind: 'requirement', workflowId: 'delivery'},
+ proposal: {reason: '可选的后续工作', timing: 'end'},
+ }));
+ const muted = await post(`/api/assistant/sessions/${id}/proposals`, {
+ messageIndex: 1,
+ draftIndex: 0,
+ decision: 'muted',
+ });
+ assert.equal(muted.followUp, null);
+ assert.equal(JSON.parse(muted.session.messages[1].content).drafts[0].decision, 'muted');
+
+ const plain = uid('proposal');
+ track(`session ${plain}`, () => del(`/api/assistant/sessions/${plain}`));
+ await put(`/api/assistant/sessions/${plain}`, proposalSession({tool: 'issues_dispatch', path: {id: 'issue-1'}}));
+ await api('POST', `/api/assistant/sessions/${plain}/proposals`, {
+ messageIndex: 1,
+ draftIndex: 0,
+ decision: 'declined',
+ }, {expect: 400});
+ await api('POST', `/api/assistant/sessions/${id}/proposals`, {
+ messageIndex: 1,
+ draftIndex: 0,
+ decision: 'nope',
+ }, {expect: 400});
+});
diff --git a/e2e/ui/01-views.spec.mjs b/e2e/ui/01-views.spec.mjs
index f2a0a548..cca7c08f 100644
--- a/e2e/ui/01-views.spec.mjs
+++ b/e2e/ui/01-views.spec.mjs
@@ -6,7 +6,7 @@ import { test, expect, watchErrors } from './fixtures.mjs';
// Keep in sync with viewTitles() in web/app.js; a renamed or dropped view is
// a visible product change the suite should notice.
const TITLES = {
- collaboration: 'AI 工作台', issues: '需求列表', aiSchedules: '定时任务', bots: '通道管理', runs: '运行记录',
+ collaboration: 'AI 工作台', issues: '需求列表', aiSchedules: '定时任务', bots: '通道管理', assistant: 'AI 助手', runs: '运行记录',
approvals: '待我确认', sops: '流程模板', flow: '流程设计', agents: '角色定义', mcp: '能力资产', rules: '能力资产', skills: '能力资产',
dockerfiles: '环境资产', environments: '环境资产', sandboxes: '环境资产', observability: '统计', projects: '项目配置',
platform: '平台管理', runners: '执行机器', settings: '个人配置', guide: '访问密钥',
diff --git a/internal/domain/assistant_generation.go b/internal/domain/assistant_generation.go
index dc6d7737..46b962aa 100644
--- a/internal/domain/assistant_generation.go
+++ b/internal/domain/assistant_generation.go
@@ -42,6 +42,8 @@ type AssistantSteer struct {
ApprovalMode string `json:"approvalMode,omitempty"`
ActorID int64 `json:"actorId,omitempty"`
ActorName string `json:"actorName,omitempty"`
+ // Trigger marks the follow-up message; empty means the user steered.
+ Trigger string `json:"trigger,omitempty"`
}
// A bounded projection survives eviction of old token events and reconnects.
diff --git a/internal/domain/assistant_preferences.go b/internal/domain/assistant_preferences.go
new file mode 100644
index 00000000..69e94c2e
--- /dev/null
+++ b/internal/domain/assistant_preferences.go
@@ -0,0 +1,16 @@
+package domain
+
+import "time"
+
+// AssistantPreferencesInstructionsMax caps the user's own rules for Main Bot.
+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.
+type AssistantPreferences struct {
+ ProactiveRoles bool `json:"proactiveRoles"`
+ ProactiveSOPs bool `json:"proactiveSops"`
+ Instructions string `json:"instructions"`
+ UpdatedAt time.Time `json:"updatedAt,omitempty"`
+}
diff --git a/internal/domain/assistant_proposal.go b/internal/domain/assistant_proposal.go
new file mode 100644
index 00000000..e5c6cc18
--- /dev/null
+++ b/internal/domain/assistant_proposal.go
@@ -0,0 +1,12 @@
+package domain
+
+const (
+ AssistantProposalAccepted = "accepted"
+ AssistantProposalDeclined = "declined"
+ // AssistantProposalMuted declines and turns proposals off for the rest
+ // of the conversation.
+ AssistantProposalMuted = "muted"
+ // AssistantProposalExpired means nobody answered a blocking proposal in
+ // time and Main Bot went on to do the work itself.
+ AssistantProposalExpired = "expired"
+)
diff --git a/internal/httpapi/agent_tool_mcp.go b/internal/httpapi/agent_tool_mcp.go
index 83bae6ff..69df4c4d 100644
--- a/internal/httpapi/agent_tool_mcp.go
+++ b/internal/httpapi/agent_tool_mcp.go
@@ -261,6 +261,12 @@ func (h *agentToolGateway) callTerminal(session *AgentToolSession, name string,
logAgentToolEvent("terminal-invalid", "mode="+string(session.Mode), "tool="+name, "err="+truncateRunes(err.Error(), 160))
return mcpToolTextResult("草稿参数校验失败,本轮继续;请按以下错误修正后重新提交,不代表工具不可用:"+err.Error(), true), nil
}
+ if h.deps != nil && h.repo != nil {
+ if err := h.assistant().vetProposalDrafts(session, &reply); err != nil {
+ logAgentToolEvent("terminal-invalid", "mode="+string(session.Mode), "tool="+name, "err="+truncateRunes(err.Error(), 160))
+ return mcpToolTextResult("派发建议未提交,本轮继续:"+err.Error(), true), nil
+ }
+ }
if len(reply.Drafts) == 0 {
// This tool ends the model process. Accepting a progress message here
// used to kill sibling read calls before a requested SOP was prepared.
diff --git a/internal/httpapi/agent_tool_native_terminal_test.go b/internal/httpapi/agent_tool_native_terminal_test.go
index 00ae83cd..4226058e 100644
--- a/internal/httpapi/agent_tool_native_terminal_test.go
+++ b/internal/httpapi/agent_tool_native_terminal_test.go
@@ -35,7 +35,7 @@ func TestAssistantProgressSubmissionCannotEndToolExecution(t *testing.T) {
if _, err := gateway.callTool(context.Background(), session, json.RawMessage(`{"name":"workbench_tool_schema","arguments":{"name":"issues_dispatch"}}`)); err != nil {
t.Fatalf("cannot continue querying after rejected progress: %v", err)
}
- result, err = gateway.callTerminal(session, submitAssistantReplyTool, json.RawMessage(`{"message":"已核对需求,确认后派发。","drafts":[{"tool":"issues_dispatch","path":{"id":"workbench-issue"}}]}`))
+ result, err = gateway.callTerminal(session, submitAssistantReplyTool, json.RawMessage(`{"message":"已核对需求,确认后派发。","drafts":[{"tool":"issues_dispatch","path":{"id":"workbench-issue"},"proposal":{"reason":"整件需求走 SOP","timing":"start"}}]}`))
if err != nil || result["isError"] == true || !session.finished() || !cancelled {
t.Fatalf("valid draft did not finish: result=%v err=%v", result, err)
}
diff --git a/internal/httpapi/agent_tool_session.go b/internal/httpapi/agent_tool_session.go
index 08f48030..b26f55e7 100644
--- a/internal/httpapi/agent_tool_session.go
+++ b/internal/httpapi/agent_tool_session.go
@@ -60,8 +60,12 @@ type AgentToolSession struct {
RunID string
// ChatSessionID/ChatOwnerID identify the ordinary conversation this turn
// belongs to, so Main Bot can open and bind a temporary workspace there.
- ChatSessionID string
- ChatOwnerID int64
+ ChatSessionID string
+ ChatOwnerID int64
+ // turnMessages is the transcript this chat request is sending. A new
+ // personal session is stored only after the reply, so proposal checks
+ // read the request before the saved session.
+ turnMessages []assistantMessage
SandboxProfileID string
// workspaceRunID is the one workspace an ordinary conversation is bound
// to: one it opened itself, or the SOP run of an issue.
diff --git a/internal/httpapi/agent_tool_terminal.go b/internal/httpapi/agent_tool_terminal.go
index 5c6818d8..c393bec5 100644
--- a/internal/httpapi/agent_tool_terminal.go
+++ b/internal/httpapi/agent_tool_terminal.go
@@ -46,7 +46,7 @@ func terminalToolDescriptors(mode AgentToolMode, exec assistantExecMode) []agent
UpstreamName: submitClarificationTool,
}}
case AgentToolAssistant:
- schema, _ := json.Marshal(submitAssistantReplySchema())
+ schema, _ := json.Marshal(submitAssistantReplySchema(exec))
return []agentToolDescriptor{{
Name: submitAssistantReplyTool,
Description: submitAssistantReplyDescription(exec),
@@ -105,7 +105,9 @@ func submitClarificationSchema() map[string]any {
}
}
-func submitAssistantReplySchema() map[string]any {
+// submitAssistantReplySchema offers SOP proposals only where the user
+// answers them: full access starts a SOP without asking.
+func submitAssistantReplySchema(exec assistantExecMode) map[string]any {
names := assistantWriteToolNameList()
toolSchema := map[string]any{"type": "string", "description": "必填:本草稿要执行的写入工具名称,如 issues_save、issues_dispatch;不要省略,不带 mcp__ 前缀"}
if len(names) > 0 {
@@ -116,6 +118,15 @@ func submitAssistantReplySchema() map[string]any {
enum = append(enum, "assistant_tasks_save")
toolSchema["enum"] = enum
}
+ draft := map[string]any{
+ "tool": toolSchema,
+ "path": map[string]any{"type": "object"},
+ "query": map[string]any{"type": "object"},
+ "body": map[string]any{},
+ }
+ if !exec.AutoWrite || exec.ReviewWrites {
+ draft["proposal"] = assistantProposalSchema()
+ }
return map[string]any{
"type": "object",
"additionalProperties": false,
@@ -130,12 +141,7 @@ func submitAssistantReplySchema() map[string]any {
"type": "object",
"additionalProperties": false,
"required": []string{"tool"},
- "properties": map[string]any{
- "tool": toolSchema,
- "path": map[string]any{"type": "object"},
- "query": map[string]any{"type": "object"},
- "body": map[string]any{},
- },
+ "properties": draft,
},
},
},
diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go
index c1c065be..2159f44e 100644
--- a/internal/httpapi/assistant.go
+++ b/internal/httpapi/assistant.go
@@ -34,6 +34,10 @@ type assistantDraft struct {
Warnings []string `json:"warnings,omitempty"`
SaveError string `json:"saveError,omitempty"`
Review *assistantApprovalReview `json:"review,omitempty"`
+ // Proposal marks a draft the assistant offers on its own to hand work to a
+ // SOP; Decision is the server-recorded answer to it.
+ Proposal *assistantProposal `json:"proposal,omitempty"`
+ Decision string `json:"decision,omitempty"`
}
type assistantReply struct {
SpeakerName string `json:"speakerName,omitempty"`
@@ -251,6 +255,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {
sess.RunID = req.RunID
sess.ChatSessionID = req.SessionID
sess.ChatOwnerID = ownerID
+ sess.turnMessages = append([]assistantMessage(nil), req.Messages...)
if saved, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {
sess.SandboxProfileID = saved.SandboxProfileID
}
@@ -541,6 +546,11 @@ func (h *assistantHandlers) chat(c *gin.Context) {
draftCtx = withConversationSession(ctx, req.SessionID)
}
reply.Drafts = h.resolveAssistantDrafts(draftCtx, user, req.ProjectID, reply.Drafts, approvalMode)
+ var deadline time.Time
+ if sink != nil && req.RunID == "" {
+ deadline = time.Now().Add(assistantProposalTimeout)
+ }
+ stampProposalDeadlines(reply.Drafts, deadline)
}
{
stored := append([]assistantMessage{}, req.Messages...)
@@ -564,6 +574,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {
saveErr = saveAssistantConversation(h.repo, ownerID, conversation)
}
if saveErr != nil {
+ log.Printf("assistant save session=%s: %v", req.SessionID, saveErr)
fail(500, "保存对话失败,请重试")
return
}
@@ -953,6 +964,9 @@ func validateAssistantDraft(d *assistantDraft, projectID string) error {
if d.Tool == "" {
return errors.New("drafts 中每个草稿都必须提供 tool 字段,例如 tool=issues_save 或 tool=issues_dispatch;同时保留对应的 body/path/query 参数")
}
+ if err := validateAssistantProposal(d); err != nil {
+ return err
+ }
if d.Tool == "assistant_tasks_save" {
var task assistantTask
if json.Unmarshal(d.Body, &task) != nil || strings.TrimSpace(task.Name) == "" || strings.TrimSpace(task.Prompt) == "" {
diff --git a/internal/httpapi/assistant_approval.go b/internal/httpapi/assistant_approval.go
index 398627f4..f65e8a18 100644
--- a/internal/httpapi/assistant_approval.go
+++ b/internal/httpapi/assistant_approval.go
@@ -64,6 +64,7 @@ func (h *assistantHandlers) resolveAssistantDrafts(ctx context.Context, user dom
for _, draft := range drafts {
// Review receipts are host-generated, never accepted from model output.
draft.Review = nil
+ draft.Decision = ""
draft.Body = injectAssistantDraftProjectID(draft.Tool, draft.Body, projectID)
draft.Warnings = h.assistantDraftWarnings(draft)
// 存在警告(依赖冲突、节点未绑定角色等必然失败或残缺)的草稿,
diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.go
index bc741428..19a9cefd 100644
--- a/internal/httpapi/assistant_generation.go
+++ b/internal/httpapi/assistant_generation.go
@@ -366,6 +366,8 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assist
rec.live.publish()
if steer != nil {
h.followSteer(parent, g, steer, actor)
+ } else if g.Status == "completed" {
+ h.expireProposalLater(parent, g, req, actor)
}
}
@@ -461,7 +463,7 @@ func (h *assistantHandlers) commitTurnTranscript(g domain.AssistantGeneration, s
}
last := len(session.Messages) - 1
if last < 0 || session.Messages[last].Role != "user" || session.Messages[last].Content != content {
- session.Messages = append(session.Messages, domain.AssistantMessage{Role: "user", Content: content, AuthorID: steer.ActorID, AuthorName: steer.ActorName, CreatedAt: time.Now().UTC(), Attachments: steer.Attachments, References: steer.References, Trigger: "steer"})
+ session.Messages = append(session.Messages, domain.AssistantMessage{Role: "user", Content: content, AuthorID: steer.ActorID, AuthorName: steer.ActorName, CreatedAt: time.Now().UTC(), Attachments: steer.Attachments, References: steer.References, Trigger: firstNonEmpty(steer.Trigger, "steer")})
changed = true
}
}
diff --git a/internal/httpapi/assistant_preferences.go b/internal/httpapi/assistant_preferences.go
new file mode 100644
index 00000000..7320133e
--- /dev/null
+++ b/internal/httpapi/assistant_preferences.go
@@ -0,0 +1,39 @@
+package httpapi
+
+import (
+ "fmt"
+ "unicode/utf8"
+
+ "github.com/gin-gonic/gin"
+
+ "agentflow/internal/domain"
+)
+
+// preferences handles GET/PUT /api/assistant/preferences: the signed-in
+// user's Main Bot settings.
+func (h *assistantHandlers) preferences(c *gin.Context) {
+ user, ok := h.requestUser(c.Request, true)
+ if !ok || user.ID <= 0 {
+ c.JSON(401, gin.H{"error": "请先登录"})
+ return
+ }
+ if c.Request.Method == "GET" {
+ c.JSON(200, h.repo.AssistantPreferences(user.ID))
+ return
+ }
+ var body domain.AssistantPreferences
+ if err := c.ShouldBindJSON(&body); err != nil {
+ c.JSON(400, gin.H{"error": "设置格式不正确"})
+ return
+ }
+ if utf8.RuneCountInString(body.Instructions) > domain.AssistantPreferencesInstructionsMax {
+ c.JSON(400, gin.H{"error": fmt.Sprintf("自定义规则最多 %d 字", domain.AssistantPreferencesInstructionsMax)})
+ return
+ }
+ saved, err := h.repo.PutAssistantPreferences(user.ID, body)
+ if err != nil {
+ c.JSON(500, gin.H{"error": "保存设置失败,请重试"})
+ return
+ }
+ c.JSON(200, saved)
+}
diff --git a/internal/httpapi/assistant_proposals.go b/internal/httpapi/assistant_proposals.go
new file mode 100644
index 00000000..c732b66c
--- /dev/null
+++ b/internal/httpapi/assistant_proposals.go
@@ -0,0 +1,547 @@
+package httpapi
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "agentflow/internal/auth"
+ "agentflow/internal/domain"
+)
+
+const (
+ assistantProposalStart = "start"
+ assistantProposalEnd = "end"
+
+ assistantProposalReasonMax = 500
+)
+
+// assistantProposal marks a draft Main Bot submits on its own to hand work to
+// a SOP. Roles never need one: Main Bot dispatches them directly.
+type assistantProposal struct {
+ Reason string `json:"reason"`
+ // Timing is start when the whole request belongs to the SOP and Main Bot
+ // asks before doing the work, end when Main Bot finished its part and
+ // offers follow-up work the turn does not depend on.
+ Timing string `json:"timing"`
+ // ExpiresAt is when an unanswered timing=start proposal hands the work
+ // back to Main Bot. Host-stamped; model output never sets it.
+ ExpiresAt *time.Time `json:"expiresAt,omitempty"`
+}
+
+func assistantProposalSchema() map[string]any {
+ return map[string]any{
+ "type": "object",
+ "additionalProperties": false,
+ "required": []string{"reason", "timing"},
+ "description": "走 SOP 的建议:用户没 @ SOP、也没点名要走 SOP 或完整流程,是你自己决定交给 SOP(绑定 SOP 新建需求的 issues_save、issues_dispatch、runs_start)时必填;用户明确要求时不填",
+ "properties": map[string]any{
+ "reason": map[string]any{"type": "string", "description": "一句话说明为什么这件事走 SOP 更合适"},
+ "timing": map[string]any{"type": "string", "enum": []string{assistantProposalStart, assistantProposalEnd}, "description": "start:整件事走 SOP、你还没开始做;end:你已做完自己的部分,这是可选的后续工作"},
+ },
+ }
+}
+
+// assistantSOPDraft reports whether a draft hands work to a SOP: dispatching
+// an issue, starting a run, or a new requirement bound to a SOP, which is how
+// the SOP route starts when the requirement does not exist yet.
+func assistantSOPDraft(d assistantDraft) bool {
+ switch d.Tool {
+ case "issues_dispatch", "runs_start":
+ return true
+ case "issues_save":
+ var body struct {
+ ID string `json:"id"`
+ }
+ _ = json.Unmarshal(d.Body, &body)
+ return strings.TrimSpace(body.ID) == "" && assistantProposalTarget(d) != ""
+ default:
+ return false
+ }
+}
+
+func validateAssistantProposal(d *assistantDraft) error {
+ if d.Proposal != nil && !assistantSOPDraft(*d) {
+ d.Proposal = nil
+ }
+ if d.Proposal == nil {
+ return nil
+ }
+ d.Proposal.Reason = truncateRunes(strings.TrimSpace(d.Proposal.Reason), assistantProposalReasonMax)
+ d.Proposal.Timing = strings.TrimSpace(d.Proposal.Timing)
+ if d.Proposal.Timing != assistantProposalStart && d.Proposal.Timing != assistantProposalEnd {
+ return fmt.Errorf("proposal.timing 只能是 start 或 end")
+ }
+ if d.Proposal.Reason == "" {
+ return fmt.Errorf("proposal.reason 不能为空,用一句话说明为什么走 SOP 更合适")
+ }
+ return nil
+}
+
+// assistantProposalTarget names what a proposal hands the work to: the issue
+// whose SOP it dispatches, or the SOP it starts or binds.
+func assistantProposalTarget(d assistantDraft) string {
+ if d.Tool == "issues_dispatch" {
+ return assistantPathValue(d.Path, "id")
+ }
+ var body struct {
+ WorkflowID string `json:"workflowId"`
+ }
+ _ = json.Unmarshal(d.Body, &body)
+ return strings.TrimSpace(body.WorkflowID)
+}
+
+// assistantProposalHistory is what the transcript says about earlier
+// proposals: whether the user turned them off and in which message, which
+// ones were declined, whether an optional add-on was ever declined, and
+// whether the latest answered one was taken.
+type assistantProposalHistory struct {
+ Muted bool
+ MutedAt int
+ DeclinedEnd bool
+ Accepted bool
+ Declined map[string]string
+}
+
+func proposalHistory(messages []assistantMessage) assistantProposalHistory {
+ out := assistantProposalHistory{MutedAt: -1, Declined: map[string]string{}}
+ for i, message := range messages {
+ if message.Role != "assistant" {
+ continue
+ }
+ var reply struct {
+ Drafts []assistantDraft `json:"drafts"`
+ }
+ if json.Unmarshal([]byte(message.Content), &reply) != nil {
+ continue
+ }
+ for _, d := range reply.Drafts {
+ if d.Proposal == nil {
+ continue
+ }
+ switch d.Decision {
+ case domain.AssistantProposalAccepted:
+ out.Accepted = true
+ case "":
+ // 帮我批准 runs an approved proposal without anyone answering it.
+ if d.Saved {
+ out.Accepted = true
+ }
+ case domain.AssistantProposalMuted:
+ out.Muted, out.MutedAt = true, i
+ fallthrough
+ case domain.AssistantProposalDeclined:
+ out.Accepted = false
+ out.Declined[assistantProposalTarget(d)] = assistantProposalLabel(d)
+ out.DeclinedEnd = out.DeclinedEnd || d.Proposal.Timing == assistantProposalEnd
+ case domain.AssistantProposalExpired:
+ // Main Bot already took this one over; asking again would
+ // block the conversation a second time.
+ out.Accepted = false
+ out.Declined[assistantProposalTarget(d)] = assistantProposalLabel(d)
+ }
+ }
+ }
+ return out
+}
+
+func assistantProposalLabel(d assistantDraft) string {
+ if d.Tool == "issues_dispatch" {
+ return "派发需求 " + assistantProposalTarget(d) + " 的 SOP"
+ }
+ return "启动 SOP " + assistantProposalTarget(d)
+}
+
+// delegationContext tells Main Bot when to hand work to a role or a SOP on
+// its own, only for what the user turned on in the AI 助手 settings, and,
+// whenever the project has SOPs, that outside full access a SOP it picks
+// itself needs the user's or the reviewer's consent. Roles are always
+// dispatched directly.
+func delegationContext(req *assistantRequest, prefs domain.AssistantPreferences, mode string, hasSOP bool) string {
+ if strings.TrimSpace(req.ProjectID) == "" {
+ return ""
+ }
+ var b strings.Builder
+ if prefs.ProactiveRoles || prefs.ProactiveSOPs {
+ b.WriteString(assistantDelegationHeading)
+ b.WriteString(assistantDelegationSelf)
+ b.WriteString(assistantDelegationSkill)
+ if prefs.ProactiveRoles {
+ b.WriteString(assistantDelegationRole)
+ b.WriteString(assistantDelegationRoleCheck)
+ }
+ if prefs.ProactiveSOPs {
+ b.WriteString(assistantDelegationSOP)
+ if mode == AssistantApprovalAuto {
+ b.WriteString(assistantDelegationSOPAuto)
+ }
+ }
+ }
+ if mode == AssistantApprovalAuto || !hasSOP {
+ return b.String()
+ }
+ b.WriteString("## 交给 SOP 前先征得同意\n")
+ if mode == AssistantApprovalAssisted {
+ b.WriteString("当前是帮我批准:你自己决定走 SOP 时也直接调用写入工具,由独立 AI 审查这件事是否该走 SOP,通过才执行;未通过转成草稿时,按下面的规则带上 proposal 交给用户确认。\n")
+ }
+ b.WriteString(assistantProposalRules)
+ history := proposalHistory(req.Messages)
+ if history.Muted {
+ b.WriteString("用户已在本会话关闭 SOP 建议:不要再提交任何带 proposal 的草稿,自己完成用户的请求。\n")
+ } else if len(history.Declined) > 0 {
+ labels := make([]string, 0, len(history.Declined))
+ for _, label := range history.Declined {
+ labels = append(labels, label)
+ }
+ b.WriteString("用户在本会话拒绝过这些建议,不要再提:" + strings.Join(labels, "、") + "。\n")
+ if history.DeclinedEnd {
+ b.WriteString("用户在本会话拒绝过 timing=end 的后续建议:不要再提任何 timing=end 建议。\n")
+ }
+ }
+ return b.String()
+}
+
+// assistantInstructionsContext carries the user's own rules for Main Bot.
+func assistantInstructionsContext(prefs domain.AssistantPreferences) string {
+ text := strings.TrimSpace(prefs.Instructions)
+ if text == "" {
+ return ""
+ }
+ return "## 用户给你的自定义规则\n以下是用户在「AI 助手」设置里写的规则,在不违反平台规则和审批模式的前提下照做:\n" + text + "\n"
+}
+
+const (
+ assistantDelegationHeading = "## 自己做、用技能,还是交给角色或 SOP\n"
+ assistantDelegationSelf = "- 默认自己做:问答、解释、只读查询、小范围改动,以及用户说了“你来做”“直接改”的事。\n"
+ assistantDelegationSkill = "- 技能:任务和某个技能的描述对得上时,先用 Skill 工具加载它,照它的说明做;加载技能不需要用户确认。\n"
+ assistantDelegationRole = "- 派角色:用户要的整件事就是某个角色的本职(如独立评审、整套测试),且工作量不小;你这轮改了代码,改动碰到资金/积分、并发、鉴权权限、数据迁移或对外接口这类出错代价高的地方,需要评审或测试角色独立复核;有几块互不依赖的工作可以并行。符合时直接用 Agent 工具派给对应的子 Agent,不用征求同意;派发前用一句话告诉用户交给了谁、为什么。\n"
+ assistantDelegationRoleCheck = "- 收尾检查:回复前看一眼——这轮改了上面说的高风险代码、项目里又有评审或测试角色时,先用 Agent 工具派它独立复核(prompt 写清仓库、改动文件和要重点复核的点),核对它的结论后一起汇报;否则照常回复。\n"
+ assistantDelegationSOP = "- 走 SOP:用户提的是一条要落到仓库的新需求或新功能(不是修 bug、不是小改动),且项目里有用途对得上的 SOP;用户说“推进/交付/做这个需求”就属于这种。动手实现前先交给 SOP,不要自己做完再说。\n"
+ assistantDelegationSOPAuto = "当前是完全权限:走 SOP 时直接调用写入工具(需求还没建时用绑定 SOP 的 issues_save,已存在时用 issues_dispatch),在回复里说明交给了哪个 SOP、为什么。\n"
+
+ assistantProposalRules = `用户没 @ SOP、也没点名要走 SOP 或完整流程时,你自己决定交给 SOP 的事是建议,要在 drafts 里提交并带 proposal={reason, timing}:需求还没建时提交绑定 SOP 的 issues_save(body 带 workflowId),这张卡就是建议;需求已存在时提交 issues_dispatch。用户接受后,后续派发就是用户要的操作,不再带 proposal。
+- 只说“推进”“交付”“实现这个需求”不算点名。
+- timing=start:整件事就该走 SOP、自己做不划算。只做判断所需的少量只读查询,然后立刻提交,不要先做半天再问。确认时限由卡片展示,message 里不要提。
+- timing=end:先把自己能做的做完并在 message 里汇报,再把可选的后续 SOP 作为建议提交;用户不点也不影响本轮交付。
+- 不要在做到一半时提交建议;每轮最多一个;问答、只读查询和小改动不建议。
+- 用户拒绝 timing=start 的建议时,下一轮由你自己完成。
+`
+)
+
+// vetProposalDrafts makes Main Bot ask before a SOP the user did not ask
+// for, outside full access, and rejects proposals the conversation no longer
+// accepts, before submit_assistant_reply ends the turn.
+func (h *assistantHandlers) vetProposalDrafts(session *AgentToolSession, reply *assistantReply) error {
+ if session.ExecMode.AutoWrite && !session.ExecMode.ReviewWrites {
+ return nil
+ }
+ var messages []assistantMessage
+ var history *assistantProposalHistory
+ load := func() *assistantProposalHistory {
+ if history == nil {
+ // Prefer the request. A new personal session is stored after the
+ // reply, so an SOP the user just named is only here.
+ messages = append([]assistantMessage(nil), session.turnMessages...)
+ if len(messages) == 0 {
+ if conv, ok := h.repo.AssistantSession(session.ChatOwnerID, session.ChatSessionID); ok {
+ messages = conv.Messages
+ }
+ }
+ loaded := proposalHistory(messages)
+ history = &loaded
+ }
+ return history
+ }
+ for i := range reply.Drafts {
+ d := &reply.Drafts[i]
+ if !assistantSOPDraft(*d) {
+ continue
+ }
+ if d.Proposal == nil {
+ // Only what the user said after turning proposals off counts.
+ if h.sopRequested(session.ProjectID, messages[load().MutedAt+1:]) {
+ continue
+ }
+ if history.Muted {
+ return errors.New("用户已关闭本会话的 SOP 建议,之后也没点名要走 SOP:自己完成用户的请求")
+ }
+ if history.Accepted {
+ continue
+ }
+ return fmt.Errorf("用户没有 @ SOP 也没点名要走 SOP,%s 这张卡是你的建议:给它带上 proposal={reason, timing:\"start\"},用户可以选择让你自己做", d.Tool)
+ }
+ load()
+ if history.Muted {
+ return errors.New("用户已关闭本会话的 SOP 建议:自己完成用户的请求;如果用户本轮明确要求走 SOP,请他用 @SOP 发起")
+ }
+ if _, declined := history.Declined[assistantProposalTarget(*d)]; declined {
+ return errors.New("用户在本会话已拒绝过这条建议,不要再提:自己完成,或换一种做法")
+ }
+ if history.DeclinedEnd && d.Proposal.Timing == assistantProposalEnd {
+ return errors.New("用户在本会话拒绝过后续建议,不要再提 timing=end 建议:把草稿去掉,直接回复本轮结果")
+ }
+ }
+ return nil
+}
+
+// sopRequested reports whether the user asked for an SOP in this
+// conversation: by @-mentioning one, or by naming SOP, the full process, or
+// one of the project's SOPs.
+func (h *assistantHandlers) sopRequested(projectID string, messages []assistantMessage) bool {
+ names := []string{"sop", "完整流程", "走流程"}
+ for _, wf := range h.repo.Workflows() {
+ if wf.ProjectID == projectID {
+ names = append(names, strings.ToLower(wf.ID), strings.ToLower(wf.Name))
+ }
+ }
+ for _, m := range messages {
+ if m.Role != "user" || m.Trigger != "" {
+ continue
+ }
+ for _, ref := range m.References {
+ if ref.Type == "sop" {
+ return true
+ }
+ }
+ text := strings.ToLower(m.Content)
+ for _, name := range names {
+ if name != "" && assistantMentionsUnnegated(text, name) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// assistantNegationWindow is how many runes before a mention are checked
+// for a negation, so "不要走 SOP" does not count as asking for one.
+const assistantNegationWindow = 6
+
+func assistantMentionsUnnegated(text, name string) bool {
+ for from := 0; ; {
+ at := strings.Index(text[from:], name)
+ if at < 0 {
+ return false
+ }
+ at += from
+ before := []rune(text[:at])
+ if len(before) > assistantNegationWindow {
+ before = before[len(before)-assistantNegationWindow:]
+ }
+ if !strings.ContainsAny(string(before), "不别勿免") && !strings.Contains(string(before), "无需") && !strings.Contains(string(before), "没必要") {
+ return true
+ }
+ from = at + len(name)
+ }
+}
+
+type assistantProposalFollowUp struct {
+ Text string `json:"text"`
+}
+
+// decideProposal records the user's answer to a proposal card. The card
+// accepts before it runs its operation, so a timeout that already handed the
+// work to Main Bot makes the accept fail instead of doing it twice; declining
+// a timing=start proposal returns the turn the client sends next.
+func (h *assistantHandlers) decideProposal(c *gin.Context) {
+ user, ok := h.requestUser(c.Request, true)
+ if !ok {
+ c.JSON(401, gin.H{"error": "请先登录"})
+ return
+ }
+ id := strings.TrimSpace(c.Param("id"))
+ ownerID, shared, err := h.conversationScope(c, id, "", "", user.ID)
+ if err != nil {
+ c.JSON(403, gin.H{"error": err.Error()})
+ return
+ }
+ var body struct {
+ MessageIndex int `json:"messageIndex"`
+ DraftIndex int `json:"draftIndex"`
+ Decision string `json:"decision"`
+ }
+ if !decode(c, &body) {
+ return
+ }
+ switch body.Decision {
+ case domain.AssistantProposalAccepted, domain.AssistantProposalDeclined, domain.AssistantProposalMuted:
+ default:
+ c.JSON(400, gin.H{"error": "未知的处理方式"})
+ return
+ }
+ if job, ok := h.repo.AssistantGeneration(ownerID, id); ok && job.Status == "running" {
+ c.JSON(409, gin.H{"error": "请等待回复结束后再处理建议"})
+ return
+ }
+ existing, err := loadAssistantConversation(h.repo, ownerID, id)
+ if err != nil {
+ c.JSON(404, gin.H{"error": "对话不存在"})
+ return
+ }
+ if body.MessageIndex < 0 || body.MessageIndex >= len(existing.Messages) || existing.Messages[body.MessageIndex].Role != "assistant" {
+ c.JSON(400, gin.H{"error": "建议不存在"})
+ return
+ }
+ var content map[string]any
+ if json.Unmarshal([]byte(existing.Messages[body.MessageIndex].Content), &content) != nil {
+ c.JSON(400, gin.H{"error": "建议不存在"})
+ return
+ }
+ drafts, _ := content["drafts"].([]any)
+ if body.DraftIndex < 0 || body.DraftIndex >= len(drafts) {
+ c.JSON(400, gin.H{"error": "建议不存在"})
+ return
+ }
+ raw, _ := drafts[body.DraftIndex].(map[string]any)
+ encoded, _ := json.Marshal(raw)
+ var draft assistantDraft
+ if raw == nil || json.Unmarshal(encoded, &draft) != nil || draft.Proposal == nil {
+ c.JSON(400, gin.H{"error": "这不是派发建议"})
+ return
+ }
+ if draft.Decision != "" {
+ c.JSON(409, gin.H{"error": "这条建议已经处理过"})
+ return
+ }
+ raw["decision"] = body.Decision
+ next := existing
+ next.Messages = append([]assistantMessage(nil), existing.Messages...)
+ next.Messages[body.MessageIndex].Content = jsonObject(content)
+ var saveErr error
+ if shared {
+ saveErr = h.repo.PutSharedAssistantReceipt(ownerID, next, existing)
+ } else {
+ saveErr = h.repo.PutAssistantSessionIfUnchanged(ownerID, next, existing)
+ }
+ if saveErr != nil {
+ c.JSON(409, gin.H{"error": "会话已更新,请刷新后再处理"})
+ return
+ }
+ stored, err := loadAssistantConversation(h.repo, ownerID, id)
+ if err != nil {
+ c.JSON(500, gin.H{"error": "保存对话失败"})
+ return
+ }
+ var followUp *assistantProposalFollowUp
+ if body.Decision != domain.AssistantProposalAccepted && draft.Proposal.Timing == assistantProposalStart {
+ followUp = &assistantProposalFollowUp{Text: assistantProposalDeclinedText}
+ }
+ c.JSON(200, gin.H{"session": stored, "followUp": followUp})
+}
+
+const assistantProposalDeclinedText = "不走 SOP,这件事由你直接完成。"
+
+// assistantProposalTimeout is how long a timing=start proposal blocks the
+// conversation before Main Bot does the work itself.
+const assistantProposalTimeout = 3 * time.Minute
+
+const (
+ assistantProposalExpiredText = "SOP 建议超时未确认,这件事由你直接完成。"
+ assistantProposalTimeoutTrigger = "proposal_timeout"
+)
+
+// stampProposalDeadlines gives each pending timing=start proposal the
+// deadline its card counts down to; a zero deadline means no timer will run.
+func stampProposalDeadlines(drafts []assistantDraft, deadline time.Time) {
+ for i, d := range drafts {
+ if d.Proposal == nil {
+ continue
+ }
+ p := *d.Proposal
+ p.ExpiresAt = nil
+ if !deadline.IsZero() && p.Timing == assistantProposalStart && d.Decision == "" && !d.Saved {
+ at := deadline.UTC()
+ p.ExpiresAt = &at
+ }
+ drafts[i].Proposal = &p
+ }
+}
+
+// pendingStartProposal finds the timing=start proposal the latest reply is
+// still waiting on.
+func pendingStartProposal(messages []assistantMessage) (messageIndex, draftIndex int, deadline time.Time, ok bool) {
+ last := len(messages) - 1
+ if last < 0 || messages[last].Role != "assistant" {
+ return 0, 0, time.Time{}, false
+ }
+ var reply struct {
+ Drafts []assistantDraft `json:"drafts"`
+ }
+ if json.Unmarshal([]byte(messages[last].Content), &reply) != nil {
+ return 0, 0, time.Time{}, false
+ }
+ for i, d := range reply.Drafts {
+ if d.Proposal != nil && d.Proposal.Timing == assistantProposalStart && d.Proposal.ExpiresAt != nil && d.Decision == "" && !d.Saved {
+ return last, i, *d.Proposal.ExpiresAt, true
+ }
+ }
+ return 0, 0, time.Time{}, false
+}
+
+// expireProposalLater hands an unanswered timing=start proposal back to Main
+// Bot at its deadline, so a task left alone does not stall on
+// a card. Anything the user does first — answering it, sending a message,
+// starting another turn — leaves the conversation as it is.
+func (h *assistantHandlers) expireProposalLater(parent context.Context, g domain.AssistantGeneration, req assistantRequest, actor *auth.User) {
+ session, ok := h.repo.AssistantSession(g.UserID, g.SessionID)
+ if !ok {
+ return
+ }
+ messageIndex, draftIndex, deadline, ok := pendingStartProposal(session.Messages)
+ if !ok {
+ return
+ }
+ time.AfterFunc(time.Until(deadline), func() {
+ done := inflightTasks.Add()
+ defer done()
+ steer := h.expireProposal(g.UserID, g.SessionID, messageIndex, draftIndex, deadline, g.ActorID, g.ActorName)
+ if steer == nil {
+ return
+ }
+ steer.Model, steer.Effort, steer.ApprovalMode = req.Model, req.Effort, req.ApprovalMode
+ h.followSteer(parent, g, steer, actor)
+ })
+}
+
+// expireProposal marks the proposal expired and appends the turn that tells
+// Main Bot to do the work, or returns nil when the conversation moved on —
+// including a regenerated reply whose card is not the one timed.
+func (h *assistantHandlers) expireProposal(ownerID int64, sessionID string, messageIndex, draftIndex int, deadline time.Time, actorID int64, actorName string) *domain.AssistantSteer {
+ session, ok := h.repo.AssistantSession(ownerID, sessionID)
+ if !ok || len(session.Messages) != messageIndex+1 {
+ return nil
+ }
+ var content map[string]any
+ if json.Unmarshal([]byte(session.Messages[messageIndex].Content), &content) != nil {
+ return nil
+ }
+ drafts, _ := content["drafts"].([]any)
+ if draftIndex < 0 || draftIndex >= len(drafts) {
+ return nil
+ }
+ raw, _ := drafts[draftIndex].(map[string]any)
+ if decision, _ := raw["decision"].(string); raw == nil || decision != "" || raw["saved"] == true {
+ return nil
+ }
+ proposal, _ := raw["proposal"].(map[string]any)
+ timing, _ := proposal["timing"].(string)
+ stamped, _ := proposal["expiresAt"].(string)
+ if at, err := time.Parse(time.RFC3339Nano, stamped); timing != assistantProposalStart || err != nil || !at.Equal(deadline) {
+ return nil
+ }
+ raw["decision"] = domain.AssistantProposalExpired
+ steer := &domain.AssistantSteer{Content: assistantProposalExpiredText, ActorID: actorID, ActorName: actorName, Trigger: assistantProposalTimeoutTrigger}
+ next := session
+ next.Messages = append([]assistantMessage(nil), session.Messages...)
+ next.Messages[messageIndex].Content = jsonObject(content)
+ next.Messages = append(next.Messages, assistantMessage{Role: "user", Content: steer.Content, AuthorID: actorID, AuthorName: actorName, CreatedAt: time.Now().UTC(), Trigger: steer.Trigger})
+ if err := h.repo.PutAssistantSessionIfUnchanged(ownerID, next, session); err != nil {
+ return nil
+ }
+ return steer
+}
diff --git a/internal/httpapi/assistant_proposals_test.go b/internal/httpapi/assistant_proposals_test.go
new file mode 100644
index 00000000..d5a5d449
--- /dev/null
+++ b/internal/httpapi/assistant_proposals_test.go
@@ -0,0 +1,536 @@
+package httpapi
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "agentflow/internal/domain"
+)
+
+func proposalReply(t *testing.T, drafts ...assistantDraft) string {
+ t.Helper()
+ raw, err := json.Marshal(map[string]any{"message": "建议走 SOP", "drafts": drafts})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+func sopDraft(issueID, timing string) assistantDraft {
+ return assistantDraft{Tool: "issues_dispatch", Path: map[string]any{"id": issueID}, Body: json.RawMessage(`{}`), Proposal: &assistantProposal{Reason: "整件需求走 SOP", Timing: timing}}
+}
+
+func TestSOPProposalValidation(t *testing.T) {
+ bad := sopDraft("i1", "later")
+ if err := validateAssistantDraft(&bad, "workbench"); err == nil {
+ t.Fatal("an unknown timing was accepted")
+ }
+ role := assistantDraft{Tool: "subagent_dispatch", Body: json.RawMessage(`{"roleId":"dev","task":"做"}`), Proposal: &assistantProposal{Reason: "x", Timing: "start"}}
+ if err := validateAssistantDraft(&role, "workbench"); err == nil {
+ t.Fatal("a role dispatch draft was accepted; roles are dispatched with the Agent tool")
+ }
+ save := assistantDraft{Tool: "issues_save", Body: json.RawMessage(`{"id":"i1","title":"t","projectId":"workbench"}`), Proposal: &assistantProposal{Reason: "x", Timing: "start"}}
+ if err := validateAssistantDraft(&save, "workbench"); err != nil || save.Proposal != nil {
+ t.Fatalf("a proposal on an ordinary write must be dropped: %v %+v", err, save.Proposal)
+ }
+ rebind := assistantDraft{Tool: "issues_save", Body: json.RawMessage(`{"id":"i1","title":"t","projectId":"workbench","workflowId":"sop"}`), Proposal: &assistantProposal{Reason: "x", Timing: "start"}}
+ if err := validateAssistantDraft(&rebind, "workbench"); err != nil || rebind.Proposal != nil {
+ t.Fatalf("binding an existing issue to an SOP is not a proposal: %v %+v", err, rebind.Proposal)
+ }
+ create := assistantDraft{Tool: "issues_save", Body: json.RawMessage(`{"title":"t","projectId":"workbench","workflowId":"sop"}`), Proposal: &assistantProposal{Reason: "整件需求走 SOP", Timing: "start"}}
+ if err := validateAssistantDraft(&create, "workbench"); err != nil || create.Proposal == nil {
+ t.Fatalf("a new requirement bound to an SOP lost its proposal: %v %+v", err, create.Proposal)
+ }
+ if target := assistantProposalTarget(create); target != "sop" {
+ t.Fatalf("target=%s", target)
+ }
+}
+
+func TestVetProposalDraftsFollowsHistory(t *testing.T) {
+ h, u := workbenchFixture(t)
+ session := &AgentToolSession{ProjectID: "workbench", UserID: u.ID, ChatOwnerID: u.ID, ChatSessionID: "vet"}
+ vet := func(d assistantDraft) error {
+ return h.vetProposalDrafts(session, &assistantReply{Drafts: []assistantDraft{d}})
+ }
+ if err := vet(sopDraft("i1", "end")); err != nil {
+ t.Fatal(err)
+ }
+ declined := sopDraft("i1", "end")
+ declined.Decision = domain.AssistantProposalDeclined
+ h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "vet", ProjectID: "workbench", Messages: []domain.AssistantMessage{
+ {Role: "user", Content: "改一下"}, {Role: "assistant", Content: proposalReply(t, declined)},
+ }})
+ if err := vet(sopDraft("i1", "start")); err == nil || !strings.Contains(err.Error(), "拒绝过") {
+ t.Fatalf("a declined proposal was offered again: %v", err)
+ }
+ if err := vet(sopDraft("i2", "end")); err == nil || !strings.Contains(err.Error(), "timing=end") {
+ t.Fatalf("another add-on followed a declined add-on: %v", err)
+ }
+ if err := vet(sopDraft("i2", "start")); err != nil {
+ t.Fatal("a whole-task proposal was blocked by a declined add-on", err)
+ }
+ muted := sopDraft("i1", "end")
+ muted.Decision = domain.AssistantProposalMuted
+ h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "vet", ProjectID: "workbench", Messages: []domain.AssistantMessage{
+ {Role: "user", Content: "改一下"}, {Role: "assistant", Content: proposalReply(t, muted)},
+ }})
+ if err := vet(sopDraft("i2", "start")); err == nil || !strings.Contains(err.Error(), "关闭") {
+ t.Fatalf("a muted conversation accepted a proposal: %v", err)
+ }
+ plain := sopDraft("i2", "start")
+ plain.Proposal = nil
+ if err := vet(plain); err == nil || !strings.Contains(err.Error(), "自己完成") {
+ t.Fatalf("an unrequested SOP dispatch slipped past the mute: %v", err)
+ }
+ h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "vet", ProjectID: "workbench", Messages: []domain.AssistantMessage{
+ {Role: "user", Content: "改一下"}, {Role: "assistant", Content: proposalReply(t, muted)}, {Role: "user", Content: "这个还是走 SOP 吧"},
+ }})
+ if err := vet(plain); err != nil {
+ t.Fatal("a requested SOP dispatch was blocked by the mute", err)
+ }
+}
+
+func TestDecideProposalRecordsAnswerAndReturnsFollowUp(t *testing.T) {
+ h, u := workbenchFixture(t)
+ h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "decide", ProjectID: "workbench", Messages: []domain.AssistantMessage{
+ {Role: "user", Content: "改一下"},
+ {Role: "assistant", Content: proposalReply(t, sopDraft("i1", "start"))},
+ {Role: "user", Content: "做需求"},
+ {Role: "assistant", Content: proposalReply(t, sopDraft("i2", "start"))},
+ }})
+ decide := func(message int, decision string) (int, map[string]json.RawMessage) {
+ body, _ := json.Marshal(map[string]any{"messageIndex": message, "draftIndex": 0, "decision": decision})
+ c, rec := workbenchContext(u, "POST", "/api/assistant/sessions/decide/proposals", bytes.NewBuffer(body))
+ c.Params = gin.Params{{Key: "id", Value: "decide"}}
+ h.decideProposal(c)
+ var out map[string]json.RawMessage
+ _ = json.Unmarshal(rec.Body.Bytes(), &out)
+ return rec.Code, out
+ }
+ // The card accepts before it runs the operation, so a timeout cannot
+ // hand the same work to Main Bot while the operation is running.
+ code, out := decide(1, domain.AssistantProposalAccepted)
+ if code != 200 || string(out["followUp"]) != "null" {
+ t.Fatalf("accept=%d %s", code, out)
+ }
+ stored, _ := h.repo.AssistantSession(u.ID, "decide")
+ var reply struct {
+ Drafts []assistantDraft `json:"drafts"`
+ }
+ json.Unmarshal([]byte(stored.Messages[1].Content), &reply)
+ if reply.Drafts[0].Decision != domain.AssistantProposalAccepted || reply.Drafts[0].Saved {
+ t.Fatalf("draft not marked: %+v", reply.Drafts[0])
+ }
+ if steer := h.expireProposal(u.ID, "decide", 1, 0, time.Now(), u.ID, u.LoginName); steer != nil {
+ t.Fatal("the timeout took over an accepted proposal")
+ }
+ if code, _ := decide(1, domain.AssistantProposalDeclined); code != 409 {
+ t.Fatalf("an answered proposal was answered again: %d", code)
+ }
+ var followUp assistantProposalFollowUp
+ code, out = decide(3, domain.AssistantProposalMuted)
+ if code != 200 || json.Unmarshal(out["followUp"], &followUp) != nil || followUp.Text != assistantProposalDeclinedText {
+ t.Fatalf("declining a timing=start proposal must hand the work back: %d %s", code, out["followUp"])
+ }
+ stored, _ = h.repo.AssistantSession(u.ID, "decide")
+ if history := proposalHistory(stored.Messages); !history.Muted {
+ t.Fatal("muting is not visible to later turns")
+ }
+}
+
+func TestUnansweredStartProposalHandsTheTurnBack(t *testing.T) {
+ h, u := workbenchFixture(t)
+ seed := func(messages ...domain.AssistantMessage) {
+ t.Helper()
+ if err := h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "expire", ProjectID: "workbench", Messages: messages}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ask := domain.AssistantMessage{Role: "user", Content: "做积分转赠需求"}
+ deadline := time.Now().Add(assistantProposalTimeout)
+ stamped := func(drafts ...assistantDraft) string {
+ stampProposalDeadlines(drafts, deadline)
+ return proposalReply(t, drafts...)
+ }
+ forged := sopDraft("i1", "end")
+ forged.Proposal.ExpiresAt = &deadline
+ unstamped := []assistantDraft{forged}
+ stampProposalDeadlines(unstamped, time.Time{})
+ if unstamped[0].Proposal.ExpiresAt != nil {
+ t.Fatal("a model-supplied deadline survived")
+ }
+ proposal := domain.AssistantMessage{Role: "assistant", Content: stamped(sopDraft("i1", "start"))}
+
+ seed(ask, domain.AssistantMessage{Role: "assistant", Content: stamped(sopDraft("i1", "end"))})
+ session, _ := h.repo.AssistantSession(u.ID, "expire")
+ if _, _, _, ok := pendingStartProposal(session.Messages); ok {
+ t.Fatal("an optional add-on was treated as blocking")
+ }
+ seed(ask, domain.AssistantMessage{Role: "assistant", Content: proposalReply(t, sopDraft("i1", "start"))})
+ session, _ = h.repo.AssistantSession(u.ID, "expire")
+ if _, _, _, ok := pendingStartProposal(session.Messages); ok {
+ t.Fatal("a proposal without a deadline got a timer")
+ }
+
+ seed(ask, proposal, domain.AssistantMessage{Role: "user", Content: "先别走 SOP,我自己说"})
+ if steer := h.expireProposal(u.ID, "expire", 1, 0, deadline, u.ID, u.LoginName); steer != nil {
+ t.Fatal("the timeout overrode a message the user already sent")
+ }
+
+ seed(ask, proposal)
+ session, _ = h.repo.AssistantSession(u.ID, "expire")
+ messageIndex, draftIndex, at, ok := pendingStartProposal(session.Messages)
+ if !ok || messageIndex != 1 || draftIndex != 0 || !at.Equal(deadline.UTC()) {
+ t.Fatalf("pending=%d/%d at=%v %v", messageIndex, draftIndex, at, ok)
+ }
+ if err := h.repo.BeginAssistantGeneration(domain.AssistantGeneration{ID: "g-running", SessionID: "expire", UserID: u.ID, Status: "running"}); err != nil {
+ t.Fatal(err)
+ }
+ if steer := h.expireProposal(u.ID, "expire", 1, 0, deadline, u.ID, u.LoginName); steer != nil {
+ t.Fatal("the timeout rewrote the conversation during a reply")
+ }
+ done, _ := h.repo.AssistantGeneration(u.ID, "expire")
+ done.Status = "completed"
+ if err := h.repo.CheckpointAssistantGeneration(done); err != nil {
+ t.Fatal(err)
+ }
+
+ if steer := h.expireProposal(u.ID, "expire", 1, 0, deadline.Add(time.Second), u.ID, u.LoginName); steer != nil {
+ t.Fatal("a timer expired a card it was not started for")
+ }
+ optional := sopDraft("i1", "end")
+ optional.Proposal.ExpiresAt = &deadline
+ seed(ask, domain.AssistantMessage{Role: "assistant", Content: proposalReply(t, optional)})
+ if steer := h.expireProposal(u.ID, "expire", 1, 0, deadline, u.ID, u.LoginName); steer != nil {
+ t.Fatal("the old timer expired the optional proposal of a regenerated reply")
+ }
+ seed(ask, proposal)
+
+ steer := h.expireProposal(u.ID, "expire", 1, 0, deadline, u.ID, u.LoginName)
+ if steer == nil || steer.Trigger != assistantProposalTimeoutTrigger || steer.Content != assistantProposalExpiredText {
+ t.Fatalf("steer=%+v", steer)
+ }
+ saved, _ := h.repo.AssistantSession(u.ID, "expire")
+ if len(saved.Messages) != 3 || saved.Messages[2].Trigger != assistantProposalTimeoutTrigger || saved.Messages[2].Role != "user" {
+ t.Fatalf("messages=%+v", saved.Messages)
+ }
+ if !strings.Contains(saved.Messages[1].Content, `"decision":"expired"`) {
+ t.Fatalf("proposal not marked expired: %s", saved.Messages[1].Content)
+ }
+ if _, declined := proposalHistory(saved.Messages).Declined["i1"]; !declined {
+ t.Fatal("an expired proposal may be offered again")
+ }
+ if again := h.expireProposal(u.ID, "expire", 1, 0, deadline, u.ID, u.LoginName); again != nil {
+ t.Fatal("the proposal expired twice")
+ }
+
+ body, _ := json.Marshal(map[string]any{"messageIndex": 1, "draftIndex": 0, "decision": domain.AssistantProposalAccepted})
+ c, rec := workbenchContext(u, "POST", "/api/assistant/sessions/expire/proposals", bytes.NewBuffer(body))
+ c.Params = gin.Params{{Key: "id", Value: "expire"}}
+ h.decideProposal(c)
+ if rec.Code != 409 {
+ t.Fatalf("an expired proposal was answered: %d %s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestSOPDraftsNeedAProposalUnlessTheUserAskedForTheSOP(t *testing.T) {
+ h, u := workbenchFixture(t)
+ if err := h.repo.PutWorkflow(domain.WorkflowDefinition{ID: "delivery", Name: "交付流水线", ProjectID: "workbench", Status: "published"}); err != nil {
+ t.Fatal(err)
+ }
+ session := &AgentToolSession{ProjectID: "workbench", UserID: u.ID, ChatOwnerID: u.ID, ChatSessionID: "sop"}
+ seed := func(messages ...domain.AssistantMessage) {
+ t.Helper()
+ if err := h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "sop", ProjectID: "workbench", Messages: messages}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ vet := func(d assistantDraft) error {
+ return h.vetProposalDrafts(session, &assistantReply{Drafts: []assistantDraft{d}})
+ }
+ dispatch := assistantDraft{Tool: "issues_dispatch", Path: map[string]any{"id": "i1"}, Body: json.RawMessage(`{}`)}
+ create := assistantDraft{Tool: "issues_save", Body: json.RawMessage(`{"title":"t","workflowId":"delivery"}`)}
+ update := assistantDraft{Tool: "issues_save", Body: json.RawMessage(`{"id":"i1","title":"t","workflowId":"delivery"}`)}
+
+ // The AI 助手 switches are off: a SOP Main Bot picks itself still asks.
+ seed(domain.AssistantMessage{Role: "user", Content: "积分转赠这个需求帮我推进一下"})
+ for _, exec := range []assistantExecMode{{}, {AutoWrite: true, ReviewWrites: true}} {
+ session.ExecMode = exec
+ for _, d := range []assistantDraft{dispatch, create} {
+ if err := vet(d); err == nil || !strings.Contains(err.Error(), "proposal") {
+ t.Fatalf("%+v: %s without a proposal passed: %v", exec, d.Tool, err)
+ }
+ }
+ }
+ if err := vet(update); err != nil {
+ t.Fatalf("editing an issue is not an SOP proposal: %v", err)
+ }
+ if err := vet(sopDraft("i1", "start")); err != nil {
+ t.Fatal(err)
+ }
+ session.ExecMode = assistantExecMode{AutoWrite: true}
+ if err := vet(dispatch); err != nil {
+ t.Fatalf("full access starts a SOP without asking: %v", err)
+ }
+ session.ExecMode = assistantExecMode{}
+
+ for _, refused := range []string{"不要走 SOP,你直接改", "这个不需要走完整流程", "别用交付流水线了"} {
+ seed(domain.AssistantMessage{Role: "user", Content: refused})
+ if err := vet(dispatch); err == nil || !strings.Contains(err.Error(), "proposal") {
+ t.Fatalf("%q counted as asking for the SOP: %v", refused, err)
+ }
+ }
+ for _, asked := range []domain.AssistantMessage{
+ {Role: "user", Content: "直接走 SOP 完整交付"},
+ {Role: "user", Content: "这个走 SOP,不用你自己写"},
+ {Role: "user", Content: "用交付流水线跑一下"},
+ {Role: "user", Content: "推进一下", References: []domain.AssistantReference{{Type: "sop", ID: "delivery"}}},
+ } {
+ seed(asked)
+ if err := vet(dispatch); err != nil {
+ t.Fatalf("%q asked for the SOP: %v", asked.Content, err)
+ }
+ }
+
+ accepted := create
+ accepted.Proposal, accepted.Decision, accepted.Saved = &assistantProposal{Reason: "走 SOP", Timing: "start"}, "accepted", true
+ reviewed := create
+ reviewed.Proposal, reviewed.Saved, reviewed.Auto = &assistantProposal{Reason: "走 SOP", Timing: "start"}, true, true
+ for _, taken := range []assistantDraft{accepted, reviewed} {
+ seed(domain.AssistantMessage{Role: "user", Content: "推进一下"},
+ domain.AssistantMessage{Role: "assistant", Content: proposalReply(t, taken)},
+ domain.AssistantMessage{Role: "user", Content: "已确认并执行 issues_save。"})
+ if err := vet(dispatch); err != nil {
+ t.Fatalf("the dispatch after a taken SOP proposal asked again: %v", err)
+ }
+ }
+
+ muted := sopDraft("i2", "start")
+ muted.Decision = domain.AssistantProposalMuted
+ thread := []domain.AssistantMessage{
+ {Role: "user", Content: "走 SOP 吧"},
+ {Role: "assistant", Content: proposalReply(t, accepted)},
+ {Role: "user", Content: "再做个需求"},
+ {Role: "assistant", Content: proposalReply(t, muted)},
+ }
+ seed(thread...)
+ if err := vet(dispatch); err == nil || !strings.Contains(err.Error(), "关闭") {
+ t.Fatalf("an earlier accept or request outlived the mute: %v", err)
+ }
+ // The stored transcript still ends at the mute. A direct chat carries the
+ // new request only on the turn, and that request is what counts.
+ session.turnMessages = append(append([]domain.AssistantMessage{}, thread...), domain.AssistantMessage{Role: "user", Content: "还是走 SOP 吧"})
+ if err := vet(dispatch); err != nil {
+ t.Fatalf("the unsaved request after a mute was blocked: %v", err)
+ }
+ session.turnMessages = nil
+ seed(append(thread, domain.AssistantMessage{Role: "user", Content: "还是走 SOP 吧"})...)
+ if err := vet(dispatch); err != nil {
+ t.Fatalf("asking after the mute was blocked: %v", err)
+ }
+}
+
+func TestAssistantPreferencesShapeTheContext(t *testing.T) {
+ h, u := workbenchFixture(t)
+ h.repo.PutAgent(domain.AgentDefinition{ID: "reviewer", Name: "评审", ProjectID: "workbench", Prompt: "评审"})
+ if p := h.repo.AssistantPreferences(u.ID); p.ProactiveRoles || p.ProactiveSOPs || p.Instructions != "" {
+ t.Fatalf("defaults=%+v", p)
+ }
+ put := func(body string) (int, domain.AssistantPreferences) {
+ c, rec := workbenchContext(u, "PUT", "/api/assistant/preferences", bytes.NewBufferString(body))
+ h.preferences(c)
+ var out domain.AssistantPreferences
+ _ = json.Unmarshal(rec.Body.Bytes(), &out)
+ return rec.Code, out
+ }
+ if code, _ := put(`{"instructions":"` + strings.Repeat("长", domain.AssistantPreferencesInstructionsMax+1) + `"}`); code != 400 {
+ t.Fatalf("oversized rules=%d", code)
+ }
+ contextFor := func(mode string) assistantRequest {
+ t.Helper()
+ c, _ := workbenchContext(u, "POST", "/", &bytes.Buffer{})
+ req := assistantRequest{ProjectID: "workbench", SessionID: "prefs", ApprovalMode: mode, Messages: []domain.AssistantMessage{{Role: "user", Content: "评审一下"}}}
+ if err := h.prepareWorkbenchContext(c, &req, u); err != nil {
+ t.Fatal(err)
+ }
+ return req
+ }
+ const asBefore = "任务明显属于某个角色的职责、或需要它的规则和技能时,可以自行派给它;简单问题自己处理。"
+ const askSOP = "## 交给 SOP 前先征得同意"
+
+ for _, exec := range []assistantExecMode{{}, {AutoWrite: true, ReviewWrites: true}, {AutoWrite: true}} {
+ schema, _ := json.Marshal(submitAssistantReplySchema(exec))
+ if got, want := strings.Contains(string(schema), `"proposal"`), !exec.AutoWrite || exec.ReviewWrites; got != want {
+ t.Fatalf("%+v: schema offers proposal=%v", exec, got)
+ }
+ if strings.Contains(string(schema), `"subagent_dispatch"`) {
+ t.Fatalf("%+v: schema offers a role dispatch draft", exec)
+ }
+ }
+
+ if req := contextFor(AssistantApprovalConfirm); strings.Contains(req.contextText, askSOP) {
+ t.Fatalf("a project without SOPs explains SOP proposals: %s", req.contextText)
+ }
+ if err := h.repo.PutWorkflow(domain.WorkflowDefinition{ID: "delivery", Name: "交付流水线", ProjectID: "workbench", Status: "published"}); err != nil {
+ t.Fatal(err)
+ }
+
+ // Both off: roles as before; a SOP Main Bot picks itself still asks
+ // outside full access.
+ for _, mode := range []string{AssistantApprovalConfirm, AssistantApprovalAssisted, AssistantApprovalAuto} {
+ req := contextFor(mode)
+ if len(req.roles) != 1 || !strings.Contains(req.contextText, asBefore) {
+ t.Fatalf("%s with both off: roles=%d context=%s", mode, len(req.roles), req.contextText)
+ }
+ for _, unwanted := range []string{"## 自己做", "- 派角色:", "- 走 SOP:", "用户给你的自定义规则"} {
+ if strings.Contains(req.contextText, unwanted) {
+ t.Fatalf("%s with both off adds %q: %s", mode, unwanted, req.contextText)
+ }
+ }
+ if got := strings.Contains(req.contextText, askSOP); got != (mode != AssistantApprovalAuto) {
+ t.Fatalf("%s with both off: asks before a SOP=%v", mode, got)
+ }
+ if got := strings.Contains(req.contextText, "当前是帮我批准"); got != (mode == AssistantApprovalAssisted) {
+ t.Fatalf("%s: assisted note=%v", mode, got)
+ }
+ }
+
+ code, saved := put(`{"proactiveRoles":true,"proactiveSops":false,"instructions":" 回复先给结论 "}`)
+ if code != 200 || !saved.ProactiveRoles || saved.ProactiveSOPs || saved.Instructions != "回复先给结论" {
+ t.Fatalf("saved=%d %+v", code, saved)
+ }
+ c, rec := workbenchContext(u, "GET", "/api/assistant/preferences", &bytes.Buffer{})
+ h.preferences(c)
+ if !strings.Contains(rec.Body.String(), `"proactiveRoles":true`) {
+ t.Fatalf("get=%s", rec.Body.String())
+ }
+ for _, mode := range []string{AssistantApprovalConfirm, AssistantApprovalAuto} {
+ req := contextFor(mode)
+ if len(req.roles) != 1 || strings.Contains(req.contextText, asBefore) {
+ t.Fatalf("%s with roles on: roles=%d context=%s", mode, len(req.roles), req.contextText)
+ }
+ for _, want := range []string{"- 派角色:", "不用征求同意", "- 收尾检查:", "## 用户给你的自定义规则", "回复先给结论"} {
+ if !strings.Contains(req.contextText, want) {
+ t.Fatalf("%s roles on: context lacks %q: %s", mode, want, req.contextText)
+ }
+ }
+ if strings.Contains(req.contextText, "- 走 SOP:") {
+ t.Fatalf("SOPs off still describes when to take one: %s", req.contextText)
+ }
+ }
+
+ if code, _ := put(`{"proactiveSops":true}`); code != 200 {
+ t.Fatalf("SOPs on=%d", code)
+ }
+ if req := contextFor(AssistantApprovalAuto); !strings.Contains(req.contextText, "- 走 SOP:") || !strings.Contains(req.contextText, "当前是完全权限:走 SOP 时直接调用写入工具") || strings.Contains(req.contextText, askSOP) {
+ t.Fatalf("full access with SOPs on: %s", req.contextText)
+ }
+ if req := contextFor(AssistantApprovalConfirm); !strings.Contains(req.contextText, "- 走 SOP:") || !strings.Contains(req.contextText, askSOP) || !strings.Contains(req.contextText, asBefore) {
+ t.Fatalf("confirm with SOPs on: %s", req.contextText)
+ }
+}
+
+// A direct chat, including SSE, stores the personal session after the reply.
+// The proposal gate has to see the user message on that request, or a named
+// SOP is refused as if Main Bot had suggested it.
+func TestDirectChatSeesTheSOPTheUserJustAskedFor(t *testing.T) {
+ h, u := workbenchFixture(t)
+ if err := h.repo.PutWorkflow(domain.WorkflowDefinition{ID: "delivery", Name: "交付流水线", ProjectID: "workbench", Status: "published"}); err != nil {
+ t.Fatal(err)
+ }
+ const asked = "请走 SOP 交付流水线实现新功能"
+ dispatch := json.RawMessage(`{"message":"交给交付流水线","drafts":[{"tool":"issues_dispatch","path":{"id":"i1"},"body":{}}]}`)
+ gateway := &agentToolGateway{deps: h.deps}
+ chat := func(t *testing.T, sessionID string, messages []domain.AssistantMessage, accept, want string) {
+ t.Helper()
+ var once sync.Once
+ var toolText string
+ var toolErr bool
+ var called bool
+ h.generate = func(context.Context, string, domain.User) (string, error) {
+ once.Do(func() {
+ called = true
+ session := assistantToolSessionForChat(sessionID)
+ if session == nil {
+ t.Error("chat did not open a tool session")
+ return
+ }
+ result, err := gateway.callTerminal(session, submitAssistantReplyTool, dispatch)
+ if err != nil {
+ toolText, toolErr = err.Error(), true
+ return
+ }
+ toolErr, _ = result["isError"].(bool)
+ toolText = mcpToolResultText(result)
+ })
+ return `{"message":"好","drafts":[]}`, nil
+ }
+ body, err := json.Marshal(map[string]any{"sessionId": sessionID, "projectId": "workbench", "messages": messages})
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, rec := workbenchContext(u, http.MethodPost, "/api/assistant/chat", bytes.NewBuffer(body))
+ if accept != "" {
+ c.Request.Header.Set("Accept", accept)
+ }
+ h.chat(c)
+ if !called {
+ t.Fatalf("chat never reached the model: %d %s", rec.Code, rec.Body.String())
+ }
+ if want == "" {
+ if toolErr || !strings.Contains(toolText, "提交成功") {
+ t.Fatalf("a named SOP was refused: err=%v %s http=%d %s", toolErr, toolText, rec.Code, rec.Body.String())
+ }
+ if rec.Code >= 400 {
+ t.Fatalf("chat failed after accepting the SOP: %d %s", rec.Code, rec.Body.String())
+ }
+ return
+ }
+ if !toolErr || !strings.Contains(toolText, want) {
+ t.Fatalf("an unnamed SOP passed: err=%v %s", toolErr, toolText)
+ }
+ }
+ chat(t, "direct-json", []domain.AssistantMessage{{Role: "user", Content: asked}}, "", "")
+ chat(t, "direct-sse", []domain.AssistantMessage{{Role: "user", Content: asked}}, "text/event-stream", "")
+
+ muted := sopDraft("i2", "start")
+ muted.Decision = domain.AssistantProposalMuted
+ prior := []domain.AssistantMessage{
+ {Role: "user", Content: "先看看这个需求"},
+ {Role: "assistant", Content: proposalReply(t, muted)},
+ }
+ if err := h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "direct-muted", ProjectID: "workbench", Messages: prior}); err != nil {
+ t.Fatal(err)
+ }
+ again := append(append([]domain.AssistantMessage{}, prior...), domain.AssistantMessage{Role: "user", Content: asked})
+ chat(t, "direct-muted", again, "", "")
+ chat(t, "direct-unnamed", []domain.AssistantMessage{{Role: "user", Content: "积分转赠这个需求帮我推进一下"}}, "", "proposal")
+}
+
+func assistantToolSessionForChat(sessionID string) *AgentToolSession {
+ agentToolSessions.mu.Lock()
+ defer agentToolSessions.mu.Unlock()
+ for _, session := range agentToolSessions.sessions {
+ if session.ChatSessionID == sessionID && session.Mode == AgentToolAssistant {
+ return session
+ }
+ }
+ return nil
+}
+
+func mcpToolResultText(result map[string]any) string {
+ content, _ := result["content"].([]map[string]any)
+ if len(content) == 0 {
+ return ""
+ }
+ text, _ := content[0]["text"].(string)
+ return text
+}
diff --git a/internal/httpapi/assistant_workbench.go b/internal/httpapi/assistant_workbench.go
index bf109443..791548f3 100644
--- a/internal/httpapi/assistant_workbench.go
+++ b/internal/httpapi/assistant_workbench.go
@@ -329,9 +329,23 @@ func (h *assistantHandlers) prepareWorkbenchContext(c *gin.Context, req *assista
req.attachmentOwners[a.ID] = attachmentOwner
}
}
+ prefs := h.repo.AssistantPreferences(user.ID)
if len(req.roles) > 0 {
- context.WriteString("本项目的角色已作为子 Agent 提供(Agent 工具的 subagent_type=role-<角色ID>),各自带着角色的 prompt、规则和技能。任务明显属于某个角色的职责、或需要它的规则和技能时,可以自行派给它;简单问题自己处理。子 Agent 看不到本对话,派发的 prompt 要写清背景、要做什么、工作区里相关的仓库和文件路径。同一角色在本对话里已经派过(前几轮,或本轮早先 Agent 结果里的 Agent ID),默认传 resume=<agent ID> 复用那个子 Agent,让它带着之前的上下文继续;只有用户要求新开、新任务与它之前做的事无关、或要与它并行时才不传 resume。resume 失败时直接新开。\n")
+ context.WriteString("本项目的角色已作为子 Agent 提供(Agent 工具的 subagent_type=role-<角色ID>),各自带着角色的 prompt、规则和技能。")
+ if !prefs.ProactiveRoles {
+ context.WriteString("任务明显属于某个角色的职责、或需要它的规则和技能时,可以自行派给它;简单问题自己处理。")
+ }
+ context.WriteString("子 Agent 看不到本对话,派发的 prompt 要写清背景、要做什么、工作区里相关的仓库和文件路径。同一角色在本对话里已经派过(前几轮,或本轮早先 Agent 结果里的 Agent ID),默认传 resume=<agent ID> 复用那个子 Agent,让它带着之前的上下文继续;只有用户要求新开、新任务与它之前做的事无关、或要与它并行时才不传 resume。resume 失败时直接新开。\n")
+ }
+ hasSOP := false
+ for _, wf := range h.repo.Workflows() {
+ if req.ProjectID != "" && wf.ProjectID == req.ProjectID {
+ hasSOP = true
+ break
+ }
}
+ context.WriteString(delegationContext(req, prefs, normalizeAssistantApprovalMode(req.ApprovalMode), hasSOP))
+ context.WriteString(assistantInstructionsContext(prefs))
if len(req.roles) > 0 {
if stored, ok := h.repo.AssistantSession(assistantStorageOwner(h.repo, req.SessionID, user.ID), req.SessionID); ok {
ids := roleAgentIDs(stored.Messages)
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index f0c30a7e..515a49ec 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -301,6 +301,9 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
g.GET("/api/assistant/sessions/:id/generation", asst.generation)
g.POST("/api/assistant/sessions/:id/generation/cancel", asst.generation)
g.POST("/api/assistant/sessions/:id/generation/steer", asst.steerGeneration)
+ g.POST("/api/assistant/sessions/:id/proposals", asst.decideProposal)
+ g.GET("/api/assistant/preferences", asst.preferences)
+ g.PUT("/api/assistant/preferences", asst.preferences)
g.GET("/api/assistant/models", asst.models)
g.POST("/api/assistant/attachments", asst.uploadAttachment)
g.GET("/api/assistant/attachments/:id", asst.downloadAttachment)
diff --git a/internal/repo/assistant_preferences.go b/internal/repo/assistant_preferences.go
new file mode 100644
index 00000000..4dd39a8b
--- /dev/null
+++ b/internal/repo/assistant_preferences.go
@@ -0,0 +1,40 @@
+package repo
+
+import (
+ "errors"
+ "strings"
+ "time"
+
+ "agentflow/internal/domain"
+)
+
+// AssistantPreferences returns the user's Main Bot settings; the zero value
+// when they never saved any.
+func (r *AssistantRepo) AssistantPreferences(userID int64) domain.AssistantPreferences {
+ var out domain.AssistantPreferences
+ if userID <= 0 {
+ return out
+ }
+ var row assistantPreferenceRow
+ if err := r.DB.Where("user_id = ?", userID).Take(&row).Error; err != nil {
+ return out
+ }
+ out.ProactiveRoles, out.ProactiveSOPs, out.Instructions = row.ProactiveRoles, row.ProactiveSOPs, row.Instructions
+ if row.UpdatedAt != nil {
+ out.UpdatedAt = *row.UpdatedAt
+ }
+ return out
+}
+
+// PutAssistantPreferences replaces the user's Main Bot settings.
+func (r *AssistantRepo) PutAssistantPreferences(userID int64, p domain.AssistantPreferences) (domain.AssistantPreferences, error) {
+ if userID <= 0 {
+ return p, errors.New("user id is required")
+ }
+ now := time.Now().UTC()
+ row := assistantPreferenceRow{UserID: userID, ProactiveRoles: p.ProactiveRoles, ProactiveSOPs: p.ProactiveSOPs, Instructions: strings.TrimSpace(p.Instructions), UpdatedAt: &now}
+ if err := r.DB.Save(&row).Error; err != nil {
+ return p, err
+ }
+ return r.AssistantPreferences(userID), nil
+}
diff --git a/internal/repo/assistant_proposals.go b/internal/repo/assistant_proposals.go
new file mode 100644
index 00000000..36f79d2e
--- /dev/null
+++ b/internal/repo/assistant_proposals.go
@@ -0,0 +1,44 @@
+package repo
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+
+ "agentflow/internal/domain"
+)
+
+// PutAssistantSessionIfUnchanged saves next only while the stored session is
+// still expected and no reply is being generated, so two writers answering
+// the same proposal cannot overwrite each other.
+func (r *AssistantRepo) PutAssistantSessionIfUnchanged(userID int64, next, expected domain.AssistantSession) error {
+ return r.DB.Transaction(func(tx *gorm.DB) error {
+ var row assistantSessionRow
+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ? AND user_id = ?", assistantRecordID(next.ID), userID).Take(&row).Error; err != nil {
+ return err
+ }
+ old := decodeAssistantSession(row)
+ a, _ := json.Marshal(old.Messages)
+ b, _ := json.Marshal(expected.Messages)
+ if !old.UpdatedAt.Equal(expected.UpdatedAt) || !bytes.Equal(a, b) {
+ return fmt.Errorf("会话已更新,请重新打开")
+ }
+ var active int64
+ if err := tx.Model(&assistantGenerationRow{}).Where("session_id = ? AND status = ?", row.ID, "running").Count(&active).Error; err != nil {
+ return err
+ }
+ if active > 0 {
+ return fmt.Errorf("生成期间不能改写会话")
+ }
+ scoped := *r
+ base := *r.deps
+ base.DB = tx
+ scoped.deps = &base
+ next.UpdatedAt = time.Time{}
+ return scoped.putAssistantSession(userID, next)
+ })
+}
diff --git a/internal/repo/models.go b/internal/repo/models.go
index 0e866cb2..f0add9d8 100644
--- a/internal/repo/models.go
+++ b/internal/repo/models.go
@@ -523,6 +523,17 @@ type userRunnerPrefRow struct {
func (userRunnerPrefRow) TableName() string { return "user_runner_prefs" }
+// assistantPreferenceRow: a missing row means both switches are off.
+type assistantPreferenceRow struct {
+ UserID int64 `gorm:"column:user_id;primaryKey;autoIncrement:false"`
+ ProactiveRoles bool `gorm:"column:proactive_roles;not null;default:false"`
+ ProactiveSOPs bool `gorm:"column:proactive_sops;not null;default:false"`
+ Instructions string `gorm:"column:instructions;type:text"`
+ UpdatedAt *time.Time `gorm:"column:updated_at"`
+}
+
+func (assistantPreferenceRow) TableName() string { return "assistant_preferences" }
+
type assistantSessionRow struct {
ID string `gorm:"column:id;primaryKey;size:64"`
UserID int64 `gorm:"column:user_id;index:idx_assistant_sessions_user_updated"`
@@ -689,7 +700,7 @@ func allModels() []any {
runPreviewRow{}, previewSessionRow{}, previewBlobRow{}, WorkspaceCheckpoint{}, workspaceCheckpointChunk{},
mrDeliveryStateRow{}, definitionRevisionRow{},
runnerRow{}, runnerTaskRow{}, runnerTaskEventRow{}, userRunnerPrefRow{},
- assistantSessionRow{}, assistantTaskRow{}, assistantGenerationRow{}, assistantSessionReadRow{},
+ assistantSessionRow{}, assistantTaskRow{}, assistantGenerationRow{}, assistantSessionReadRow{}, assistantPreferenceRow{},
chatRoomRow{}, chatMessageRow{},
requirementSpaceRow{}, spaceMemberRow{}, spaceArtifactRow{}, spaceArtifactRevisionRow{}, spaceThreadRow{},
engineInstanceRow{},
diff --git a/web/app.js b/web/app.js
index 65171625..239a0bd3 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1578,7 +1578,7 @@ function settingsSidebarExpanded(){
}
let settingsSidebarEntryFrame=0;
let settingsSidebarWasManaged=false;
-const settingsManagementViews=['settings','projects','bots','sops','flow','runs','aiSchedules','agents','mcp','rules','skills','runners','dockerfiles','environments','sandboxes','guide','platform'];
+const settingsManagementViews=['settings','assistant','projects','bots','sops','flow','runs','aiSchedules','agents','mcp','rules','skills','runners','dockerfiles','environments','sandboxes','guide','platform'];
const settingsRouteMotion=matchMedia('(prefers-reduced-motion: reduce)');
let settingsRouteTransition=null;
let settingsRouteApplying=false;
@@ -1768,7 +1768,7 @@ function setPlatformRailExpanded(expanded){
const text=button.querySelector('.rail-label');
if(text)text.textContent=label;
}
-function viewTitles(){return {management:'设置',collaboration:'AI 工作台',issues:'需求列表',aiSchedules:'定时任务',bots:'通道管理',runs:'运行记录',approvals:'待我确认',sops:'流程模板',flow:'流程设计',agents:'角色定义',mcp:'能力资产',rules:'能力资产',skills:'能力资产',dockerfiles:'环境资产',environments:'环境资产',sandboxes:'环境资产',observability:'统计',projects:'项目配置',platform:'平台管理',runners:'执行机器',settings:'个人配置',access:'访问密钥',guide:'访问密钥'}}
+function viewTitles(){return {management:'设置',collaboration:'AI 工作台',issues:'需求列表',aiSchedules:'定时任务',bots:'通道管理',assistant:'AI 助手',runs:'运行记录',approvals:'待我确认',sops:'流程模板',flow:'流程设计',agents:'角色定义',mcp:'能力资产',rules:'能力资产',skills:'能力资产',dockerfiles:'环境资产',environments:'环境资产',sandboxes:'环境资产',observability:'统计',projects:'项目配置',platform:'平台管理',runners:'执行机器',settings:'个人配置',access:'访问密钥',guide:'访问密钥'}}
// 设置侧栏只列一级入口;被合并进同一页的子视图(能力资产、环境资产的类型 Tab,
// 从流程模板打开的流程设计)按 data-nav-match 高亮它们所属的入口。
function settingsNavMatches(btn,name){return btn.dataset.view===name||String(btn.dataset.navMatch||'').split(/\s+/).includes(name)}
@@ -1984,6 +1984,7 @@ function switchView(name){
if(name==='aiSchedules'){renderScheduleJobs();refreshAISchedules()}
if(name==='bots')loadBots();
+ if(name==='assistant')loadAssistantSettings();
if(name==='sops'){if(!staying&&state.data){sopCatalogMotion.reset();renderSOPCatalog()}refreshWorkflowMetrics()}
if(name==='dashboard')refreshDashboard()
if(name==='approvals')renderApprovals(false)
diff --git a/web/app/assistant-settings.css b/web/app/assistant-settings.css
new file mode 100644
index 00000000..5693bb9b
--- /dev/null
+++ b/web/app/assistant-settings.css
@@ -0,0 +1,22 @@
+/* AI 助手设置页(#assistantView):两张面板,主动派发开关 + 自定义规则。 */
+#assistantView .asst-form fieldset { margin: 0; padding: 0; border: 0; min-width: 0; display: grid; gap: 16px; }
+#assistantView .asst-panel { padding: 20px 22px; border: 1px solid var(--hui-border); border-radius: 14px; background: var(--hui-surface); box-shadow: var(--hui-panel-shadow); }
+#assistantView .asst-panel-head h2 { margin: 0; color: var(--hui-text); font: 600 15px/1.4 var(--hui-sans); }
+#assistantView .asst-panel-head p { margin: 4px 0 0; color: var(--hui-secondary); font-size: 13px; line-height: 1.6; }
+#assistantView .asst-rows { margin-top: 12px; }
+#assistantView .asst-switch-row { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 14px 0; border-top: 1px solid var(--hui-border-soft); cursor: pointer; }
+#assistantView .asst-switch-row:first-child { border-top: 0; }
+#assistantView .asst-switch-row > input { flex: none; }
+#assistantView .asst-switch-row b { display: block; color: var(--hui-text); font-size: 13px; font-weight: 500; }
+#assistantView .asst-switch-row small { display: block; margin-top: 3px; color: var(--hui-tertiary); font-size: 12px; line-height: 1.6; }
+#assistantView .asst-rules-label { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+#assistantView .asst-rules { display: block; box-sizing: border-box; width: 100%; min-height: 160px; margin-top: 14px; padding: 10px 12px; resize: vertical; font: 13px/1.6 var(--hui-sans); }
+#assistantView .asst-rules-foot { display: flex; justify-content: flex-end; margin-top: 6px; }
+#assistantView .asst-count { color: var(--hui-tertiary); font-size: 12px; font-variant-numeric: tabular-nums; }
+#assistantView .asst-actions { display: flex; justify-content: flex-end; }
+#assistantView .asst-empty { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--hui-secondary); font-size: 13px; }
+#assistantView .asst-empty p { margin: 0; }
+@media (max-width: 640px) {
+ #assistantView .asst-panel { padding: 16px; }
+ #assistantView .asst-switch-row { gap: 16px; }
+}
diff --git a/web/app/assistant-settings.js b/web/app/assistant-settings.js
new file mode 100644
index 00000000..20269fd7
--- /dev/null
+++ b/web/app/assistant-settings.js
@@ -0,0 +1,63 @@
+// AI 助手设置:没有 @ 时是否更主动地派角色、走 SOP(默认都关),以及每轮都带上的自定义规则。只对当前用户生效。
+const ASSISTANT_RULES_MAX=4000;
+const assistantPrefsUI={saved:null,loading:false,saving:false,error:''};
+
+function assistantPrefsSignedIn(){return !!state.currentUser&&!state.currentUser.isGuest}
+function assistantPrefsForm(){return document.querySelector('#assistantPrefsForm')}
+function assistantPrefsDraft(form){return {proactiveRoles:form.proactiveRoles.checked,proactiveSops:form.proactiveSops.checked,instructions:form.instructions.value.trim()}}
+function assistantPrefsDirty(form){
+ const saved=assistantPrefsUI.saved;if(!saved||!form)return false;
+ const draft=assistantPrefsDraft(form);
+ return draft.proactiveRoles!==!!saved.proactiveRoles||draft.proactiveSops!==!!saved.proactiveSops||draft.instructions!==(saved.instructions||'');
+}
+function assistantPrefsSwitchRow(name,title,help,on){
+ return `<label class="asst-switch-row"><span><b>${title}</b><small>${help}</small></span><input type="checkbox" role="switch" name="${name}" ${on?'checked':''}></label>`;
+}
+function assistantPrefsFormHTML(p){
+ const rules=p.instructions||'';
+ return `<form id="assistantPrefsForm" class="asst-form" novalidate><fieldset ${assistantPrefsUI.saving?'disabled':''}>
+ <section class="asst-panel"><header class="asst-panel-head"><h2>主动派发</h2><p>打开后 AI 助手会更主动地把事情交给角色或 SOP。派角色不需要确认;走 SOP 仍按审批模式先征求同意,完全权限下直接启动。</p></header>
+ <div class="asst-rows">
+ ${assistantPrefsSwitchRow('proactiveRoles','主动派角色','整件事是某个角色的本职(如独立评审、整套测试),或改了高风险代码需要复核时,直接交给这个角色。',p.proactiveRoles)}
+ ${assistantPrefsSwitchRow('proactiveSops','主动走 SOP','遇到要落到仓库的新需求时,先交给项目里用途对得上的 SOP,而不是自己直接改代码。',p.proactiveSops)}
+ </div></section>
+ <section class="asst-panel"><header class="asst-panel-head"><h2>自定义规则</h2><p>每轮对话都会带上这些规则,适合写你的习惯和偏好;不会越过审批模式和平台规则。</p></header>
+ <label class="asst-rules-label" for="assistantPrefsRules">规则</label>
+ <textarea id="assistantPrefsRules" class="input asst-rules" name="instructions" rows="8" maxlength="${ASSISTANT_RULES_MAX}" placeholder="例如:回复先给结论再给细节;改代码前先说明要改哪些文件;不要自动发起 MR。">${escapeHTML(rules)}</textarea>
+ <div class="asst-rules-foot"><span id="assistantPrefsCount" class="asst-count">${rules.length} / ${ASSISTANT_RULES_MAX}</span></div></section>
+ <div class="asst-actions"><button type="submit" class="button primary" id="assistantPrefsSave" disabled>${assistantPrefsUI.saving?'保存中…':'保存'}</button></div>
+ </fieldset></form>`;
+}
+function renderAssistantSettings(){
+ const host=document.querySelector('#assistantContent');if(!host)return;
+ if(!assistantPrefsSignedIn()){host.innerHTML='<section class="asst-panel asst-empty"><p>登录后可以设置 AI 助手。</p></section>';return}
+ if(assistantPrefsUI.error&&!assistantPrefsUI.saved){host.innerHTML=`<section class="asst-panel asst-empty"><p>${escapeHTML(assistantPrefsUI.error)}</p><button type="button" class="button" data-assistant-prefs-retry>重试</button></section>`;host.querySelector('[data-assistant-prefs-retry]').onclick=loadAssistantSettings;return}
+ if(!assistantPrefsUI.saved){host.innerHTML='<section class="asst-panel asst-empty"><p>正在读取设置…</p></section>';return}
+ host.innerHTML=assistantPrefsFormHTML(assistantPrefsUI.saved);
+ const form=assistantPrefsForm(),save=form.querySelector('#assistantPrefsSave'),count=form.querySelector('#assistantPrefsCount');
+ const refresh=()=>{count.textContent=`${form.instructions.value.length} / ${ASSISTANT_RULES_MAX}`;save.disabled=assistantPrefsUI.saving||!assistantPrefsDirty(form)};
+ form.addEventListener('input',refresh);
+ form.addEventListener('change',refresh);
+ form.onsubmit=async event=>{
+ event.preventDefault();
+ if(assistantPrefsUI.saving||!assistantPrefsDirty(form))return;
+ const draft=assistantPrefsDraft(form);
+ assistantPrefsUI.saving=true;save.disabled=true;save.textContent='保存中…';
+ try{
+ assistantPrefsUI.saved=await api('/api/assistant/preferences',{method:'PUT',body:JSON.stringify(draft)});
+ toast('AI 助手设置已保存');
+ }catch(err){toast(err.message||'保存失败,请重试')}
+ finally{assistantPrefsUI.saving=false;save.textContent='保存';refresh()}
+ };
+}
+async function loadAssistantSettings(){
+ if(!assistantPrefsSignedIn()){renderAssistantSettings();return}
+ if(assistantPrefsUI.loading)return;
+ const form=assistantPrefsForm();
+ if(form&&assistantPrefsDirty(form))return;
+ assistantPrefsUI.loading=true;assistantPrefsUI.error='';
+ if(!assistantPrefsUI.saved)renderAssistantSettings();
+ try{assistantPrefsUI.saved=await api('/api/assistant/preferences',{silent:true})}
+ catch(err){assistantPrefsUI.error=err.message||'读取设置失败'}
+ finally{assistantPrefsUI.loading=false;renderAssistantSettings()}
+}
diff --git a/web/app/harness-motion.js b/web/app/harness-motion.js
index f1bbf65a..73c725df 100644
--- a/web/app/harness-motion.js
+++ b/web/app/harness-motion.js
@@ -1148,7 +1148,7 @@
const views = {
collaboration: "home-start", issues: "form", approvals: "gate",
sops: "workflow", runs: "runs", management: "dashboard", runners: "server",
- settings: "settings", bots: "robot", projects: "users", flow: "workflow",
+ settings: "settings", bots: "robot", assistant: "sparkles", projects: "users", flow: "workflow",
agents: "user", mcp: "connector", rules: "doc", skills: "skills",
dockerfiles: "layers", environments: "terminal", sandboxes: "server",
observability: "token", guide: "key", platform: "gate",
diff --git a/web/app/harness-ui.css b/web/app/harness-ui.css
index 175bc43b..1af41c55 100644
--- a/web/app/harness-ui.css
+++ b/web/app/harness-ui.css
@@ -70,14 +70,14 @@ html[data-theme="dark"] {
}
/* ---------- Harness 视图 ----------
- * 原生 Harness 页面:#issuesView #runsView #assetsView #approvalsView #observabilityView #mcpView #botsView #aiSchedulesView #knowledgeView
+ * 原生 Harness 页面:#issuesView #runsView #assetsView #approvalsView #observabilityView #mcpView #botsView, #assistantView #aiSchedulesView #knowledgeView
* 设置区视图(1200px 居中容器、页头与按钮映射):
- * #settingsView #botsView #projectsView #runnersView #agentsView #mcpView #assetsView #knowledgeView
+ * #settingsView #botsView, #assistantView #projectsView #runnersView #agentsView #mcpView #assetsView #knowledgeView
* #metricsView #businessDomainsView #guideView #platformView #businessDomainManagementView
* 弹窗:#agentModal #customMcpModal #scheduleModal #requirementModal(新建需求向导,布局见 requirement-wizard.css)
* #flowView 与工作区其他页面不在列表内。
*/
-:is(#issuesView, #assetsView, #approvalsView, #observabilityView, #obsExpand, .obs-source-dialog, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #knowledgeView, #kbDrawer, #requirementModal, .hui-select-panel, .issue-action-popover) {
+:is(#issuesView, #assetsView, #approvalsView, #observabilityView, #obsExpand, .obs-source-dialog, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #knowledgeView, #kbDrawer, #requirementModal, .hui-select-panel, .issue-action-popover) {
font-family: var(--hui-sans);
color: var(--hui-text);
-webkit-font-smoothing: antialiased;
@@ -124,7 +124,7 @@ html[data-theme="dark"] {
/* 设置区:页头与内容外层容器居中、最大 1200px;页面内部布局不变。
* product-v4.css 用 !important 清掉了这些元素的 max-width / margin,这里同样需要 !important。 */
-:is(#settingsView, #botsView, #aiSchedulesView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView).page-view.active > :not(.agent-row-menu) {
+:is(#settingsView, #botsView, #assistantView, #aiSchedulesView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView).page-view.active > :not(.agent-row-menu) {
box-sizing: border-box;
width: 100%;
max-width: 1200px !important;
@@ -133,12 +133,12 @@ html[data-theme="dark"] {
}
/* 设置区页头:H1 22px/600,说明 13px 次级色 */
-:is(#settingsView, #botsView, #aiSchedulesView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph, .kb-head) h1 {
+:is(#settingsView, #botsView, #assistantView, #aiSchedulesView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph, .kb-head) h1 {
color: var(--hui-text);
font: 600 22px/1.25 var(--hui-sans);
letter-spacing: -.02em;
}
-:is(#settingsView, #botsView, #aiSchedulesView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph) h1 + p,
+:is(#settingsView, #botsView, #assistantView, #aiSchedulesView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph) h1 + p,
:is(#settingsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) .page-heading > div > p:last-child,
#knowledgeView .kb-head-desc {
color: var(--hui-secondary);
@@ -149,7 +149,7 @@ html[data-theme="dark"] {
/* ---------- 按钮:实心强调 / 白底强边框 / quiet,另有淡紫行内主操作与图标按钮 ----------
* 原生 Harness 页面使用完整规格(页面级 32px、行内 28px);
* 其他设置页只映射外观,尺寸沿用原元素。 */
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal) .button {
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal) .button {
box-sizing: border-box;
display: inline-flex;
align-items: center;
@@ -164,10 +164,10 @@ html[data-theme="dark"] {
text-decoration: none;
cursor: pointer;
}
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal) .button.small { height: 28px; min-height: 28px; padding: 0 10px; font-size: 12.5px; }
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal) .button.hui-icon-button { width: 32px; padding: 0; }
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal) .button.small { height: 28px; min-height: 28px; padding: 0 10px; font-size: 12.5px; }
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal) .button.hui-icon-button { width: 32px; padding: 0; }
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button,
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button,
:is(#knowledgeView, #kbDrawer) .kb-btn {
border: 1px solid var(--hui-border-strong);
border-radius: 7px;
@@ -178,7 +178,7 @@ html[data-theme="dark"] {
transform: none;
transition: background-color .18s var(--hui-ease-flow), color .18s var(--hui-ease-flow), border-color .18s var(--hui-ease-flow);
}
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:hover:not(:disabled),
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:hover:not(:disabled),
:is(#knowledgeView, #kbDrawer) .kb-btn:hover:not(:disabled) {
border-color: var(--hui-border-strong);
background: var(--hui-canvas);
@@ -186,17 +186,17 @@ html[data-theme="dark"] {
box-shadow: none;
transform: none;
}
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:focus-visible,
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:focus-visible,
:is(#knowledgeView, #kbDrawer) .kb-btn:focus-visible,
.credential-btn:focus-visible {
outline: 2px solid var(--hui-focus-ring);
outline-offset: 1px;
}
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:disabled,
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:disabled,
:is(#knowledgeView, #kbDrawer) .kb-btn:disabled { opacity: .45; cursor: not-allowed; }
/* 实心强调:每页只有一个页面级主操作(弹窗/抽屉内另计) */
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark),
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark),
:is(#knowledgeView, #kbDrawer) .kb-btn.primary,
#issuesView #newIssue,
.credential-btn.primary {
@@ -204,7 +204,7 @@ html[data-theme="dark"] {
background: var(--hui-accent);
color: var(--hui-on-accent);
}
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark):hover:not(:disabled),
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark):hover:not(:disabled),
:is(#knowledgeView, #kbDrawer) .kb-btn.primary:hover:not(:disabled),
#issuesView #newIssue:hover,
.credential-btn.primary:hover:not(:disabled) {
@@ -214,24 +214,24 @@ html[data-theme="dark"] {
}
/* 淡紫行内主操作 */
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft {
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft {
border-color: transparent;
background: var(--hui-accent-soft);
color: var(--hui-accent);
}
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft:hover:not(:disabled) {
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft:hover:not(:disabled) {
border-color: transparent;
background: color-mix(in srgb, var(--hui-accent) 16%, var(--hui-surface));
color: var(--hui-accent-hover);
}
/* 删除类:描边 */
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline {
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline {
border-color: color-mix(in srgb, var(--hui-error) 30%, var(--hui-border));
background: var(--hui-surface);
color: var(--hui-error);
}
-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline:hover:not(:disabled) {
+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #assistantView, #aiSchedulesView, #scheduleModal, #sharedSchedulePublishModal, #sharedScheduleVersionModal, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline:hover:not(:disabled) {
border-color: color-mix(in srgb, var(--hui-error) 30%, var(--hui-border));
background: color-mix(in srgb, var(--hui-error) 6%, var(--hui-surface));
color: var(--hui-error);
@@ -301,7 +301,7 @@ html[data-theme="dark"] {
/* ---------- 面板 / 卡片:圆角 14px、细边框、极浅阴影 ---------- */
.hui-panel,
-#botsView, #scheduleModal .bot-panel,
+#botsView, #assistantView, #scheduleModal .bot-panel,
#runsView .run-panel,
#knowledgeView :is(.kb-panel, .kb-metric) {
border: 1px solid var(--hui-border);
diff --git a/web/assistant_settings_test.go b/web/assistant_settings_test.go
new file mode 100644
index 00000000..cc0b82d9
--- /dev/null
+++ b/web/assistant_settings_test.go
@@ -0,0 +1,48 @@
+package web
+
+import (
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+func TestAssistantSettingsPageIsWired(t *testing.T) {
+ read := func(name string) string {
+ data, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(data)
+ }
+ index, app, ui, motion := read("index.html"), read("app.js"), read("app/harness-ui.css"), read("app/harness-motion.js")
+ for _, want := range []string{`data-view="assistant"`, `<section id="assistantView" class="view page-view">`, `<div id="assistantContent">`, `/app/assistant-settings.css`, `/app/assistant-settings.js`} {
+ if !strings.Contains(index, want) {
+ t.Fatalf("index.html is missing %q", want)
+ }
+ }
+ if strings.Index(index, `data-view="assistant"`) > strings.Index(index, `data-view="bots"`) || strings.Index(index, `data-view="assistant"`) < strings.Index(index, `data-view="settings"`) {
+ t.Fatal("AI 助手 belongs with personal settings, ahead of the project section")
+ }
+ for _, want := range []string{"'settings','assistant'", "assistant:'AI 助手'", "if(name==='assistant')loadAssistantSettings();"} {
+ if !strings.Contains(app, want) {
+ t.Fatalf("app.js is missing %q", want)
+ }
+ }
+ if !strings.Contains(motion, `assistant: "sparkles"`) {
+ t.Fatal("the AI 助手 nav entry needs its Harness icon")
+ }
+ if got, want := strings.Count(ui, "#assistantView"), strings.Count(ui, "#botsView"); got != want {
+ t.Fatalf("#assistantView must join every Harness scope #botsView is in: %d vs %d", got, want)
+ }
+}
+
+func TestAssistantSettingsForm(t *testing.T) {
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Skip("node not installed")
+ }
+ if out, err := exec.Command(node, "assistant_settings_test.js", "app/assistant-settings.js").CombinedOutput(); err != nil {
+ t.Fatalf("assistant settings: %v\n%s", err, out)
+ }
+}
diff --git a/web/assistant_settings_test.js b/web/assistant_settings_test.js
new file mode 100644
index 00000000..c20a1664
--- /dev/null
+++ b/web/assistant_settings_test.js
@@ -0,0 +1,33 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+
+const ctx = {
+ state: { currentUser: { id: 1 } },
+ escapeHTML: value => String(value).replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch])),
+ document: { querySelector: () => null },
+};
+vm.createContext(ctx);
+vm.runInContext(fs.readFileSync(process.argv[2], 'utf8') + '\n;globalThis.__mb={assistantPrefsUI,assistantPrefsFormHTML,assistantPrefsDirty,assistantPrefsSignedIn};', ctx);
+const mb = ctx.__mb;
+
+const html = mb.assistantPrefsFormHTML({ proactiveRoles: true, proactiveSops: false, instructions: '先给结论 <b>&' });
+assert.match(html, /role="switch" name="proactiveRoles" checked/);
+assert.match(html, /role="switch" name="proactiveSops" >/);
+assert.match(html, /maxlength="4000"/);
+assert.match(html, />先给结论 &lt;b&gt;&amp;<\/textarea>/, 'rules must be escaped inside the textarea');
+assert.match(html, /9 \/ 4000/);
+assert.match(html, /id="assistantPrefsSave" disabled/);
+
+const form = { proactiveRoles: { checked: true }, proactiveSops: { checked: false }, instructions: { value: ' 先给结论 ' } };
+mb.assistantPrefsUI.saved = { proactiveRoles: true, proactiveSops: false, instructions: '先给结论' };
+assert.equal(mb.assistantPrefsDirty(form), false, 'surrounding whitespace is not a change');
+form.proactiveSops.checked = true;
+assert.equal(mb.assistantPrefsDirty(form), true);
+form.proactiveSops.checked = false;
+form.instructions.value = '先给结论,再给细节';
+assert.equal(mb.assistantPrefsDirty(form), true);
+
+ctx.state.currentUser = { id: 0, isGuest: true };
+assert.equal(mb.assistantPrefsSignedIn(), false);
diff --git a/web/i18n-en.js b/web/i18n-en.js
index 354d4556..fe8d1083 100644
--- a/web/i18n-en.js
+++ b/web/i18n-en.js
@@ -121,4 +121,22 @@ Object.assign(window.LF_I18N_EN,{
"默认运行沙箱":"Default sandbox",
"默认运行沙箱不能删除;可编辑配置或新建其他沙箱":"The default sandbox cannot be deleted; edit its settings or create another sandbox."
});
+Object.assign(window.LF_I18N_EN,{
+"AI 助手":"AI assistant",
+"AI 工作台里和你对话、帮你动手的助手。设置它什么时候主动把事情交给角色或 SOP,以及每次对话都要遵守的规则;只对你自己生效。":"The assistant you talk to in the AI workbench. Choose when it hands work to a role or an SOP, and the rules every conversation follows. This applies only to you.",
+"登录后可以设置 AI 助手。":"Sign in to configure the AI assistant.",
+"正在读取设置…":"Loading settings…",
+"主动派发":"Proactive handoff",
+"打开后 AI 助手会更主动地把事情交给角色或 SOP。派角色不需要确认;走 SOP 仍按审批模式先征求同意,完全权限下直接启动。":"When enabled, the assistant is more ready to hand work to a role or an SOP. Roles are dispatched directly. An SOP still follows the approval mode, and full access starts it immediately.",
+"主动派角色":"Dispatch roles",
+"整件事是某个角色的本职(如独立评审、整套测试),或改了高风险代码需要复核时,直接交给这个角色。":"Hand the whole job to a role when it is that role's work, such as an independent review or a full test pass, or when a risky code change needs a second look.",
+"主动走 SOP":"Use an SOP",
+"遇到要落到仓库的新需求时,先交给项目里用途对得上的 SOP,而不是自己直接改代码。":"For a new requirement that should land in the repository, hand it to a matching SOP instead of changing the code directly.",
+"自定义规则":"Custom rules",
+"每轮对话都会带上这些规则,适合写你的习惯和偏好;不会越过审批模式和平台规则。":"These rules go with every turn. Use them for your habits and preferences. They do not override approval mode or platform rules.",
+"规则":"Rules",
+"AI 助手设置已保存":"AI assistant settings saved",
+"保存设置失败,请重试":"Could not save settings. Try again.",
+"读取设置失败":"Could not load settings"
+});
Object.assign(window.LF_I18N_EN,{"平台目录":"Platform catalog","通用模板按名称绑定这些 MCP,添加到本项目后即可使用。":"Generic templates bind these MCPs by name. Add one to this project to use it.","已添加到当前项目":"Added to this project","添加中…":"Adding…"});
diff --git a/web/index.html b/web/index.html
index 7650e24f..9c88bac9 100644
--- a/web/index.html
+++ b/web/index.html
@@ -33,6 +33,7 @@
<link rel="stylesheet" href="/app/mcp.css">
<link rel="stylesheet" href="/app/flow-canvas.css?v=20261109cli">
<link rel="stylesheet" href="/app/page-feedback.css">
+ <link rel="stylesheet" href="/app/assistant-settings.css">
<link rel="stylesheet" href="/preferences.css">
<link rel="stylesheet" href="/app/issues-list.css">
<link rel="stylesheet" href="/app/requirement-wizard.css?v=20261031req1">
@@ -139,6 +140,7 @@
<div id="configurationNav" class="management-navigation">
<button class="nav management-back" data-jump="collaboration"><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="chevron-left" data-icon-motion="idle" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M15 6l-6 6 6 6"/></svg></span><span class="nav-label">返回工作台</span></button>
<button class="nav" data-view="settings"><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="user" data-icon-motion="idle" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle class="head" cx="12" cy="8" r="4"/><path class="body" d="M4 21a8 8 0 0 1 16 0"/></svg></span><span class="nav-label">个人配置</span></button>
+ <button class="nav" data-view="assistant" aria-label="AI 助手" title="AI 助手"><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="sparkles" data-icon-motion="idle" width="15" height="15" aria-hidden="true" focusable="false"></svg></span><span class="nav-label">AI 助手</span></button>
<p>项目</p>
<button class="nav" data-view="projects"><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="users" data-icon-motion="idle" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><g class="team-front"><circle cx="9" cy="8" r="3"/><path d="M3 20v-1a6 6 0 0 1 12 0v1"/></g><g class="team-back"><path d="M16 5a3 3 0 0 1 0 6M17 14a5 5 0 0 1 4 5v1"/></g></svg></span><span class="nav-label">项目配置</span></button>
<button class="nav" data-view="bots" aria-label="通道管理" title="通道管理"><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="robot" data-icon-motion="idle" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><rect x="4" y="8" width="16" height="11" rx="2"/><path class="antenna" d="M12 3v5"/><path class="eyes" d="M8 13h.01M16 13h.01"/><path class="mouth" d="M9 17h6"/></svg></span><span class="nav-label">通道管理</span></button>
@@ -309,6 +311,12 @@
</div>
<div id="botsContent"></div>
</section>
+ <section id="assistantView" class="view page-view">
+ <div class="page-heading">
+ <div><h1>AI 助手</h1><p>AI 工作台里和你对话、帮你动手的助手。设置它什么时候主动把事情交给角色或 SOP,以及每次对话都要遵守的规则;只对你自己生效。</p></div>
+ </div>
+ <div id="assistantContent"></div>
+ </section>
<!-- 运行记录 -->
<section id="runsView" class="view page-view">
<div class="page-heading runs-heading">
@@ -1299,6 +1307,7 @@
<script src="/app/shared-schedules.js"></script>
<script src="/app/notification-editor.js"></script>
<script src="/app/bots.js"></script>
+ <script src="/app/assistant-settings.js"></script>
<script src="/app/flow-history.js?v=20261030fd2"></script>
<script src="/app/flow-viewport.js?v=20261030fd2"></script>
<script src="/app/flow-palette.js?v=20261030fd2"></script>