Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5685: fix agent builder composer clearing and conversation routing (#6339)
Naiyuan Qing736fbc8a5f1b
diff --git a/apps/desktop/src/renderer/src/pages/ai-builder-session-page.tsx b/apps/desktop/src/renderer/src/pages/ai-builder-session-page.tsxnew file mode 100644index 0000000000..1d8e2b8e98--- /dev/null+++ b/apps/desktop/src/renderer/src/pages/ai-builder-session-page.tsx@@ -0,0 +1,8 @@+import { useParams } from "react-router-dom";+import { AiBuilderSessionPage as SharedAiBuilderSessionPage } from "@multica/views/agents";++export function AiBuilderSessionPage() {+ const { sessionId } = useParams<{ sessionId: string }>();+ if (!sessionId) return null;+ return <SharedAiBuilderSessionPage sessionId={sessionId} />;+}diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxindex accaef575a..806d5d5ccd 100644--- a/apps/desktop/src/renderer/src/routes.tsx+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -6,6 +6,7 @@ import { ProjectDetailPage } from "./pages/project-detail-page";import { AutopilotDetailPage } from "./pages/autopilot-detail-page";import { SkillDetailPage } from "./pages/skill-detail-page";import { AgentDetailPage } from "./pages/agent-detail-page";+import { AiBuilderSessionPage } from "./pages/ai-builder-session-page";import { MemberDetailPage } from "./pages/member-detail-page";import {RuntimeDetailPage,@@ -198,6 +199,11 @@ export const appRoutes: RouteObject[] = [element: <AiCreateAgentPage />,handle: { title: "Create Agent" },},+ {+ path: "agents/new/ai/:sessionId",+ element: <AiBuilderSessionPage />,+ handle: { title: "Create Agent" },+ },{path: "agents/:id",element: <AgentDetailPage />,diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/ai/[sessionId]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/ai/[sessionId]/page.tsxnew file mode 100644index 0000000000..599701fb37--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/ai/[sessionId]/page.tsx@@ -0,0 +1,13 @@+"use client";++import { use } from "react";+import { AiBuilderSessionPage } from "@multica/views/agents";++export default function NewAgentAiSessionRoute({+ params,+}: {+ params: Promise<{ sessionId: string }>;+}) {+ const { sessionId } = use(params);+ return <AiBuilderSessionPage sessionId={sessionId} />;+}diff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.tsindex 0711c892c1..1276cbe3b7 100644--- a/packages/core/diagnostics/diagnostic-context.ts+++ b/packages/core/diagnostics/diagnostic-context.ts@@ -63,6 +63,7 @@ const WORKSPACE_ROUTES: readonly RoutePattern[] = [["agents", "new"],["agents", "new", "manual"],["agents", "new", "ai"],+ ["agents", "new", "ai", ":sessionId"],["agents", ":id"],["members", ":id"],["squads"],diff --git a/packages/core/paths/paths.test.ts b/packages/core/paths/paths.test.tsindex 2b09355421..98ed656a7f 100644--- a/packages/core/paths/paths.test.ts+++ b/packages/core/paths/paths.test.ts@@ -14,6 +14,8 @@ describe("paths.workspace(slug)", () => {expect(ws.autopilotDetail("a1")).toBe("/acme/autopilots/a1");expect(ws.agents()).toBe("/acme/agents");expect(ws.newAgent()).toBe("/acme/agents/new");+ expect(ws.newAgentAi()).toBe("/acme/agents/new/ai");+ expect(ws.newAgentAiSession("sess_1")).toBe("/acme/agents/new/ai/sess_1");expect(ws.memberDetail("u1")).toBe("/acme/members/u1");expect(ws.inbox()).toBe("/acme/inbox");expect(ws.myIssues()).toBe("/acme/my-issues");diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.tsindex 3bdec60d11..b48f873e3b 100644--- a/packages/core/paths/paths.ts+++ b/packages/core/paths/paths.ts@@ -31,6 +31,11 @@ function workspaceScoped(slug: string) {// half-filled form survives a refresh and can be linked to directly.newAgentManual: () => `${ws}/agents/new/manual`,newAgentAi: () => `${ws}/agents/new/ai`,+ // One creation conversation. It is a durable object, not a step of the+ // route above: it survives leaving the studio and is resumed later, so it+ // owns an address instead of being a query param on the "start one" screen.+ newAgentAiSession: (sessionId: string) =>+ `${ws}/agents/new/ai/${encode(sessionId)}`,agentDetail: (id: string) => `${ws}/agents/${encode(id)}`,memberDetail: (id: string) => `${ws}/members/${encode(id)}`,squads: () => `${ws}/squads`,diff --git a/packages/views/agents/create/ai-builder-session-page.tsx b/packages/views/agents/create/ai-builder-session-page.tsxnew file mode 100644index 0000000000..fc98c067b0--- /dev/null+++ b/packages/views/agents/create/ai-builder-session-page.tsx@@ -0,0 +1,86 @@+"use client";++import { useCallback, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { agentBuilderSessionListOptions } from "@multica/core/agents";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { useNavigation } from "../../navigation";+import { useT } from "../../i18n";+import { BuilderWorkspace } from "./builder-workspace";+import { AgentCreateChip, AgentCreateShell } from "./create-shell";+import { withSquadParam } from "./squad-param";++/**+ * One creation conversation, addressed by its own session id.+ *+ * The id is in the path, not in component state or a query param, because this+ * conversation outlives the screen that started it: leaving the studio no+ * longer deletes it (#6307), so a refresh, a back/forward, a reopened tab and a+ * direct link all have to land back in the same chat.+ */+export function AiBuilderSessionPage({ sessionId }: { sessionId: string }) {+ const { t } = useT("agents");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const navigation = useNavigation();+ const squadId = navigation.searchParams.get("squad");+ // The runtime this conversation was just started on. It cannot be read back+ // for the first turn — a conversation joins the list only once it has a+ // message or a saved configuration — so the starting screen hands it over in+ // the URL. Absent on every later visit, by which point the list answers.+ const startedRuntimeId = navigation.searchParams.get("runtime") ?? "";++ const builderSessions = useQuery(agentBuilderSessionListOptions(wsId));+ const sessions = builderSessions.data ?? [];+ const sessionSettled = builderSessions.isSuccess || builderSessions.isError;+ const session = sessions.find((row) => row.session_id === sessionId);++ // Only the open conversation knows which runtime it settled on.+ const [runtimeLabel, setRuntimeLabel] = useState<string | null>(null);++ // The conversation is gone — discarded here, deleted from another tab, or a+ // link that outlived it. Replace rather than push: the address no longer+ // resolves, so it must not stay on the stack for a back to land on.+ const leave = useCallback(+ () => navigation.replace(withSquadParam(paths.newAgentAi(), squadId)),+ [navigation, paths, squadId],+ );++ return (+ <AgentCreateShell+ title={+ squadId+ ? t(($) => $.creation_studio.squad_title)+ : t(($) => $.creation_studio.title)+ }+ step={t(($) => $.creation_studio.step_ai)}+ onBack={() => navigation.push(paths.newAgent())}+ chips={+ <>+ <AgentCreateChip>+ {t(($) => $.creation_studio.modes.ai.title)}+ </AgentCreateChip>+ {runtimeLabel ? (+ <AgentCreateChip>{runtimeLabel}</AgentCreateChip>+ ) : null}+ </>+ }+ >+ <BuilderWorkspace+ // Switching conversations remounts everything below: the draft, the+ // applied-message marker and the composer all belong to one+ // conversation, and a remount is the only reset that cannot forget a+ // field.+ key={sessionId}+ sessionId={sessionId}+ squadId={squadId}+ session={session}+ sessionSettled={sessionSettled}+ fallbackRuntimeId={startedRuntimeId}+ onDiscarded={leave}+ onRuntimeLabel={setRuntimeLabel}+ />+ </AgentCreateShell>+ );+}diff --git a/packages/views/agents/create/ai-create-agent-page.tsx b/packages/views/agents/create/ai-create-agent-page.tsxindex d21a9e07af..6e9158ae12 100644--- a/packages/views/agents/create/ai-create-agent-page.tsx+++ b/packages/views/agents/create/ai-create-agent-page.tsx@@ -10,21 +10,23 @@ import type { RuntimeDevice } from "@multica/core/types";import { useNavigation } from "../../navigation";import { useT } from "../../i18n";import { BuilderSetupPanel } from "./builder-setup-panel";-import { BuilderWorkspace } from "./builder-workspace";import { AgentCreateChip, AgentCreateShell } from "./create-shell";import { createPathWithParams } from "./squad-param";/**- * Conversational agent creation.+ * Starting a conversational agent creation: pick where it will run.*- * The route holds the conversation list and the identity of the open one; each- * conversation's own state lives in {@link BuilderWorkspace}, mounted under a- * `key` so switching is a remount rather than a reset every future field would- * have to remember to join.+ * This route is the ACTION — one screen, one job. The conversation it produces+ * is a durable object and lives at its own address (ai-builder-session-page),+ * because it is left and resumed rather than completed in one sitting. Both+ * used to share this route, switched on a `?session=` param, which made the+ * route render two unrelated screens and left the conversation — the thing+ * with a lifetime — as a modifier on the thing without one.*- * `?session=` is what makes a conversation addressable — a refresh, a- * back/forward, and a reopened tab all land back in the same chat instead of- * silently starting a new one.+ * Entering a conversation REPLACES this entry. The runtime choice is consumed+ * the moment the session exists — it is frozen onto the hidden carrier agent+ * and cannot be revisited from here — so leaving it on the history stack would+ * only offer to start a second conversation on the way back.*/export function AiCreateAgentPage() {const { t } = useT("agents");@@ -32,49 +34,29 @@ export function AiCreateAgentPage() {const paths = useWorkspacePaths();const navigation = useNavigation();const squadId = navigation.searchParams.get("squad");- const sessionId = navigation.searchParams.get("session") ?? "";const builderSessions = useQuery(agentBuilderSessionListOptions(wsId));const sessions = builderSessions.data ?? [];- const sessionSettled = builderSessions.isSuccess || builderSessions.isError;- const openSession = sessions.find(- (session) => session.session_id === sessionId,- );- // The chip has to say something before the list answers, and only the open- // pane knows which runtime it settled on.+ // The chip has to say something before a runtime is settled on.const [runtimeLabel, setRuntimeLabel] = useState<string | null>(null);- // The runtime a just-started conversation was created with. It cannot be read- // back yet — a conversation joins the list only once it has a message — and- // without it the first turn would render against the first runtime in the- // list instead of the one the user picked.- const [startedRuntimeId, setStartedRuntimeId] = useState("");-- const handleSetupRuntimeLabel = useCallback(+ const handleRuntimeLabel = useCallback((runtime: RuntimeDevice | null) =>setRuntimeLabel(runtime ? runtimeDisplayLabel(runtime) : null),[],);const open = useCallback(- (nextSessionId: string) =>+ (sessionId: string, runtimeId: string | null) =>navigation.replace(- createPathWithParams(paths.newAgentAi(), {+ createPathWithParams(paths.newAgentAiSession(sessionId), {squad: squadId,- session: nextSessionId,+ runtime: runtimeId,}),),[navigation, paths, squadId],);- const closeSession = useCallback(- () =>- navigation.replace(- createPathWithParams(paths.newAgentAi(), { squad: squadId }),- ),- [navigation, paths, squadId],- );-return (<AgentCreateShelltitle={@@ -95,35 +77,14 @@ export function AiCreateAgentPage() {</>}>- {sessionId ? (- <BuilderWorkspace- // Switching conversations remounts everything below: the draft, the- // applied-message marker and the composer all belong to one- // conversation, and a remount is the only reset that cannot forget a- // field.- key={sessionId}- sessionId={sessionId}- squadId={squadId}- session={openSession}- sessionSettled={sessionSettled}- fallbackRuntimeId={startedRuntimeId}- onDiscarded={closeSession}- onRuntimeLabel={setRuntimeLabel}- />- ) : (- <BuilderSetupPanel- sessions={sessions}- onResume={(nextSessionId) => {- setStartedRuntimeId("");- open(nextSessionId);- }}- onStarted={(nextSessionId, runtimeId) => {- setStartedRuntimeId(runtimeId);- open(nextSessionId);- }}- onRuntimeLabel={handleSetupRuntimeLabel}- />- )}+ <BuilderSetupPanel+ sessions={sessions}+ // Resuming carries no runtime seed: a listed conversation reports its+ // own, which is the truthful answer after a runtime switch.+ onResume={(sessionId) => open(sessionId, null)}+ onStarted={(sessionId, runtimeId) => open(sessionId, runtimeId)}+ onRuntimeLabel={handleRuntimeLabel}+ /></AgentCreateShell>);}diff --git a/packages/views/agents/create/builder-conversation.tsx b/packages/views/agents/create/builder-conversation.tsxindex 49b46921a5..2a70aea5c4 100644--- a/packages/views/agents/create/builder-conversation.tsx+++ b/packages/views/agents/create/builder-conversation.tsx@@ -146,7 +146,9 @@ export function BuilderConversation({| { task_id?: string; status?: string; created_at?: string }| undefined;runtimeOnline: boolean;- onSend: (content: string) => Promise<boolean>;+ /** `commitInput` is the composer's clear; the owner runs it as soon as the+ * server accepts the message. The prompt buttons below send without one. */+ onSend: (content: string, commitInput?: () => void) => Promise<boolean>;onStop: () => void;restoreDraftRequest: BuilderRestore | null;onRestoreDraftApplied: () => void;@@ -235,7 +237,9 @@ export function BuilderConversation({) : null}<ChatInput- onSend={(content) => onSend(content)}+ onSend={(content, _attachmentIds, commitInput) =>+ onSend(content, commitInput)+ }onStop={onStop}isRunning={pending}disabled={!runtimeOnline}diff --git a/packages/views/agents/create/index.ts b/packages/views/agents/create/index.tsindex d80c5f1a32..153061d5f4 100644--- a/packages/views/agents/create/index.ts+++ b/packages/views/agents/create/index.ts@@ -1,6 +1,7 @@-// The three route entry points. Everything else in this folder is internal to-// the flow and already imported by path — re-exporting it here only created a+// The route entry points. Everything else in this folder is internal to the+// flow and already imported by path — re-exporting it here only created a// second name for the same thing and a list to keep in sync.export { ChooseCreateMethodPage } from "./choose-create-method-page";export { ManualCreateAgentPage } from "./manual-create-agent-page";export { AiCreateAgentPage } from "./ai-create-agent-page";+export { AiBuilderSessionPage } from "./ai-builder-session-page";diff --git a/packages/views/agents/create/squad-param.ts b/packages/views/agents/create/squad-param.tsindex abbb984b42..eacccda01d 100644--- a/packages/views/agents/create/squad-param.ts+++ b/packages/views/agents/create/squad-param.ts@@ -3,17 +3,21 @@* between screens.** `squad` is the reason the flow was opened at all, so it rides along from the- * chooser into whichever method the user picks. `session` addresses one builder- * conversation, so a refresh, a back/forward, or a reopened tab lands back in- * the same chat instead of starting a new one.+ * chooser into whichever method the user picks.+ *+ * `runtime` is a seed, not an identity: a conversation joins the sessions list+ * only once it holds a message or a saved configuration, so for the first turn+ * the runtime the user just picked cannot be read back from anywhere. It rides+ * in the URL rather than in component state so a refresh on that first turn+ * still knows where the conversation runs.*/export function createPathWithParams(path: string,- params: { squad?: string | null; session?: string | null },+ params: { squad?: string | null; runtime?: string | null },): string {const query = new URLSearchParams();if (params.squad) query.set("squad", params.squad);- if (params.session) query.set("session", params.session);+ if (params.runtime) query.set("runtime", params.runtime);const suffix = query.toString();return suffix ? `${path}?${suffix}` : path;}diff --git a/packages/views/agents/create/use-builder-session.ts b/packages/views/agents/create/use-builder-session.tsindex ea851e95fe..39b4cd312b 100644--- a/packages/views/agents/create/use-builder-session.ts+++ b/packages/views/agents/create/use-builder-session.ts@@ -207,7 +207,22 @@ export function useBuilderSession(options: {}};- const send = async (content: string): Promise<boolean> => {+ /**+ * Sends one turn.+ *+ * `commitInput` is the composer's clear (MUL-5181): it runs the moment the+ * server has accepted the message and the caches render it, NOT after the+ * reconciling invalidations settle. Awaiting those held the user's text in+ * the box for three more round-trips while their message was already on+ * screen. Same ordering as the main chat's handleSend.+ *+ * Optional because the empty-state prompt buttons call this directly, with+ * no composer to clear.+ */+ const send = async (+ content: string,+ commitInput?: () => void,+ ): Promise<boolean> => {const text = content.trim();// switchingRuntime blocks the send while a rebind is in flight: the server// serialises the two anyway, but letting the message through would mean the@@ -240,13 +255,13 @@ export function useBuilderSession(options: {status: "queued",created_at: createdAt,});- await Promise.all([- qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) }),- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) }),- // The first turn is what makes a brand-new conversation listable at- // all, and every later one moves it to the top with a new preview.- invalidateDraftList(),- ]);+ // Accepted and rendered — release the composer before reconciling.+ commitInput?.();+ void qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });+ void qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });+ // The first turn is what makes a brand-new conversation listable at+ // all, and every later one moves it to the top with a new preview.+ void invalidateDraftList();return true;} catch (err) {setError(diff --git a/packages/views/agents/index.ts b/packages/views/agents/index.tsindex 66fbb70a8a..e431d0107e 100644--- a/packages/views/agents/index.ts+++ b/packages/views/agents/index.ts@@ -3,4 +3,5 @@ export {ChooseCreateMethodPage,ManualCreateAgentPage,AiCreateAgentPage,+ AiBuilderSessionPage,} from "./create";