From 7212ea3980179850bd967627fe5d905a2f92fe07 Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Tue, 24 Nov 2026 03:27:30 +0000 Subject: [PATCH 1/2] test(web): Chat views list only the queued messages that belong there Failing tests. In Chat mode the main list and each sub-thread list every queued message of the thread: a main-list message shows in every sub-thread, a reply shows in the main list and in other sub-threads, and a reply's run shows in the main list as "Queued message" while its message is still on the way. A queued reply cannot be edited in its reply box, and a reply's queue offers a shortcut that does not run there. Edit hook tests cover one edit per thread owned by the view that lists its run. Fake threads can now carry projection messages. Co-Authored-By: Claude Opus 5.5 --- .../queuedRunEditOwnership.browser.test.tsx | 310 ++++++++++++++++++ .../queuedRunsInChat.browser.test.tsx | 248 ++++++++++++++ .../queuedRunsScope.browser.test.tsx | 297 +++++++++++++++++ apps/web/test/fakeEnvironment.ts | 3 +- 4 files changed, 857 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/fork/subThreads/queuedRunEditOwnership.browser.test.tsx create mode 100644 apps/web/src/fork/subThreads/queuedRunsInChat.browser.test.tsx create mode 100644 apps/web/src/fork/subThreads/queuedRunsScope.browser.test.tsx diff --git a/apps/web/src/fork/subThreads/queuedRunEditOwnership.browser.test.tsx b/apps/web/src/fork/subThreads/queuedRunEditOwnership.browser.test.tsx new file mode 100644 index 0000000000000..144012e449ec2 --- /dev/null +++ b/apps/web/src/fork/subThreads/queuedRunEditOwnership.browser.test.tsx @@ -0,0 +1,310 @@ +import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; +import { + EnvironmentId, + MessageId, + ProviderInstanceId, + 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, useComposerThreadDraft } from "../../composerDraftStore"; +import { deriveComposerSendState } from "../../components/ChatView.logic"; +import { ComposerPrimaryActions } from "../../components/chat/ComposerPrimaryActions"; +import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; +import { useQueuedRunEdit } from "../../components/chat/useQueuedRunEdit"; +import { useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; + +interface RunStatus { + readonly id: RunId; + readonly status: string; + readonly activeAttemptId?: string; +} + +const mocks = await vi.hoisted(async () => { + const { Atom } = await import("effect/reactivity"); + return { + editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(), + promoteQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" }>>(), + promoteCommand: {}, + // The projection's runs per thread, written by each test to stand in for the server. + threadRuns: Atom.family((_key: string) => + Atom.make | null>(null).pipe(Atom.keepAlive), + ), + }; +}); + +vi.mock("../../state/use-atom-command", () => ({ + useAtomCommand: (command: unknown) => + command === mocks.promoteCommand ? mocks.promoteQueuedRun : mocks.editQueuedRun, +})); + +vi.mock("../../hooks/useSettings", () => ({ + useEnvironmentIdentificationMode: () => "none", +})); + +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: {}, + promoteQueuedRun: mocks.promoteCommand, + }, + environmentThreadDetails: { + statusAtom: () => Atom.make("ready"), + quietThreadAtom: (ref: ScopedThreadRef) => + Atom.make((get) => { + const runs = get(mocks.threadRuns(key(ref))); + if (runs === null) return null; + // A Claude-like session whose running turn takes steering. + return { + projection: { + thread: { id: ref.threadId, activeProviderThreadId: null }, + runs, + messages: [], + providerThreads: [], + providerSessions: [ + { + id: "session", + status: "running", + capabilities: { turns: { supportsActiveSteering: true } }, + }, + ], + providerTurns: runs.flatMap((run) => + run.activeAttemptId + ? [{ runAttemptId: run.activeAttemptId, status: "running" }] + : [], + ), + }, + }; + }), + }, + 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; + +function projection(runs: ReadonlyArray, messages: ReadonlyArray) { + 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; + readonly messages: ReadonlyArray; + readonly ownsRun?: boolean; + readonly recoveryTarget?: ScopedThreadRef; +}) { + const result = useQueuedRunEdit({ + environmentId: ENV, + routeThreadRef: props.threadRef, + threadDraftTarget: props.threadRef, + activeThreadId: props.threadRef.threadId, + ...(props.ownsRun === undefined ? {} : { ownsEdit: () => props.ownsRun! }), + ...(props.recoveryTarget === undefined ? {} : { recoveryTarget: () => props.recoveryTarget! }), + serverProjection: projection([{ id: RUN, status: props.runStatus }], props.messages), + promptRef: { current: "" }, + composerRef: { current: null }, + }); + useImperativeHandle(props.hookRef, () => result); + const draft = useComposerThreadDraft(result.draftTarget); + const sendState = deriveComposerSendState({ + prompt: draft.prompt, + imageCount: draft.images.length + draft.files.length, + existingAttachmentCount: result.editingAttachments?.length ?? 0, + terminalContexts: draft.terminalContexts, + }); + return result.isEditing ? ( + void result.saveEdit(savedContent(draft.prompt), () => {})} + onPreviousPendingQuestion={() => {}} + onInterrupt={() => {}} + /> + ) : null; +} + +function view( + threadRef: ScopedThreadRef, + runStatus: string, + hook: { current: HookResult | null }, + messages: ReadonlyArray = [], + ownsRun?: boolean, +) { + return ( + + + + ); +} + +function setup() { + mocks.editQueuedRun.mockReset(); + mocks.promoteQueuedRun.mockReset(); + useAttachmentUploadStore.setState({ uploadsByImageId: {} }); + 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 savedContent = (prompt: string) => ({ + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + prompt, + images: [], + files: [], + terminalContexts: [], + reviewComments: [], + previewAnnotations: [], + threadContexts: [], + environmentContexts: [], +}); + +const promptOf = (ref: ScopedThreadRef) => + useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? ""; + +// One queued-message edit per thread, owned by the chat view that lists its run (Chat mode views). +describe("useQueuedRunEdit across chat views", () => { + it("hands an open edit to the view that lists its run, keeping the unsaved text", async () => { + const { hook } = setup(); + await using screen = await render(view(THREAD_A, "queued", hook, [], true)); + await beginChangedEdit(hook); + + // Another view lists the run now, so this view's composer leaves the edit alone. + await screen.rerender(view(THREAD_A, "queued", hook, [], false)); + expect(requireHook(hook).isEditing).toBe(false); + expect(requireHook(hook).draftTarget).toBe(THREAD_A); + await screen.rerender(view(THREAD_A, "queued", hook, [], true)); + + expect(requireHook(hook).editingRunId).toBe(RUN); + expect( + useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt, + ).toBe("changed"); + }); + + it("leaves another view's composer free while one view owns and saves the edit", async () => { + const { hook } = setup(); + const other = { current: null as HookResult | null }; + let started!: () => void; + const requested = new Promise((resolve) => { + started = resolve; + }); + let finishSave!: (result: { readonly _tag: "Success" }) => void; + mocks.editQueuedRun.mockImplementation(() => { + started(); + return new Promise((resolve) => { + finishSave = resolve; + }); + }); + await using _screen = await render( + + + + , + ); + await beginChangedEdit(hook); + expect(requireHook(other).isEditingElsewhere).toBe(true); + + // The other view cannot start a second edit that would throw this one's text away. + await act(() => + requireHook(other).beginEdit({ + runId: RunId.make("run-2"), + messageId: MessageId.make("message-2"), + text: "another", + attachments: [], + }), + ); + expect(requireHook(hook).editingRunId).toBe(RUN); + expect( + useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt, + ).toBe("changed"); + + const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {}); + await act(() => requested); + expect(requireHook(hook).isSaving).toBe(true); + expect(requireHook(other).isSaving).toBe(false); + finishSave({ _tag: "Success" }); + await act(() => saved); + }); + + it("recovers a changed edit into the message box that shows it when its run starts", async () => { + const { hook } = setup(); + await using _screen = await render( + + + , + ); + await beginChangedEdit(hook); + await act(() => setRuns(THREAD_A, "running")); + + expect(promptOf(THREAD_B)).toBe("changed"); + expect(promptOf(THREAD_A)).toBe(""); + }); +}); diff --git a/apps/web/src/fork/subThreads/queuedRunsInChat.browser.test.tsx b/apps/web/src/fork/subThreads/queuedRunsInChat.browser.test.tsx new file mode 100644 index 0000000000000..a29382a56a60f --- /dev/null +++ b/apps/web/src/fork/subThreads/queuedRunsInChat.browser.test.tsx @@ -0,0 +1,248 @@ +import { createMemoryHistory } from "@tanstack/react-router"; +import { MessageId, RunId, ThreadId } from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import { CHAT_REPLIES_DISPLAY_MODE } from "@t3tools/shared/displayModes"; +import type * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { AppRoot } from "~/AppRoot"; +import "~/index.css"; +// The route loads ChatView lazily, and its first transform takes seconds; see ChatView.browser.test.tsx. +import "~/components/ChatView"; +import { __setClientSettingsForTests } from "~/hooks/useSettings"; +import { getRouter } from "~/router"; +import { + assistantItem, + emitThreadEvent, + ENVIRONMENT_ID, + installFakeEnvironment, + threadWithHistory, + type FakeDriver, + type FakeThread, +} from "../../../test/fakeEnvironment"; +import { render } from "../../../test/render"; +import { replyContextField } from "./subThreadReply"; + +vi.mock( + "../../../../../packages/client-runtime/src/connection/driver.ts", + async (importOriginal) => { + const [actual, { fakeDriver }, Layer] = await Promise.all([ + importOriginal<{ readonly ConnectionDriver: Context.Key }>(), + import("../../../test/fakeEnvironment"), + import("effect/Layer"), + ]); + return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; + }, +); + +vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ + ...(await original()), + trackRpcRequestSent: () => {}, +})); + +const QUEUED_MAIN = "Queued in the main list"; +const QUEUED_AGENT = "Queued by another agent"; +const QUEUED_REPLY = "Queued in the deploy's replies"; +const AT = DateTime.makeUnsafe("2026-11-23T00:00:00.000Z"); + +/** + * A one-turn thread whose agent sent "The deploy is done.", with three queued messages: one typed in + * the main list, one from another agent, and one typed in the deploy message's replies. + */ +function threadWithQueue(): FakeThread { + const history = threadWithHistory("queued-scope", 1); + const { + messageId: _id, + text: _text, + streaming: _streaming, + ...item + } = assistantItem(history.id, history.runs[0]!.id, "queued-scope-news", 2, ""); + const news = { + ...item, + type: "dynamic_tool" as const, + toolName: "mcp__t3-code__send_to_user", + input: { text: "The deploy is done.", new_sub_thread: true }, + output: { ok: true }, + }; + const queued = [ + { id: "main", text: QUEUED_MAIN, fields: { createdBy: "user", creationSource: "web" } }, + { + id: "agent", + text: QUEUED_AGENT, + fields: { + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("lead"), + }, + }, + { + id: "reply", + text: QUEUED_REPLY, + fields: { createdBy: "user", creationSource: "web", ...replyContextField(news.id) }, + }, + ] as const; + return { + ...history, + items: [...history.items, news], + runs: [ + ...history.runs, + ...queued.map(({ id }, index) => ({ + ...history.runs[0]!, + id: RunId.make(`queued-${id}`), + ordinal: index + 2, + userMessageId: MessageId.make(`queued-${id}-message`), + status: "queued" as const, + startedAt: null, + completedAt: null, + })), + ], + messages: queued.map(({ id, text, fields }) => ({ + id: MessageId.make(`queued-${id}-message`), + threadId: history.id, + runId: RunId.make(`queued-${id}`), + nodeId: null, + role: "user" as const, + text, + attachments: [], + streaming: false, + createdAt: AT, + updatedAt: AT, + ...fields, + })) as never, + }; +} + +async function openChatThread(thread: FakeThread) { + const environment = installFakeEnvironment([thread], { + settings: { threadDisplayModes: { [thread.id]: CHAT_REPLIES_DISPLAY_MODE.id } }, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + await page.viewport(1194, 834); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + try { + await router.load(); + const app = await render(, { router: false }); + return { + [Symbol.asyncDispose]: async () => { + await app[Symbol.asyncDispose](); + environment[Symbol.dispose](); + }, + }; + } catch (error) { + environment[Symbol.dispose](); + throw error; + } +} + +/** The queued texts that the queue of the view `root` lists. */ +const queuedIn = (root: Element) => + [QUEUED_MAIN, QUEUED_AGENT, QUEUED_REPLY].filter((text) => + root.querySelector("[data-thread-queue]")?.textContent?.includes(text), + ); + +it("in Chat mode, each view lists only its own queued messages", async () => { + const thread = threadWithQueue(); + await using _app = await openChatThread(thread); + await expect.element(page.getByText(QUEUED_MAIN, { exact: true })).toBeVisible(); + // Only the main list is open, so the page holds one queue. + expect(queuedIn(document.body)).toEqual([QUEUED_MAIN, QUEUED_AGENT]); + + await page.getByRole("button", { name: "Reply", exact: true }).click(); + const news = thread.items.at(-1)!.id; + await expect + .poll(() => document.querySelector(`[data-sub-thread-view="${news}"]`)) + .not.toBeNull(); + const replies = document.querySelector(`[data-sub-thread-view="${news}"]`)!; + await expect.poll(() => queuedIn(replies)).toEqual([QUEUED_REPLY]); + // The main list still lists its own two, and not the reply. + const mainQueue = [...document.querySelectorAll("[data-thread-queue]")].find( + (queue) => !replies.contains(queue), + )!; + expect(queuedIn(mainQueue.parentElement!)).toEqual([QUEUED_MAIN, QUEUED_AGENT]); +}); + +it("in Chat mode, a queued reply never shows in the main list while its message is on the way", async () => { + const full = threadWithQueue(); + const runOf = (id: string) => full.runs.find((candidate) => candidate.id === id)!; + const messageOf = (id: string) => + full.messages!.find((candidate) => candidate.id === runOf(id).userMessageId)!; + const thread = { ...full, runs: full.runs.slice(0, 1), messages: [] }; + await using _app = await openChatThread(thread); + await page.getByRole("button", { name: "Reply", exact: true }).click(); + const news = thread.items.at(-1)!.id; + await expect + .poll(() => document.querySelector(`[data-sub-thread-view="${news}"]`)) + .not.toBeNull(); + const replies = document.querySelector(`[data-sub-thread-view="${news}"]`)!; + const mainQueueText = () => + [...document.querySelectorAll("[data-thread-queue]")] + .filter((queue) => !replies.contains(queue)) + .map((queue) => queue.textContent ?? "") + .join(""); + + // The server announces the reply's run before its message. A main-list message, queued after it + // with its message, marks the moment the main list has seen the reply's run. + await emitThreadEvent(thread.id, { type: "run.created", payload: runOf("queued-reply") }); + await emitThreadEvent(thread.id, { type: "message.updated", payload: messageOf("queued-main") }); + await emitThreadEvent(thread.id, { type: "run.created", payload: runOf("queued-main") }); + await expect.poll(mainQueueText).toContain(QUEUED_MAIN); + expect(mainQueueText()).not.toContain("Queued message"); + expect(queuedIn(replies)).toEqual([]); + + await emitThreadEvent(thread.id, { type: "message.updated", payload: messageOf("queued-reply") }); + await expect.poll(() => queuedIn(replies)).toEqual([QUEUED_REPLY]); + expect(mainQueueText()).not.toContain(QUEUED_REPLY); +}); + +it("in Chat mode, a reply's queue offers no keyboard shortcut, since its keys do not run there", async () => { + const thread = threadWithQueue(); + await using _app = await openChatThread(thread); + await page.getByRole("button", { name: "Reply", exact: true }).click(); + const news = thread.items.at(-1)!.id; + await expect + .poll(() => document.querySelector(`[data-sub-thread-view="${news}"] [data-thread-queue]`)) + .not.toBeNull(); + const replyQueue = document.querySelector( + `[data-sub-thread-view="${news}"] [data-thread-queue]`, + )!; + await page.elementLocator(replyQueue).getByRole("button", { name: "Send now" }).hover(); + await expect.element(page.getByText(/^Start a turn with this message/)).toBeVisible(); + expect(page.getByText(/^Start a turn with this message/).element().textContent).toBe( + "Start a turn with this message", + ); +}); + +it("in Chat mode, a queued reply is edited in its own reply box", async () => { + const thread = threadWithQueue(); + await using _app = await openChatThread(thread); + await page.getByRole("button", { name: "Reply", exact: true }).click(); + const news = thread.items.at(-1)!.id; + await expect + .poll(() => document.querySelector(`[data-sub-thread-view="${news}"] [data-thread-queue]`)) + .not.toBeNull(); + const replies = document.querySelector(`[data-sub-thread-view="${news}"]`)!; + await page + .elementLocator(replies.querySelector("[data-thread-queue]")!) + .getByRole("button", { name: "Edit queued message" }) + .click(); + + await expect + .poll(() => replies.querySelector("[data-thread-queue]")?.textContent) + .toContain("Editing in the composer"); + const editors = [...document.querySelectorAll('[data-testid="composer-editor"]')]; + const replyEditor = editors.find((editor) => replies.contains(editor))!; + const mainEditor = editors.find((editor) => !replies.contains(editor))!; + await expect.poll(() => replyEditor.textContent).toContain(QUEUED_REPLY); + expect(mainEditor.textContent).not.toContain(QUEUED_REPLY); + const mainQueue = [...document.querySelectorAll("[data-thread-queue]")].find( + (queue) => !replies.contains(queue), + )!; + expect(mainQueue.textContent).not.toContain("Editing in the composer"); +}); diff --git a/apps/web/src/fork/subThreads/queuedRunsScope.browser.test.tsx b/apps/web/src/fork/subThreads/queuedRunsScope.browser.test.tsx new file mode 100644 index 0000000000000..6660cebe55750 --- /dev/null +++ b/apps/web/src/fork/subThreads/queuedRunsScope.browser.test.tsx @@ -0,0 +1,297 @@ +import { CHAT_REPLIES_DISPLAY_MODE, NORMAL_DISPLAY_MODE } from "@t3tools/shared/displayModes"; +import * as DateTime from "effect/DateTime"; +import { createRef, type ComponentProps } from "react"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +const state = vi.hoisted(() => ({ + workflow: null as unknown, + chat: true, + commands: [] as unknown[], +})); + +vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({ + ...(await importOriginal()), + deriveThreadQueueWorkflowState: (() => state.workflow) as never, +})); + +vi.mock(import("../displayMode/useThreadDisplayMode"), async (importOriginal) => ({ + ...(await importOriginal()), + useThreadDisplayMode: (() => + state.chat ? CHAT_REPLIES_DISPLAY_MODE : NORMAL_DISPLAY_MODE) as never, + readThreadDisplay: (() => ({ + mode: state.chat ? CHAT_REPLIES_DISPLAY_MODE : NORMAL_DISPLAY_MODE, + dashboard: false, + })) as never, +})); + +// The main list has loaded the first messages of sub-threads A and B, not of C. +const LOADED_SUB_THREADS = vi.hoisted( + () => + new Map([ + ["message:first-a", {}], + ["message:first-b", {}], + ]), +); +vi.mock(import("./subThreadsState"), async (importOriginal) => ({ + ...(await importOriginal()), + useSubThreadSummaries: (() => LOADED_SUB_THREADS) as never, + readSubThreadSummaries: (() => LOADED_SUB_THREADS) as never, +})); + +vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({ + ...(await importOriginal()), + useAtomCommand: (() => async (input: unknown) => { + state.commands.push(input); + return undefined; + }) as never, +})); + +vi.mock(import("../../state/entities"), async (importOriginal) => ({ + ...(await importOriginal()), + useQuietThreadShell: (() => ({ title: "Release lead" })) as never, +})); + +// The queue reads the thread's projection; any loaded one will do, since the workflow is mocked. +vi.mock(import("../../state/threads"), async (importOriginal) => { + const { createEnvironmentThreadDetailAtoms, EMPTY_ENVIRONMENT_THREAD_STATE } = + await import("@t3tools/client-runtime/state/threads"); + const { AsyncResult, Atom } = await import("effect/reactivity"); + const Option = await import("effect/Option"); + const { makeThreadProjectionFixture } = await import("../../test-fixtures"); + const threadState = Atom.make( + AsyncResult.success({ + ...EMPTY_ENVIRONMENT_THREAD_STATE, + data: Option.some(makeThreadProjectionFixture()), + }), + ).pipe(Atom.keepAlive); + return { + ...(await importOriginal()), + environmentThreadDetails: createEnvironmentThreadDetailAtoms(() => threadState), + }; +}); + +import "~/index.css"; + +import { render } from "../../../test/render"; +import { useQueuedRunsInView } from "./queuedRunsScope"; +import { + QueuedRunsControl, + type QueuedRunsControlHandle, +} from "../../components/chat/QueuedRunsControl"; +import { SubThreadViewContext } from "./subThreadsState"; + +const baseProps = { + environmentId: "environment:test" as never, + optimisticMessages: [], + threadId: "thread:test" as never, + editingRunId: null, + editBlockedReason: null, + onEditQueuedRun: () => undefined, + onCancelEdit: () => undefined, + timestampFormat: "locale", + onOpenThread: () => undefined, + onImageExpand: () => undefined, +} satisfies ComponentProps; + +const replyRecord = (first: string) => ({ + version: 1, + records: [ + { version: 1, contextId: "fork-reply", kind: "fork-reply", label: "Reply", payload: { first } }, + ], +}); + +const queued = (id: string, text: string, fields: Record) => ({ + run: { id: `run:${id}`, userMessageId: `message:${id}` }, + text, + attachments: [], + ...(fields.context ? { context: fields.context } : {}), + message: { + id: `message:${id}`, + role: "user", + text, + createdAt: DateTime.makeUnsafe("2026-11-22T12:00:00.000Z"), + ...fields, + }, +}); + +const TEXTS = { + replyA: "Typed in sub-thread A", + main: "Typed in the main list", + agent: "Sent by another agent", + task: "Sent by a scheduled task", + replyC: "Typed in sub-thread C, whose first message is not loaded", + replyB: "Typed in sub-thread B", +} as const; + +const typed = { createdBy: "user", creationSource: "web" }; + +function setQueue() { + state.workflow = { + activeRun: { id: "run:active" }, + canPromoteToSteer: true, + // In queue order; each view's first and last rows differ from the thread's. + queuedRuns: [ + queued("reply-a", TEXTS.replyA, { ...typed, context: replyRecord("message:first-a") }), + queued("main", TEXTS.main, typed), + queued("agent", TEXTS.agent, { + createdBy: "agent", + creationSource: "mcp", + senderThreadId: "thread:lead", + }), + queued("task", TEXTS.task, { createdBy: "agent", scheduledTaskId: "task:nightly" }), + queued("reply-c", TEXTS.replyC, { ...typed, context: replyRecord("message:first-c") }), + queued("reply-b", TEXTS.replyB, { ...typed, context: replyRecord("message:first-b") }), + ], + }; +} + +async function shownTexts( + view: string | null, + props: Partial> = {}, +): Promise> { + await using screen = await render( + + + , + ); + const items = screen.container.querySelectorAll("li"); + // The queue collapses past three rows; open it so every row it holds is on screen. + const showAll = [...screen.container.querySelectorAll("button")].find((button) => + /^Show all/.test(button.textContent ?? ""), + ); + if (showAll) { + showAll.click(); + await expect + .poll(() => screen.container.querySelectorAll("li").length) + .toBeGreaterThan(items.length); + } + const text = screen.container.textContent ?? ""; + return Object.values(TEXTS).filter((candidate) => text.includes(candidate)); +} + +it.each([ + ["the main list", null, [TEXTS.main, TEXTS.agent, TEXTS.task, TEXTS.replyC]], + ["sub-thread A", "message:first-a", [TEXTS.replyA]], + ["sub-thread B", "message:first-b", [TEXTS.replyB]], +])("in Chat mode, %s shows only the queued messages that belong there", async (_, view, want) => { + state.chat = true; + setQueue(); + await page.viewport(1280, 800); + expect(await shownTexts(view)).toEqual(want); +}); + +it("in Normal mode, the one list shows every queued message", async () => { + state.chat = false; + setQueue(); + expect(await shownTexts(null)).toEqual(Object.values(TEXTS)); +}); + +it("in Chat mode, the main list's keys send and edit the main list's own queued messages", async () => { + state.chat = true; + state.commands = []; + setQueue(); + const ref = createRef(); + const onEditQueuedRun = vi.fn(); + await using _screen = await render( + + + , + ); + await expect.element(page.getByText(TEXTS.main, { exact: true })).toBeVisible(); + expect(ref.current?.steerNext(false)).toBe(true); + await expect + .poll(() => state.commands) + .toEqual([ + expect.objectContaining({ input: expect.objectContaining({ queuedRunId: "run:main" }) }), + ]); + expect(ref.current?.editLatest(false)).toBe(true); + expect(onEditQueuedRun).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ runId: "run:reply-c", text: TEXTS.replyC }), + ); +}); + +it("in Chat mode, a queued run whose message has not arrived shows in no view", async () => { + state.chat = true; + state.workflow = { + activeRun: { id: "run:active" }, + canPromoteToSteer: true, + queuedRuns: [ + { + run: { id: "run:early", userMessageId: "message:early" }, + text: "Queued message", + attachments: [], + }, + ], + }; + for (const view of [null, "message:first-a"]) { + await using screen = await render( + + + , + ); + expect(screen.container.querySelector("[data-thread-queue]")).toBeNull(); + } +}); + +it("keeps the queued message being edited on screen in a collapsed queue", async () => { + state.chat = false; + setQueue(); + await using screen = await render( + + + , + ); + await expect.element(page.getByText(TEXTS.replyB, { exact: true })).toBeVisible(); + await expect + .element(page.getByRole("button", { name: "Cancel editing queued message" })) + .toBeVisible(); + // The queue stays collapsed: its first rows, the edited row, and a truthful Show all. + const rows = screen.container.querySelectorAll("li"); + expect(rows).toHaveLength(3); + // The edited row keeps its place in the whole queue. + expect(rows[2]!.getAttribute("aria-posinset")).toBe(String(Object.keys(TEXTS).length)); + const toggle = page.getByRole("button", { name: /^Show all \d+ queued$/ }); + await expect.element(toggle).toHaveAttribute("aria-expanded", "false"); + await toggle.click(); + expect(screen.container.querySelectorAll("li")).toHaveLength(Object.keys(TEXTS).length); +}); + +it.each([ + ["a reply in a loaded sub-thread goes to its reply box", true, "message:first-a", "sub-thread"], + ["a reply under an unloaded first message goes to the main box", true, "message:first-c", "main"], + ["a reply in Normal mode goes to the main box", false, "message:first-a", "main"], +])("recovered edit text: %s", async (_, chat, first, want) => { + state.chat = chat; + const threadRef = { environmentId: "environment:test", threadId: "thread:test" } as never; + function Probe() { + const target = useQueuedRunsInView(threadRef, null).recoveryTarget(replyRecord(first) as never); + return {target === threadRef ? "main" : typeof target}; + } + await using screen = await render(); + expect(screen.container.textContent).toBe(want === "main" ? "main" : "string"); +}); + +it.each([ + ["sub-thread A owns the edit of its reply", "message:first-a", "message:first-a", true], + ["the main list does not own the edit of a reply in A", null, "message:first-a", false], + [ + "the main list owns the edit of a reply under an unloaded first message", + null, + "message:first-c", + true, + ], +])("in Chat mode, %s, queued or not", async (_, view, first, want) => { + state.chat = true; + const threadRef = { environmentId: "environment:test", threadId: "thread:test" } as never; + function Probe() { + const owns = useQueuedRunsInView(threadRef, null).ownsEdit(replyRecord(first) as never); + return {String(owns)}; + } + await using screen = await render( + + + , + ); + expect(screen.container.textContent).toBe(String(want)); +}); diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 8c00d13a4e4f2..628fd18495d52 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -245,6 +245,7 @@ export interface FakeThread { readonly providerThreads?: ReadonlyArray; readonly issues?: OrchestrationV2ThreadShell["issues"]; readonly runs: ReadonlyArray; + readonly messages?: OrchestrationV2ThreadProjection["messages"]; readonly items: ReadonlyArray; readonly runtimeRequests?: OrchestrationV2ThreadProjection["runtimeRequests"]; } @@ -406,7 +407,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { providerThreads: [...(thread.providerThreads ?? [])], providerTurns: [], runtimeRequests: [...(thread.runtimeRequests ?? [])], - messages: [], + messages: [...(thread.messages ?? [])], plans: [], turnItems: [...thread.items], checkpointScopes: [], From 0a962602b4032c19992f9fde7b36349543c219ca Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Tue, 24 Nov 2026 03:38:00 +0000 Subject: [PATCH 2/2] fix(fork): Chat views list only the queued messages that belong there Each Chat view (the main list, or one sub-thread) listed every queued message of the thread. A queued message now shows only in the view where it belongs: a typed reply in its sub-thread when the loaded history shows that sub-thread, anything else (main-list typing, agents, tasks, wakes, slash commands) in the main list. A run whose message has not arrived yet shows in no view; the sending view keeps its own Saving row. The count, footer and queue keys follow the same rows. Pending guest messages show in the main list only, and a reply view offers no queue shortcuts. Normal mode still lists every queued message. The thread keeps one queued-message edit, owned by the view that lists the message, judged from its reply record: a queued reply is edited in its reply box in Chat mode and in the main box in Normal mode, and an open edit moves with it across a mode switch. Another view cannot start a second edit meanwhile, only the owning composer shows the save in flight, the message's current box gets unsaved text back when its run leaves the queue, and a collapsed queue keeps the edited row on screen at its queue position. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 34 ++-- .../src/components/chat/QueuedRunsControl.tsx | 16 +- .../src/components/chat/useQueuedRunEdit.ts | 30 +++- .../fork/subThreads/queuedRunsScope.test.ts | 147 +++++++++++++++++ .../src/fork/subThreads/queuedRunsScope.ts | 155 ++++++++++++++++++ .../web/src/fork/subThreads/subThreadReply.ts | 3 - .../src/fork/subThreads/subThreadsState.ts | 13 ++ 7 files changed, 369 insertions(+), 29 deletions(-) create mode 100644 apps/web/src/fork/subThreads/queuedRunsScope.test.ts create mode 100644 apps/web/src/fork/subThreads/queuedRunsScope.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index dba15931c869c..8cdfaa2700e31 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -106,7 +106,6 @@ import { workflowOpeningParentThreadId, } from "@t3tools/client-runtime/state/subagentRuntime"; import { - getUserQueuedThreadRuns, threadCanSteer, threadSupportsProviderHandoff, } from "@t3tools/client-runtime/state/thread-workflows"; @@ -400,9 +399,15 @@ import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useSplitRendered } from "../fork/rightPanelSplit/renderedSplit"; import { unfocusedPaneSurface } from "../fork/rightPanelSplit/splitLayout.logic"; import { useModeSurfaceActions } from "../fork/dashboard/dashboardSurface"; -import { REPLY_BOX_QUEUE_EDIT_BLOCKED, subThreadDraftId } from "../fork/subThreads/subThreadReply"; +import { subThreadDraftId } from "../fork/subThreads/subThreadReply"; import { useSubThreadCite } from "../fork/subThreads/subThreadCite"; import { SubThreadViewContext } from "../fork/subThreads/subThreadsState"; +import { + QUEUE_EDIT_OPEN_ELSEWHERE, + useGuestMessagesInView, + useQueuedRunsInView, + useQueueShortcutLabels, +} from "../fork/subThreads/queuedRunsScope"; import { useThreadShownView } from "../fork/displayMode/threadView"; import { ChatWorkingIndicator } from "../fork/displayMode/ChatWorkingIndicator"; import { @@ -559,12 +564,14 @@ export default function ChatView(props: ChatViewProps) { const promptRef = useRef(""); const localComposerRef = useRef(null); const composerRef = useComposerHandleContext() ?? localComposerRef; + const queuedRunsInView = useQueuedRunsInView(routeThreadDetailRef, serverProjection); const queuedRunEdit = useQueuedRunEdit({ environmentId, routeThreadRef, threadDraftTarget: baseComposerDraftTarget, - activeThreadId: - (serverThread !== null || draftThread !== null) && subThreadDraft === null ? threadId : null, + activeThreadId: serverThread !== null || draftThread !== null ? threadId : null, + ownsEdit: queuedRunsInView.ownsEdit, + recoveryTarget: queuedRunsInView.recoveryTarget, serverProjection, promptRef, composerRef, @@ -3215,7 +3222,7 @@ export default function ChatView(props: ChatViewProps) { const onComposerCompactContextStable = useStableCallback(onCompactContext); // Read from the projection the footer renders, so the scroll below sees the new message. const pendingGuestMessageIds = - serverProjection?.thread.guestShare?.messages.flatMap((message) => + useGuestMessagesInView(serverProjection?.thread.guestShare?.messages)?.flatMap((message) => message.status === "pending" ? [message.id] : [], ) ?? []; const pendingGuestMessageCount = pendingGuestMessageIds.length; @@ -3246,28 +3253,25 @@ export default function ChatView(props: ChatViewProps) { openExpandedImagePreview(routeThreadKey, preview); }; const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage); + const queueShortcutLabels = useQueueShortcutLabels(keybindings); const queuedRunsControl = isServerThread && activeThread ? ( <> showsQueuedRun(message)); const activeRun = workflow?.activeRun ?? null; // A fresh message starts its own turn: it may skip compaction, but not steer into a turn. const canSendRun = (freshContext: boolean) => @@ -251,7 +253,14 @@ export function QueuedRunsControl({ }; const collapsible = items.length > QUEUE_VISIBLE_ROWS; - const visibleItems = collapsible && !showAll ? items.slice(0, QUEUE_VISIBLE_ROWS - 1) : items; + const visibleItems = + collapsible && !showAll + ? items.filter( + (item, index) => + index < QUEUE_VISIBLE_ROWS - 1 || + (item.runId !== null && item.runId === props.editingRunId), + ) + : items; return (
    - {visibleItems.map((item, position) => { + {visibleItems.map((item) => { + const position = items.indexOf(item); const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index c8e5038e06dbb..51ad2bbe3206b 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -215,6 +215,10 @@ export function useQueuedRunEdit(input: { readonly routeThreadRef: ScopedThreadRef; readonly threadDraftTarget: ComposerThreadTarget; readonly activeThreadId: ThreadId | null; + readonly ownsEdit?: (context: OrchestrationMessageContext | undefined) => boolean; + readonly recoveryTarget?: ( + context: OrchestrationMessageContext | undefined, + ) => ComposerThreadTarget | undefined; readonly serverProjection: ThreadStructure | null; readonly promptRef: { current: string }; readonly composerRef: RefObject; @@ -224,6 +228,8 @@ export function useQueuedRunEdit(input: { routeThreadRef, threadDraftTarget, activeThreadId, + ownsEdit, + recoveryTarget, serverProjection, promptRef, composerRef, @@ -232,8 +238,12 @@ export function useQueuedRunEdit(input: { const promoteQueuedRun = useAtomCommand(threadEnvironment.promoteQueuedRun); const editKey = scopedThreadKey(routeThreadRef); const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null; - const editing = activeThreadId === null ? null : storedEdit; - const isSaving = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true; + const editing = + activeThreadId === null || (storedEdit !== null && ownsEdit?.(storedEdit.context) === false) + ? null + : storedEdit; + const saveInFlight = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true; + const isSaving = editing !== null && saveInFlight; const draftTarget = editing === null ? threadDraftTarget : queuedRunEditDraftId(routeThreadRef, editing.runId); @@ -279,7 +289,7 @@ export function useQueuedRunEdit(input: { const clearEditDraft = (runId: RunId) => { const target = queuedRunEditDraftId(routeThreadRef, runId); // A save in flight still sends these uploads. - if (isSaving) { + if (saveInFlight) { const store = useComposerDraftStore.getState(); store.clearComposerContent(target); store.clearDraftThread(target); @@ -287,7 +297,7 @@ export function useQueuedRunEdit(input: { }; const beginEdit = useStableCallback((request: EditQueuedRunRequest) => { - if (activeThreadId === null) return; + if (activeThreadId === null || (storedEdit !== null && editing === null)) return; if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId); const target = queuedRunEditDraftId(routeThreadRef, request.runId); const sentText = stripAttachmentOnlyBootstrapPrompt(request.text); @@ -350,7 +360,7 @@ export function useQueuedRunEdit(input: { onRunLeftQueue: (_, edit) => { const recovery = recoverQueuedMessageEdit({ editTarget: queuedRunEditDraftId(routeThreadRef, edit.runId), - threadTarget: threadDraftTarget, + threadTarget: recoveryTarget?.(edit.context) ?? threadDraftTarget, originalText: edit.originalText, ...(edit.originalModelSelection ? { originalModelSelection: edit.originalModelSelection } @@ -387,6 +397,7 @@ export function useQueuedRunEdit(input: { ); focusComposerSoon(); }); + const ownsEditNow = useStableCallback(() => editing !== null); const cancelEdit = useStableCallback(() => { if (editing === null) return; clearEditDraft(editing.runId); @@ -541,10 +552,12 @@ export function useQueuedRunEdit(input: { if (error !== null) return; if (changedAfterSave) return; releaseDraftAttachments(newAttachments); - promptRef.current = ""; clearEditDraft(editing.runId); - composerRef.current?.resetCursorState(); - focusComposerSoon(); + if (ownsEditNow()) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + focusComposerSoon(); + } // A plain submit means "Update queued message"; only the opposite-action shortcut or // modifier-click asks to steer, as it does for a new follow-up. if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") { @@ -555,6 +568,7 @@ export function useQueuedRunEdit(input: { return { editingRunId: editing?.runId ?? null, isEditing: editing !== null, + isEditingElsewhere: storedEdit !== null && editing === null, isSaving, draftTarget, editingAttachments, diff --git a/apps/web/src/fork/subThreads/queuedRunsScope.test.ts b/apps/web/src/fork/subThreads/queuedRunsScope.test.ts new file mode 100644 index 0000000000000..9fd22211916a8 --- /dev/null +++ b/apps/web/src/fork/subThreads/queuedRunsScope.test.ts @@ -0,0 +1,147 @@ +import { + MessageId, + type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2TurnItem, + RunId, + ScheduledTaskId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import { shortId } from "@t3tools/shared/displayModes"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic"; +import { runPlaces, timelineSubThreads } from "../displayMode/displayModeTimeline"; +import { queuedRunPlace } from "./queuedRunsScope"; +import { withSubThreadRecord } from "./subThreadReply"; + +const threadId = ThreadId.make("queued-scope-thread"); +const at = DateTime.makeUnsafe("2026-11-23T00:00:00.000Z"); +const userMessage = (id: string, ordinal: number, text: string, extra: object = {}) => + ({ + id: TurnItemId.make(id), + threadId, + runId: RunId.make(`${id}-run`), + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: at, + completedAt: at, + updatedAt: at, + type: "user_message", + messageId: MessageId.make(id), + text, + attachments: [], + inputIntent: "turn_start", + createdBy: "user", + creationSource: "web", + ...extra, + }) as OrchestrationV2TurnItem; +const inReplyBox = (first: string, text: string) => ({ + context: withSubThreadRecord(first, text, undefined), +}); + +// Each case is a message as its queued run holds it; it then starts as the run's only message. +const cases: ReadonlyArray = [ + ["typed in the main list", "Run the tests", {}], + ["typed in a loaded sub-thread", "And the lint job?", inReplyBox("first", "And the lint job?")], + ["typed under an unloaded first", "Still there?", inReplyBox("not-loaded", "Still there?")], + ["a slash command from a reply box", "/compact", inReplyBox("first", "/compact")], + [ + "sent by another agent", + "Review finished.", + { createdBy: "agent", creationSource: "mcp", senderThreadId: ThreadId.make("lead") }, + ], + [ + "sent by a scheduled task", + "Nightly check.", + { createdBy: "agent", scheduledTaskId: ScheduledTaskId.make("nightly") }, + ], + ["a wake", "/compact", { idleCompaction: true }], +]; + +function timeline(extra: OrchestrationV2TurnItem, base = [userMessage("first", 0, "Ship it")]) { + const items = [...base, extra]; + return deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.map((item, position): OrchestrationV2ProjectedTurnItem => ({ + position, + visibility: "local", + sourceThreadId: threadId, + sourceItemId: item.id, + item, + })), + optimisticMessages: [], + }); +} + +describe("queuedRunPlace", () => { + it.each(cases)("puts a queued message %s where its started run answers", (_, text, extra) => { + const entries = timeline(userMessage("queued", 1, text, extra)); + const started = entries.find( + (entry) => entry.kind === "message" && entry.message.id === "queued", + ); + if (started?.kind !== "message") throw new Error("the queued message has no row"); + const loaded = timelineSubThreads(entries, null); + expect(queuedRunPlace(started.message as never, (first) => loaded.has(first))).toBe( + runPlaces(entries).get(RunId.make("queued-run")) ?? null, + ); + }); + + it("puts a reply in its sub-thread and everything else in the main list", () => { + const places = cases.map(([name, text, extra]) => { + const entries = timeline(userMessage("queued", 1, text, extra)); + const started = entries.find( + (entry) => entry.kind === "message" && entry.message.id === "queued", + ); + const loaded = timelineSubThreads(entries, null); + const message = started?.kind === "message" ? started.message : undefined; + return [name, queuedRunPlace(message as never, (first) => loaded.has(first))] as const; + }); + expect(Object.fromEntries(places)).toEqual({ + "typed in the main list": null, + "typed in a loaded sub-thread": "first", + "typed under an unloaded first": null, + "a slash command from a reply box": null, + "sent by another agent": null, + "sent by a scheduled task": null, + "a wake": null, + }); + }); + + it("puts a run with no loaded message in the main list", () => { + expect(queuedRunPlace(undefined, () => true)).toBeNull(); + }); + + it("keeps a queued reply in the main list while its sub-thread has no row to open", () => { + // The answer replies to a question outside the loaded history; a reply under it places it. + const answer = { + ...userMessage("answer", 0, ""), + type: "dynamic_tool", + toolName: "mcp__t3-code__send_to_user", + input: { text: "Done.", reply_to: shortId("not-loaded"), user_message: "x" }, + output: { ok: true }, + } as unknown as OrchestrationV2TurnItem; + const entries = timeline( + userMessage("queued", 1, "Which one?", inReplyBox("answer", "Which one?")), + [answer], + ); + const started = entries.find( + (entry) => entry.kind === "message" && entry.message.id === "queued", + ); + if (started?.kind !== "message") throw new Error("the queued message has no row"); + const loaded = timelineSubThreads(entries, null); + // Without the reply in the history, the answer has no row, so no reply box can show the reply. + const history = timeline(userMessage("other", 1, "Unrelated"), [answer]); + const reachable = timelineSubThreads(history, null); + expect(queuedRunPlace(started.message as never, (first) => reachable.has(first))).toBeNull(); + // Once the reply runs, its row places the answer, and the run answers in that sub-thread. + expect(loaded.has("answer")).toBe(true); + expect(runPlaces(entries).get(RunId.make("queued-run"))).toBe("answer"); + }); +}); diff --git a/apps/web/src/fork/subThreads/queuedRunsScope.ts b/apps/web/src/fork/subThreads/queuedRunsScope.ts new file mode 100644 index 0000000000000..b599ebad2518b --- /dev/null +++ b/apps/web/src/fork/subThreads/queuedRunsScope.ts @@ -0,0 +1,155 @@ +import type { QueuedThreadRun } from "@t3tools/client-runtime/state/thread-workflows"; +import { getUserQueuedThreadRuns } from "@t3tools/client-runtime/state/thread-workflows"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import type { + OrchestrationMessageContext, + ResolvedKeybindingsConfig, + ScopedThreadRef, +} from "@t3tools/contracts"; +import { displayEventFromMessage, subThreadOfRecords } from "@t3tools/shared/displayModes"; +import { use } from "react"; + +import { shortcutLabelForCommand } from "../../keybindings"; +import type { DraftId } from "../../composerDraftStore"; +import { readThreadDisplay, useThreadDisplayMode } from "../displayMode/useThreadDisplayMode"; +import { subThreadDraftId } from "./subThreadReply"; +import { + readSubThreadSummaries, + SubThreadViewContext, + useSubThreadSummaries, +} from "./subThreadsState"; + +type QueuedMessage = QueuedThreadRun["message"]; +type QueueProjection = Parameters[0]; + +/** + * Returns the view where the queued run for `message` will answer, matching `runPlaces`. + * Returns the sub-thread first message id for a reply the user typed if `loaded` is true for it. + * Returns `null` for the main list on missing, slash, agent, task, wake, guest, and other messages. + */ +export function queuedRunPlace( + message: QueuedMessage, + loaded: (first: string) => boolean, +): string | null { + const event = message === undefined ? null : displayEventFromMessage(message); + return event?.type === "user" && event.under !== undefined && loaded(event.under) + ? event.under + : null; +} + +/** + * Returns a predicate for whether the current `SubThreadViewContext` view lists a queued run. + * When `threadRef`'s mode has sub-threads, it accepts defined messages `queuedRunPlace` maps to + * that view using loaded sub-thread first messages. It rejects `undefined`, so no view shows a run + * until its message arrives while the sending view keeps its pending row. Other modes accept all. + */ +export function useShowsQueuedRun( + threadRef: ScopedThreadRef | null, +): (message: QueuedMessage) => boolean { + const mode = useThreadDisplayMode(threadRef); + const view = use(SubThreadViewContext); + const summaries = useSubThreadSummaries(mode.subThreads ? threadRef : null); + return (message) => + !mode.subThreads || + (message !== undefined && queuedRunPlace(message, (first) => summaries.has(first)) === view); +} + +/** + * Returns `count` of queued runs this view lists in `projection`. `ownsEdit(context)` checks edit + * ownership from the reply record and loaded sub-threads, so ownership stays when the run leaves + * the queue. Without sub-threads, this view owns all edits. `recoveryTarget(context)` returns the + * message box for unsaved edit text when the run leaves, or `undefined` if `threadRef` is `null`. + */ +export function useQueuedRunsInView( + threadRef: ScopedThreadRef | null, + projection: QueueProjection | null, +): { + readonly count: number; + readonly ownsEdit: (context: OrchestrationMessageContext | undefined) => boolean; + readonly recoveryTarget: ( + context: OrchestrationMessageContext | undefined, + ) => ScopedThreadRef | DraftId | undefined; +} { + const showsMessage = useShowsQueuedRun(threadRef); + const mode = useThreadDisplayMode(threadRef); + const view = use(SubThreadViewContext); + const summaries = useSubThreadSummaries(mode.subThreads ? threadRef : null); + const runs = projection === null ? [] : getUserQueuedThreadRuns(projection); + const messages = new Map( + runs.length === 0 ? [] : (projection?.messages ?? []).map((message) => [message.id, message]), + ); + return { + count: runs.filter((run) => showsMessage(messages.get(run.userMessageId))).length, + ownsEdit: (context) => + !mode.subThreads || recordPlace(context, (first) => summaries.has(first)) === view, + recoveryTarget: (context) => (threadRef === null ? undefined : editHome(threadRef, context)), + }; +} + +/** + * Returns `steer` and `edit` shortcut labels from `keybindings` for queued message tooltips. + * Returns `null` for both in a sub-thread view, because queue keyboard shortcuts do not run there. + */ +export function useQueueShortcutLabels(keybindings: ResolvedKeybindingsConfig): { + readonly steer: string | null; + readonly edit: string | null; +} { + const inSubThread = use(SubThreadViewContext) !== null; + return { + steer: inSubThread + ? null + : shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", { + context: { terminalFocus: false }, + }), + edit: inSubThread + ? null + : shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", { + context: { composerFocus: true }, + }), + }; +} + +/** + * Returns `messages` in the main list and `undefined` in a sub-thread view. + * Guest messages are not replies and belong only to the main list. + */ +export function useGuestMessagesInView(messages: T | undefined): T | undefined { + return use(SubThreadViewContext) === null ? messages : undefined; +} + +/** + * Returns the message box showing a queued edit when its run leaves the queue. Uses the reply box + * of the sub-thread in `context`'s reply record when `threadRef`'s mode has sub-threads and loaded + * history shows that sub-thread, or `threadRef`, the main box. The edit hook puts unsaved text back. + */ +function editHome( + threadRef: ScopedThreadRef, + context: OrchestrationMessageContext | undefined, +): ScopedThreadRef | DraftId { + if (!readThreadDisplay(threadRef).mode.subThreads) return threadRef; + const summaries = readSubThreadSummaries(threadRef); + const first = recordPlace(context, (id) => summaries.has(id)); + return first === null + ? threadRef + : (subThreadDraftId(scopedThreadKey(threadRef), first) ?? threadRef); +} + +/** + * Returns the first message id of the sub-thread named by `context`'s reply record when `loaded` + * is true for that id, or `null` for the main list. Queued-message edit ownership and edit + * recovery both use it so they agree on where an edited message lives. + */ +function recordPlace( + context: OrchestrationMessageContext | undefined, + loaded: (first: string) => boolean, +): string | null { + const first = subThreadOfRecords(context?.records); + return first !== undefined && loaded(first) ? first : null; +} + +/** + * Tooltip on a disabled queued-message pencil while another message box of the thread owns an + * open edit. A thread keeps one queued-message edit open at a time. + */ +export const QUEUE_EDIT_OPEN_ELSEWHERE = + "Save or cancel the queued message edit in another message box first."; diff --git a/apps/web/src/fork/subThreads/subThreadReply.ts b/apps/web/src/fork/subThreads/subThreadReply.ts index 21c35bf0056bb..55da673d840e3 100644 --- a/apps/web/src/fork/subThreads/subThreadReply.ts +++ b/apps/web/src/fork/subThreads/subThreadReply.ts @@ -48,9 +48,6 @@ export const replyContextField = (first: string | null) => { export const addsContext = (context: OrchestrationMessageContext | undefined): boolean => context?.records.some((record) => record.kind !== SUB_THREAD_RECORD_KIND) === true; -/** Why a reply box does not edit a queued message: the thread keeps one edit, in the main box. */ -export const REPLY_BOX_QUEUE_EDIT_BLOCKED = "Edit a queued message from the main message box."; - /** * The draft of a sub-thread's reply box, or null for the main list. It holds the box's text and * attachments; the model and the modes are the thread's (subThreadDraft.ts). It takes the thread's diff --git a/apps/web/src/fork/subThreads/subThreadsState.ts b/apps/web/src/fork/subThreads/subThreadsState.ts index 450d800c34331..8c7832860bc7e 100644 --- a/apps/web/src/fork/subThreads/subThreadsState.ts +++ b/apps/web/src/fork/subThreads/subThreadsState.ts @@ -15,7 +15,9 @@ import { create } from "zustand"; import { connectionAtomRuntime } from "../../connection/runtime"; import { useRightPanelStore } from "../../rightPanelStore"; import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic"; +import { appAtomRegistry } from "../../rpc/atomRegistry"; import { useQuietThreadVisibleTurnItems } from "../../state/entities"; +import { environmentThreadDetails } from "../../state/threads"; import { useEnvironmentQuery } from "../../state/query"; import { timelineSubThreads } from "../displayMode/displayModeTimeline"; @@ -97,6 +99,17 @@ export function useSubThreadSummaries(threadRef: ScopedThreadRef | null): SubThr return threadRef === null ? NO_SUMMARIES : summariesOf(scopedThreadKey(threadRef), items); } +/** + * Returns `threadRef`'s sub-thread summaries from loaded history, keyed by first message id. + * Reads loaded turn items from the app's atom registry outside React. Shares the per-thread fold + * cache with `useSubThreadSummaries`, so it works even when no view has rendered the thread. + */ +export const readSubThreadSummaries = (threadRef: ScopedThreadRef): SubThreadSummaries => + summariesOf( + scopedThreadKey(threadRef), + appAtomRegistry.get(environmentThreadDetails.quietVisibleTurnItemsAtom(threadRef)), + ); + /** * Opens the thread's Replies tab on one sub-thread, or on the list with `first` null. With * `automatic`, the user did not ask for the tab, so keyboard focus stays where it is.