Skip to content
TypeScript

fix(web): queued-message edits survive navigation and settle once (#24972)

Julius Marminge7561c2e6317a
diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts
index 238534d91de..5d1d9fce271 100644
--- a/apps/web/src/components/chat/queuedMessageEdit.ts
+++ b/apps/web/src/components/chat/queuedMessageEdit.ts
@@ -1,3 +1,4 @@
+import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit";
import type { ChatAttachment } from "@t3tools/contracts";
import {
composerDraftHasUserContent,
@@ -14,15 +15,18 @@ export function recoverQueuedMessageEdit(input: {
}): "kept" | "discarded" | "clean" {
const store = useComposerDraftStore.getState();
const draft = store.getComposerDraft(input.editTarget);
- const dirty =
- draft !== null &&
- (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0);
- if (dirty && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget))) {
+ const recovery = resolveQueuedEditExit({
+ editChanged:
+ draft !== null &&
+ (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0),
+ threadDraftEmpty: !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)),
+ });
+ if (recovery === "kept") {
store.moveComposerPromptAndImages(input.editTarget, input.threadTarget);
- return "kept";
+ } else {
+ store.clearComposerContent(input.editTarget);
}
- store.clearComposerContent(input.editTarget);
- return dirty ? "discarded" : "clean";
+ return recovery;
}
export async function prepareQueuedEditAttachments(input: {
diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx
new file mode 100644
index 00000000000..c01fa57b4e2
--- /dev/null
+++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx
@@ -0,0 +1,195 @@
+import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
+import {
+ EnvironmentId,
+ MessageId,
+ RunId,
+ ThreadId,
+ type ScopedThreadRef,
+} from "@t3tools/contracts";
+import { useImperativeHandle, type RefObject } from "react";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { act, render } from "../../../test/render";
+import { useComposerDraftStore } from "../../composerDraftStore";
+import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
+import { useQueuedRunEdit } from "./useQueuedRunEdit";
+
+interface RunStatus {
+ readonly id: RunId;
+ readonly status: string;
+}
+
+const mocks = await vi.hoisted(async () => {
+ const { Atom } = await import("effect/reactivity");
+ return {
+ editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(),
+ // The projection's runs per thread, written by each test to stand in for the server.
+ threadRuns: Atom.family((_key: string) =>
+ Atom.make<ReadonlyArray<RunStatus> | null>(null).pipe(Atom.keepAlive),
+ ),
+ };
+});
+
+vi.mock("../../state/use-atom-command", () => ({
+ useAtomCommand: () => mocks.editQueuedRun,
+}));
+
+const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
+
+vi.mock("../../state/threads", async () => {
+ const { Atom } = await import("effect/reactivity");
+ const key = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
+ return {
+ threadEnvironment: {
+ snapshotAtom: () => Atom.make(null),
+ editQueuedRun: {},
+ },
+ environmentThreadDetails: {
+ statusAtom: () => Atom.make("ready"),
+ quietThreadAtom: (ref: ScopedThreadRef) =>
+ Atom.make((get) => {
+ const runs = get(mocks.threadRuns(key(ref)));
+ return runs === null ? null : { projection: { runs } };
+ }),
+ },
+ environmentThreadShells: {
+ threadShellAtom: () => Atom.make(null),
+ },
+ };
+});
+
+const ENV = EnvironmentId.make("env-1");
+const THREAD_A: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-a") };
+const THREAD_B: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-b") };
+const RUN = RunId.make("run-1");
+
+type HookResult = ReturnType<typeof useQueuedRunEdit>;
+
+function projection(runs: ReadonlyArray<RunStatus>) {
+ return { runs, messages: [] } as unknown as ThreadStructure;
+}
+
+function setRuns(ref: ScopedThreadRef, status: string) {
+ appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
+}
+
+function Harness(props: {
+ readonly threadRef: ScopedThreadRef;
+ readonly runStatus: string;
+ readonly hookRef: RefObject<HookResult | null>;
+}) {
+ const result = useQueuedRunEdit({
+ environmentId: ENV,
+ routeThreadRef: props.threadRef,
+ threadDraftTarget: props.threadRef,
+ activeThreadId: props.threadRef.threadId,
+ serverProjection: projection([{ id: RUN, status: props.runStatus }]),
+ promptRef: { current: "" },
+ composerRef: { current: null },
+ });
+ useImperativeHandle(props.hookRef, () => result);
+ return null;
+}
+
+function view(threadRef: ScopedThreadRef, runStatus: string, hook: { current: HookResult | null }) {
+ return (
+ <AppAtomRegistryProvider>
+ <Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} />
+ </AppAtomRegistryProvider>
+ );
+}
+
+function setup() {
+ mocks.editQueuedRun.mockReset();
+ useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
+ setRuns(THREAD_A, "queued");
+ setRuns(THREAD_B, "queued");
+ return { hook: { current: null as HookResult | null } };
+}
+
+function requireHook(hook: { current: HookResult | null }): HookResult {
+ if (hook.current === null) throw new Error("hook did not render");
+ return hook.current;
+}
+
+async function beginChangedEdit(hook: { current: HookResult | null }) {
+ await act(() =>
+ requireHook(hook).beginEdit({
+ runId: RUN,
+ messageId: MessageId.make("message-1"),
+ text: "original",
+ attachments: [],
+ }),
+ );
+ await act(() =>
+ useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"),
+ );
+}
+
+const promptOf = (ref: ScopedThreadRef) =>
+ useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
+
+describe("useQueuedRunEdit", () => {
+ it("keeps an open edit when the user leaves the thread and comes back", async () => {
+ const { hook } = setup();
+ await using screen = await render(view(THREAD_A, "queued", hook));
+ await beginChangedEdit(hook);
+
+ await screen.rerender(view(THREAD_B, "queued", hook));
+ expect(requireHook(hook).isEditing).toBe(false);
+ await screen.rerender(view(THREAD_A, "queued", hook));
+
+ expect(requireHook(hook).editingRunId).toBe(RUN);
+ expect(
+ useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
+ ).toBe("changed");
+ });
+
+ it("moves a changed edit into the thread draft when its run starts while the user is away", async () => {
+ const { hook } = setup();
+ await using screen = await render(view(THREAD_A, "queued", hook));
+ await beginChangedEdit(hook);
+
+ await screen.rerender(view(THREAD_B, "queued", hook));
+ expect(promptOf(THREAD_A)).toBe("");
+ await act(() => setRuns(THREAD_A, "running"));
+
+ expect(promptOf(THREAD_A)).toBe("changed");
+ });
+
+ it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => {
+ const { hook } = setup();
+ let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
+ mocks.editQueuedRun.mockReturnValue(
+ new Promise((resolve) => {
+ finishSave = resolve;
+ }),
+ );
+ await using screen = await render(view(THREAD_A, "queued", hook));
+ await beginChangedEdit(hook);
+
+ // Not inside act(): act would hold the projection update until the save settles.
+ const saved = requireHook(hook).saveEdit(
+ {
+ prompt: "changed",
+ images: [],
+ files: [],
+ terminalContexts: [],
+ reviewComments: [],
+ previewAnnotations: [],
+ threadContexts: [],
+ },
+ () => {},
+ );
+ await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
+ // The server applied the edit and then started the run; the projection
+ // reports the start before the edit's acknowledgement arrives.
+ await act(() => setRuns(THREAD_A, "running"));
+ await screen.rerender(view(THREAD_A, "running", hook));
+ finishSave({ _tag: "Success" });
+ await act(() => saved);
+
+ expect(requireHook(hook).isEditing).toBe(false);
+ expect(promptOf(THREAD_A)).toBe("");
+ });
+});
diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts
index 44a828a7b8f..a9fbf7408dd 100644
--- a/apps/web/src/components/chat/useQueuedRunEdit.ts
+++ b/apps/web/src/components/chat/useQueuedRunEdit.ts
@@ -1,3 +1,8 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ makeQueuedRunEditStore,
+ makeQueuedRunsAtom,
+} from "@t3tools/client-runtime/queued-run-edit";
import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -13,7 +18,8 @@ import {
} from "@t3tools/contracts";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
-import { useEffect, useRef, useState, type RefObject } from "react";
+import { Atom } from "effect/reactivity";
+import { useRef, useState, type RefObject } from "react";
import { useAssetUrls } from "../../assets/assetUrls";
import {
DraftId,
@@ -35,7 +41,11 @@ import type { TerminalContextDraft } from "../../lib/terminalContext";
import type { ReviewCommentContext } from "../../reviewCommentContext";
import { appAtomRegistry } from "../../rpc/atomRegistry";
import { environmentServerConfigsAtom } from "../../state/server";
-import { threadEnvironment } from "../../state/threads";
+import {
+ environmentThreadDetails,
+ environmentThreadShells,
+ threadEnvironment,
+} from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { stackedThreadToast, toastManager } from "../ui/toast";
import type { ChatComposerHandle } from "./ChatComposer";
@@ -52,6 +62,12 @@ interface EditingQueuedRun {
readonly context?: OrchestrationMessageContext | undefined;
}
+// Keyed by the route thread, so an edit survives navigating away and back.
+const queuedRunEdits = makeQueuedRunEditStore<EditingQueuedRun>({
+ registry: appAtomRegistry,
+ label: "web-queued-run-edits",
+});
+
export interface QueuedRunEditContent {
readonly prompt: string;
readonly images: ReadonlyArray<ComposerImageAttachment>;
@@ -174,12 +190,11 @@ export function useQueuedRunEdit(input: {
composerRef,
} = input;
const editQueuedRunCommand = useEditQueuedRunCommand();
- const [editing, setEditing] = useState<EditingQueuedRun | null>(null);
+ const editKey = scopedThreadKey(routeThreadRef);
+ const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null;
+ const editing = activeThreadId === null ? null : storedEdit;
const saveInFlightRef = useRef(false);
const [isSaving, setIsSaving] = useState(false);
- if (editing !== null && activeThreadId !== editing.threadId) {
- setEditing(null);
- }
const draftTarget =
editing === null ? threadDraftTarget : queuedEditDraftTarget(routeThreadRef, editing.runId);
@@ -213,62 +228,73 @@ export function useQueuedRunEdit(input: {
const store = useComposerDraftStore.getState();
store.clearComposerContent(target);
store.setPrompt(target, request.text);
- setEditing({
- threadId: activeThreadId,
- runId: request.runId,
- messageId: request.messageId,
- originalText: request.text,
- existingAttachments: request.attachments,
- context: serverProjection?.messages.find((message) => message.id === request.messageId)
- ?.context,
- });
+ const threadRef = { environmentId, threadId: activeThreadId };
+ queuedRunEdits.begin(
+ editKey,
+ {
+ threadId: activeThreadId,
+ runId: request.runId,
+ messageId: request.messageId,
+ originalText: request.text,
+ existingAttachments: request.attachments,
+ context: serverProjection?.messages.find((message) => message.id === request.messageId)
+ ?.context,
+ },
+ {
+ runs: makeQueuedRunsAtom({
+ threadId: activeThreadId,
+ snapshot: threadEnvironment.snapshotAtom(environmentId),
+ detailStatus: environmentThreadDetails.statusAtom(threadRef),
+ runs: Atom.make(
+ (get) =>
+ get(environmentThreadDetails.quietThreadAtom(threadRef))?.projection.runs ?? null,
+ ),
+ }),
+ // The run started or was cancelled from another client. A changed
+ // edit moves into the thread's own draft when that draft is empty;
+ // otherwise it is dropped. Edits outlive navigation, so the toast is
+ // unscoped and names the thread: the user may be anywhere by now.
+ onRunLeftQueue: (_, edit) => {
+ const recovery = recoverQueuedMessageEdit({
+ editTarget: queuedEditDraftTarget(routeThreadRef, edit.runId),
+ threadTarget: threadDraftTarget,
+ originalText: edit.originalText,
+ });
+ if (recovery === "clean") return;
+ const title = appAtomRegistry.get(
+ environmentThreadShells.threadShellAtom(threadRef),
+ )?.title;
+ const where = title === undefined ? "" : ` in “${title}”`;
+ toastManager.add(
+ stackedThreadToast({
+ type: recovery === "kept" ? "info" : "warning",
+ title: "Queued message is no longer queued",
+ description:
+ recovery === "kept"
+ ? `Your unsaved edit${where} was kept in the composer.`
+ : `Your unsaved edit${where} was discarded.`,
+ }),
+ );
+ },
+ },
+ );
focusComposerSoon();
});
const cancelEdit = useStableCallback(() => {
if (editing === null) return;
clearEditDraft(editing.runId);
- setEditing(null);
+ queuedRunEdits.end(editKey);
focusComposerSoon();
});
const removeEditingAttachment = useStableCallback((attachmentId: string) => {
- setEditing((current) =>
- current === null
- ? current
- : {
- ...current,
- existingAttachments: current.existingAttachments.filter(
- (attachment) => attachment.id !== attachmentId,
- ),
- },
- );
+ queuedRunEdits.update(editKey, (current) => ({
+ ...current,
+ existingAttachments: current.existingAttachments.filter(
+ (attachment) => attachment.id !== attachmentId,
+ ),
+ }));
});
- useEffect(() => {
- if (editing === null || activeThreadId !== editing.threadId) return;
- if (serverProjection === null) return;
- const run = serverProjection.runs.find((candidate) => candidate.id === editing.runId);
- if (run !== undefined && run.status === "queued") return;
- const recovery = recoverQueuedMessageEdit({
- editTarget: queuedEditDraftTarget(routeThreadRef, editing.runId),
- threadTarget: threadDraftTarget,
- originalText: editing.originalText,
- });
- if (recovery !== "clean") {
- toastManager.add(
- stackedThreadToast({
- type: recovery === "kept" ? "info" : "warning",
- title: "Queued message is no longer queued",
- description:
- recovery === "kept"
- ? "Your unsaved edit was kept in the composer."
- : "Your unsaved edit was discarded.",
- }),
- );
- }
- // oxlint-disable-next-line react/set-state-in-effect -- Leaving edit mode follows the draft recovery and toast above, which must run once after commit.
- setEditing(null);
- }, [activeThreadId, editing, routeThreadRef, serverProjection, threadDraftTarget]);
-
const saveEdit = async (
content: QueuedRunEditContent,
setThreadError: (threadId: ThreadId, error: string | null) => void,
@@ -294,6 +320,8 @@ export function useQueuedRunEdit(input: {
}
saveInFlightRef.current = true;
setIsSaving(true);
+ // The save's result decides the edit's fate, even if the run starts meanwhile.
+ queuedRunEdits.suspendExitWatch(editKey);
const error = await submitQueuedRunEdit({
environmentId,
draftTarget,
@@ -304,12 +332,15 @@ export function useQueuedRunEdit(input: {
saveInFlightRef.current = false;
setIsSaving(false);
setThreadError(editing.threadId, error);
- if (error !== null) return;
+ if (error !== null) {
+ queuedRunEdits.resumeExitWatch(editKey);
+ return;
+ }
releaseDraftAttachments(newAttachments);
promptRef.current = "";
clearEditDraft(editing.runId);
composerRef.current?.resetCursorState();
- setEditing(null);
+ queuedRunEdits.end(editKey);
focusComposerSoon();
};
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 5ae338b7d59..a58a39bc345 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -147,6 +147,10 @@
"types": "./src/webhookAddress.ts",
"default": "./src/webhookAddress.ts"
},
+ "./queued-run-edit": {
+ "types": "./src/queuedRunEdit.ts",
+ "default": "./src/queuedRunEdit.ts"
+ },
"./delayed-status": {
"types": "./src/delayedStatus.ts",
"default": "./src/delayedStatus.ts"
diff --git a/packages/client-runtime/src/queuedRunEdit.test.ts b/packages/client-runtime/src/queuedRunEdit.test.ts
new file mode 100644
index 00000000000..b5f560f849f
--- /dev/null
+++ b/packages/client-runtime/src/queuedRunEdit.test.ts
@@ -0,0 +1,217 @@
+import { RunId } from "@t3tools/contracts";
+import { Atom, AtomRegistry } from "effect/reactivity";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ makeQueuedRunEditStore,
+ makeQueuedRunsAtom,
+ resolveQueuedEditExit,
+ type QueuedRunStatus,
+} from "./queuedRunEdit.ts";
+
+const RUN = RunId.make("run-1");
+const queued = (status = "queued"): ReadonlyArray<QueuedRunStatus> => [{ id: RUN, status }];
+
+function setup(initialRuns: ReadonlyArray<QueuedRunStatus> | null = queued()) {
+ const registry = AtomRegistry.make();
+ const runs = Atom.make<ReadonlyArray<QueuedRunStatus> | null>(initialRuns);
+ const store = makeQueuedRunEditStore<{ readonly runId: RunId; readonly text: string }>({
+ registry,
+ label: "test-queued-run-edits",
+ });
+ const exits: Array<{ threadKey: string; text: string }> = [];
+ const begin = () =>
+ store.begin(
+ "env:thread",
+ { runId: RUN, text: "draft" },
+ { runs, onRunLeftQueue: (threadKey, edit) => exits.push({ threadKey, text: edit.text }) },
+ );
+ return { registry, runs, store, exits, begin };
+}
+
+describe("resolveQueuedEditExit", () => {
+ it("closes an unchanged edit without touching drafts", () => {
+ expect(resolveQueuedEditExit({ editChanged: false, threadDraftEmpty: true })).toBe("clean");
+ });
+
+ it("keeps a changed edit only when the thread draft is empty", () => {
+ expect(resolveQueuedEditExit({ editChanged: true, threadDraftEmpty: true })).toBe("kept");
+ expect(resolveQueuedEditExit({ editChanged: true, threadDraftEmpty: false })).toBe("discarded");
+ });
+});
+
+describe("makeQueuedRunEditStore", () => {
+ it("fires once when the edited run leaves the queue, with the latest edit", () => {
+ const { registry, runs, store, exits, begin } = setup();
+ begin();
+ store.update("env:thread", (edit) => ({ ...edit, text: "changed" }));
+ registry.set(runs, queued());
+ expect(exits).toEqual([]);
+ registry.set(runs, queued("running"));
+ registry.set(runs, []);
+ expect(exits).toEqual([{ threadKey: "env:thread", text: "changed" }]);
+ });
+
+ it("waits while the runs are unknown and treats a vanished run as left", () => {
+ const { registry, runs, exits, begin } = setup(null);
+ begin();
+ expect(exits).toEqual([]);
+ registry.set(runs, []);
+ expect(exits).toHaveLength(1);
+ });
+
+ it("fires immediately when the run already left the queue", () => {
+ const { exits, begin } = setup(queued("running"));
+ begin();
+ expect(exits).toHaveLength(1);
+ });
+
+ it("stops watching when the edit ends", () => {
+ const { registry, runs, store, exits, begin } = setup();
+ begin();
+ store.end("env:thread");
+ registry.set(runs, []);
+ expect(exits).toEqual([]);
+ expect(store.get("env:thread")).toBeNull();
+ });
+
+ it("holds the exit during a save and replays it when the save fails", () => {
+ const { registry, runs, store, exits, begin } = setup();
+ begin();
+ store.suspendExitWatch("env:thread");
+ registry.set(runs, []);
+ expect(exits).toEqual([]);
+ store.resumeExitWatch("env:thread");
+ expect(exits).toHaveLength(1);
+ });
+
+ // The runs read the thread's detail, a live server subscription; a thread
+ // with no edit open must not keep it.
+ it("holds the thread's runs only while an edit is open and watching", () => {
+ // The registry removes idle nodes in a scheduled task; the test runs those tasks itself.
+ const tasks: Array<() => void> = [];
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ tasks.push(task);
+ return () => {};
+ },
+ });
+ const settle = () => {
+ for (const task of tasks.splice(0)) task();
+ };
+ const source = Atom.make<ReadonlyArray<QueuedRunStatus> | null>(queued());
+ let mounted = 0;
+ const runs = Atom.make((get) => {
+ mounted += 1;
+ get.addFinalizer(() => {
+ mounted -= 1;
+ });
+ return get(source);
+ });
+ const store = makeQueuedRunEditStore<{ readonly runId: RunId }>({
+ registry,
+ label: "test-queued-run-edits",
+ });
+ const begin = () =>
+ store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: () => {} });
+
+ begin();
+ expect(mounted).toBe(1);
+ store.end("env:thread");
+ settle();
+ expect(mounted).toBe(0);
+
+ begin();
+ store.suspendExitWatch("env:thread");
+ settle();
+ expect(mounted).toBe(0);
+ store.resumeExitWatch("env:thread");
+ expect(mounted).toBe(1);
+
+ registry.set(source, []);
+ expect(store.get("env:thread")).toBeNull();
+ settle();
+ expect(mounted).toBe(0);
+ });
+});
+
+describe("makeQueuedRunsAtom", () => {
+ const thread = (overrides: { archivedAt?: string | null; deletedAt?: string | null } = {}) => ({
+ id: "thread-1",
+ archivedAt: null,
+ deletedAt: null,
+ ...overrides,
+ });
+
+ function setupWatched() {
+ const registry = AtomRegistry.make();
+ const snapshot = Atom.make<{ threads: ReadonlyArray<ReturnType<typeof thread>> } | null>({
+ threads: [thread()],
+ });
+ let detailReads = 0;
+ const detailStatus = Atom.make("live");
+ const detail = Atom.make<ReadonlyArray<QueuedRunStatus> | null>(queued());
+ const runs = makeQueuedRunsAtom({
+ threadId: "thread-1",
+ snapshot,
+ detailStatus,
+ runs: Atom.make((get) => {
+ detailReads += 1;
+ return get(detail);
+ }),
+ });
+ const store = makeQueuedRunEditStore<{ readonly runId: RunId }>({
+ registry,
+ label: "test-queued-run-edits",
+ });
+ const exits: Array<string> = [];
+ store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: (key) => exits.push(key) });
+ return {
+ registry,
+ snapshot,
+ detailStatus,
+ detail,
+ store,
+ exits,
+ detailReads: () => detailReads,
+ };
+ }
+
+ it("ends the edit when the shell marks the thread deleted, without reading its detail again", () => {
+ const { registry, snapshot, detail, exits, detailReads } = setupWatched();
+ expect(exits).toEqual([]);
+ registry.set(snapshot, { threads: [thread({ deletedAt: "2026-10-24T00:00:00Z" })] });
+ expect(exits).toEqual(["env:thread"]);
+ const reads = detailReads();
+ registry.set(detail, []);
+ expect(detailReads()).toBe(reads);
+ });
+
+ it("ends the edit when the detail reports the thread gone", () => {
+ const { registry, snapshot, detailStatus, exits } = setupWatched();
+ registry.set(snapshot, { threads: [] });
+ expect(exits).toEqual([]);
+ registry.set(detailStatus, "deleted");
+ expect(exits).toEqual(["env:thread"]);
+ });
+
+ it("keeps an archived thread's edit open, ending it only when the run leaves the queue", () => {
+ const { registry, snapshot, detail, store, exits } = setupWatched();
+ // The shell drops archived threads, but their queue stays editable.
+ registry.set(snapshot, { threads: [] });
+ registry.set(snapshot, { threads: [thread({ archivedAt: "2026-10-24T00:00:00Z" })] });
+ expect(exits).toEqual([]);
+ expect(store.get("env:thread")).not.toBeNull();
+ registry.set(detail, queued("running"));
+ expect(exits).toEqual(["env:thread"]);
+ });
+
+ it("waits while the thread detail is unknown", () => {
+ const { registry, snapshot, detail, exits } = setupWatched();
+ registry.set(snapshot, null);
+ registry.set(detail, null);
+ expect(exits).toEqual([]);
+ registry.set(detail, []);
+ expect(exits).toEqual(["env:thread"]);
+ });
+});
diff --git a/packages/client-runtime/src/queuedRunEdit.ts b/packages/client-runtime/src/queuedRunEdit.ts
new file mode 100644
index 00000000000..809e8dcfa6c
--- /dev/null
+++ b/packages/client-runtime/src/queuedRunEdit.ts
@@ -0,0 +1,167 @@
+/**
+ * A queued-message edit ends on save, cancel, or when its run leaves the queue.
+ * The store owns one watcher per edit, so "run left the queue" is handled exactly
+ * once, when the projection reports it, wherever the user is in the app.
+ */
+import type { RunId } from "@t3tools/contracts";
+import { Atom, type AtomRegistry } from "effect/reactivity";
+
+export interface QueuedRunStatus {
+ readonly id: RunId;
+ readonly status: string;
+}
+
+/** The thread's runs, or null while they are unknown (detail not loaded yet). */
+export type QueuedRunsAtom = Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
+
+interface ShellThreadPresence {
+ readonly id: string;
+ readonly deletedAt: unknown;
+}
+
+/**
+ * The edited thread's runs. A deleted thread (shell `deletedAt` or detail status
+ * `deleted`) reads as no runs, so its edit ends. Absence from the shell is not
+ * deletion: archived threads are dropped there but keep an editable queue, so
+ * everything else reads the detail's runs, unknown until it loads.
+ */
+export function makeQueuedRunsAtom(input: {
+ readonly threadId: string;
+ readonly snapshot: Atom.Atom<{ readonly threads: ReadonlyArray<ShellThreadPresence> } | null>;
+ readonly detailStatus: Atom.Atom<string>;
+ readonly runs: Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
+}): QueuedRunsAtom {
+ return Atom.make((get) => {
+ const shellThread = get(input.snapshot)?.threads.find(
+ (candidate) => candidate.id === input.threadId,
+ );
+ if (shellThread !== undefined && shellThread.deletedAt !== null) return [];
+ if (get(input.detailStatus) === "deleted") return [];
+ return get(input.runs);
+ });
+}
+
+function runLeftQueue(runs: ReadonlyArray<QueuedRunStatus> | null, runId: RunId): boolean {
+ if (runs === null) return false;
+ return !runs.some((run) => run.id === runId && run.status === "queued");
+}
+
+/**
+ * What happens to an open edit when its run leaves the queue: an unchanged
+ * edit just closes; a changed one moves into the thread's own draft when that
+ * draft is empty, and is dropped otherwise so it never overwrites the user's
+ * other work.
+ */
+export function resolveQueuedEditExit(input: {
+ readonly editChanged: boolean;
+ readonly threadDraftEmpty: boolean;
+}): "kept" | "discarded" | "clean" {
+ if (!input.editChanged) return "clean";
+ return input.threadDraftEmpty ? "kept" : "discarded";
+}
+
+interface ExitWatch<E> {
+ readonly runs: QueuedRunsAtom;
+ readonly runId: RunId;
+ readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
+ cancel: (() => void) | null;
+}
+
+export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(options: {
+ readonly registry: AtomRegistry.AtomRegistry;
+ readonly label: string;
+}) {
+ const { registry } = options;
+ const atom = Atom.make<Readonly<Record<string, E>>>({}).pipe(
+ Atom.keepAlive,
+ Atom.withLabel(options.label),
+ );
+ const watches = new Map<string, ExitWatch<E>>();
+
+ const get = (threadKey: string | null): E | null =>
+ threadKey === null ? null : (registry.get(atom)[threadKey] ?? null);
+
+ const write = (threadKey: string, edit: E | null) => {
+ const current = registry.get(atom);
+ if (edit === null) {
+ if (!(threadKey in current)) return;
+ const next = { ...current };
+ delete next[threadKey];
+ registry.set(atom, next);
+ return;
+ }
+ registry.set(atom, { ...current, [threadKey]: edit });
+ };
+
+ const unsubscribe = (watch: ExitWatch<E>) => {
+ watch.cancel?.();
+ watch.cancel = null;
+ };
+
+ const subscribe = (threadKey: string, watch: ExitWatch<E>) => {
+ const check = (runs: ReadonlyArray<QueuedRunStatus> | null) => {
+ if (watches.get(threadKey) !== watch || watch.cancel === null) return;
+ if (!runLeftQueue(runs, watch.runId)) return;
+ unsubscribe(watch);
+ watches.delete(threadKey);
+ const edit = get(threadKey);
+ if (edit === null || edit.runId !== watch.runId) return;
+ write(threadKey, null);
+ watch.onRunLeftQueue(threadKey, edit);
+ };
+ watch.cancel = registry.subscribe(watch.runs, check);
+ check(registry.get(watch.runs));
+ };
+
+ const stopWatch = (threadKey: string) => {
+ const watch = watches.get(threadKey);
+ if (watch === undefined) return;
+ unsubscribe(watch);
+ watches.delete(threadKey);
+ };
+
+ return {
+ atom,
+ get,
+ /**
+ * Starts an edit, replacing any edit already open on the thread. When the
+ * run leaves the queue the edit is removed and `onRunLeftQueue` receives
+ * it; if the run already left, that happens immediately.
+ */
+ begin(
+ threadKey: string,
+ edit: E,
+ watch: {
+ readonly runs: QueuedRunsAtom;
+ readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
+ },
+ ) {
+ stopWatch(threadKey);
+ write(threadKey, edit);
+ const next: ExitWatch<E> = { ...watch, runId: edit.runId, cancel: null };
+ watches.set(threadKey, next);
+ subscribe(threadKey, next);
+ },
+ update(threadKey: string, f: (edit: E) => E) {
+ const edit = get(threadKey);
+ if (edit !== null) write(threadKey, f(edit));
+ },
+ end(threadKey: string) {
+ stopWatch(threadKey);
+ write(threadKey, null);
+ },
+ /**
+ * Holds the exit transition while a save is in flight; the save's own
+ * result decides the edit's fate.
+ */
+ suspendExitWatch(threadKey: string) {
+ const watch = watches.get(threadKey);
+ if (watch !== undefined) unsubscribe(watch);
+ },
+ /** Resumes after a failed save, handling an exit that happened meanwhile. */
+ resumeExitWatch(threadKey: string) {
+ const watch = watches.get(threadKey);
+ if (watch !== undefined && watch.cancel === null) subscribe(threadKey, watch);
+ },
+ };
+}