diff --git a/.github/workflows/closura-arc-ci.yml b/.github/workflows/closura-arc-ci.yml index 1e7d9a1c7d87..f2f15f00a1d5 100644 --- a/.github/workflows/closura-arc-ci.yml +++ b/.github/workflows/closura-arc-ci.yml @@ -136,6 +136,7 @@ jobs: vp run --filter @t3tools/client-runtime typecheck vp run --filter @t3tools/provider-core typecheck vp run --filter t3 typecheck + vp run --filter @t3tools/mobile typecheck - name: Test AssemblyAI dictation, native inbox and thread placement behavior shell: bash @@ -162,6 +163,28 @@ jobs: apps/web/src/lib/attachmentUploadQueue.test.ts \ apps/server/src/ws.test.ts + - name: Test mobile new-task placement, outbox and uploads + shell: bash + working-directory: apps/mobile + run: | + set -euo pipefail + vp test run \ + src/state/thread-placement.model.test.ts \ + src/state/threadOutboxDelivery.placement.test.ts \ + src/state/composer-attachment-uploads.test.ts \ + src/lib/composerAttachmentUploadQueue.test.ts \ + src/lib/attachmentUpload.test.ts \ + src/state/use-composer-drafts.test.ts \ + src/state/thread-outbox.test.ts \ + src/state/threadOutboxDelivery.permissions.test.ts \ + src/state/threadOutboxDelivery.test.ts \ + src/state/pending-thread-creation.test.ts \ + src/lib/projectThreadStartTurn.test.ts \ + src/features/threads/thread-route-state.test.ts \ + src/features/threads/new-task-flow-provider.test.tsx \ + src/features/home/pendingTaskRoute.test.tsx \ + src/features/threads/NewTaskDraftRouteScreen.test.tsx + - name: Build native T3 server shell: bash run: vp run --filter t3 build:bundle diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index b2ad65cf0537..3aa8f3c325f9 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -1,4 +1,8 @@ -import { isDraftThreadRoute } from "./features/threads/thread-route-state"; +import { + explicitDraftRouteEntry, + isDraftThreadRoute, + type NewTaskDraftRouteParams, +} from "./features/threads/thread-route-state"; import { ComponentCatalogScreen } from "./features/development/ComponentCatalogScreen"; import { PullRequestGuideStopScreen } from "./features/pull-requests/guide/PullRequestGuideScreen"; import { PullRequestInlineCommentScreen } from "./features/pull-requests/PullRequestInlineCommentScreen"; @@ -399,9 +403,8 @@ function RootStackLayout(props: { const draftRouteOnTop = draftRoute !== undefined && props.state.routes.findLast((route) => route.name === "Thread") === draftRoute; - const draftParams = ( - draftRoute?.params as { draft?: { draftId?: string | string[] } } | undefined - )?.draft; + const draftParams = (draftRoute?.params as { draft?: NewTaskDraftRouteParams } | undefined) + ?.draft; const routeDraftId = Array.isArray(draftParams?.draftId) ? draftParams.draftId[0] : draftParams?.draftId; @@ -411,6 +414,7 @@ function RootStackLayout(props: { active={draftRouteOnTop} flowKey={draftRoute === undefined ? undefined : newTaskFlowKey(draftRoute)} routeDraftId={routeDraftId} + routeEntry={explicitDraftRouteEntry(draftParams)} > diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index 05ef660af4e9..f24cb5154b73 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -1,4 +1,5 @@ import { uuidv4 } from "../../lib/uuid"; +import { threadBranchDraftParams } from "../threads/thread-route-state"; import { ThreadUndoNotice } from "./ThreadUndoNotice"; import { use } from "react"; import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; @@ -79,13 +80,7 @@ export function HomeRouteScreen() { selectThreadRoute({ environmentId: String(thread.environmentId), threadId: String(thread.id) }); const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => { selectThreadRoute({ - draft: { - requestId: uuidv4(), - environmentId: String(thread.environmentId), - projectId: String(thread.projectId), - branch: thread.branch, - worktreePath: thread.worktreePath, - }, + draft: threadBranchDraftParams(thread, uuidv4()), }); }; diff --git a/apps/mobile/src/features/home/pendingTaskRoute.test.tsx b/apps/mobile/src/features/home/pendingTaskRoute.test.tsx new file mode 100644 index 000000000000..c1f75bbc0dd0 --- /dev/null +++ b/apps/mobile/src/features/home/pendingTaskRoute.test.tsx @@ -0,0 +1,358 @@ +import { RegistryContext, useAtomValue } from "@effect/atom-react"; +import { + CommandId, + EnvironmentId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type { Atom } from "effect/reactivity"; +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vite-plus/test"; + +// PR75-R1-F1: a placed task reopened from Home follows its message to the machine its origin binds. +// The pending-list handler, the list model and both route readers are real; navigation, thread +// detail, entities and the outbox store are doubles. +const harness = vi.hoisted(() => ({ + params: undefined as undefined | Record, + setParams: vi.fn(), + detailReads: [] as Array, + /** Calls into the sole speculative detail preloader, which mounts a thread's detail early. */ + preloads: [] as Array, + queue: null as unknown as Atom.Writable>>, +})); +vi.mock("@react-navigation/native", () => ({ + useRoute: () => ({ params: harness.params }), + useNavigation: () => ({ setParams: harness.setParams }), +})); +vi.mock("../../state/entities", () => ({ + useProject: () => null, + useQuietThreadShell: () => null, +})); +vi.mock("../../state/threads", async () => { + const Option = await import("effect/Option"); + return { + useEnvironmentThread: (environmentId: string | null, threadId: string | null) => { + if (environmentId !== null) harness.detailReads.push(`${environmentId}:${threadId}`); + return { data: Option.none() }; + }, + startOpeningEnvironmentThread: (environmentId: string, threadId: string) => { + harness.preloads.push(`${environmentId}:${threadId}`); + }, + }; +}); +vi.mock("../../state/use-remote-environment-registry", () => ({ + useRemoteEnvironmentRuntime: () => null, + useSavedRemoteConnection: () => null, +})); +vi.mock("../../state/use-thread-outbox", async () => { + const { Atom: A } = await import("effect/reactivity"); + const { useAtomValue: read } = await import("@effect/atom-react"); + harness.queue = A.make>>({}).pipe(A.keepAlive); + return { + useThreadOutboxMessages: () => read(harness.queue), + editingQueuedMessageIdsAtom: A.make({}), + holdEditingQueuedMessage: vi.fn(), + releaseEditingQueuedMessage: vi.fn(), + }; +}); +vi.mock("../../state/thread-outbox-removal", () => ({ removeThreadOutboxMessage: vi.fn() })); +vi.mock("../../state/use-composer-drafts", () => ({ clearComposerDraftContent: vi.fn() })); +vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); +vi.mock("./thread-dismissal", () => ({ withThreadDismissal: vi.fn() })); + +import { appAtomRegistry } from "../../state/atom-registry"; +import { buildPendingNewTasks } from "../../state/pending-new-tasks-model"; +import { pendingThreadCreationOutcomesAtom } from "../../state/pending-thread-creation"; +import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; +import { useFollowPendingRoute, useThreadSelection } from "../../state/use-thread-selection"; +import { threadSelectionDeferral } from "../layout/deferred-navigation"; +import { startOpeningDetail } from "../layout/workspace/useSelectWorkspaceDetail"; +import { usePendingTaskListActions } from "./usePendingTaskListActions"; + +const laptop = EnvironmentId.make("laptop"); +const box = EnvironmentId.make("box"); +function task(overrides: Partial = {}): QueuedThreadMessage { + return { + environmentId: laptop, + threadId: ThreadId.make("thread-auto"), + messageId: MessageId.make("message-auto"), + commandId: CommandId.make("command-auto"), + text: "Fix the build", + attachments: [], + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + creation: { + projectId: ProjectId.make("project-a"), + workspaceMode: "worktree", + branch: "main", + worktreePath: null, + }, + placement: { + originEnvironmentId: laptop, + originProjectId: ProjectId.make("project-a"), + candidateEnvironmentIds: [laptop, box], + }, + createdAt: "2026-11-18T16:00:00.000Z", + ...overrides, + }; +} +const keyed = (...messages: QueuedThreadMessage[]) => + Object.fromEntries( + messages.map((message) => [`${message.environmentId}:${message.threadId}`, [message]]), + ); + +type ThreadRoute = Record; +const recordRoute = (params: ThreadRoute) => { + harness.params = params; +}; +/** + * The workspace layout's thread selection, in its own order: inside the real selection gate, the + * real shared preload boundary runs before navigation, which here records the route's params. + */ +const selectThroughWorkspace = (params: ThreadRoute) => + threadSelectionDeferral.run(() => { + startOpeningDetail({ name: "Thread", params } as never); + recordRoute(params); + }); + +/** Opens the task as the Home list does: the real list model and the real handler. */ +function openFromHome( + message: QueuedThreadMessage, + select: (params: ThreadRoute) => void = recordRoute, +) { + const [pending] = buildPendingNewTasks({ + queuedMessages: [message], + drafts: {}, + sendGate: { + connectedEnvironmentIds: new Set(), + operableEnvironmentIds: new Set(), + shellStatuses: new Map(), + retryingMessageIds: {}, + }, + }); + if (pending?.kind !== "pending") throw new Error("Home lists no pending task for this message"); + let open!: ReturnType["openPendingTask"]; + function Handler() { + const actions = usePendingTaskListActions((params) => select(params as ThreadRoute)); + useLayoutEffect(() => { + open = actions.openPendingTask; + }); + return null; + } + const root = createRoot(document.createElement("div")); + act(() => root.render()); + act(() => open(pending)); + act(() => root.unmount()); +} + +function renderReaders() { + const seen = { + selection: null as null | ReturnType, + route: null as null | ReturnType, + }; + function Readers() { + // The two readers the live route uses: the thread selection and the route controller's. + const selection = useThreadSelection(); + const route = useFollowPendingRoute(harness.params); + useAtomValue(harness.queue); + useLayoutEffect(() => { + seen.selection = selection; + seen.route = route; + }); + return null; + } + const root = createRoot(document.createElement("div")); + const render = () => + act(() => + root.render( + + + , + ), + ); + render(); + return { seen, render, [Symbol.dispose]: () => act(() => root.unmount()) }; +} + +function reset() { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + harness.params = undefined; + harness.setParams.mockReset(); + harness.detailReads.length = 0; + harness.preloads.length = 0; + appAtomRegistry.set(harness.queue, {}); + appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {}); +} + +describe("PR75-R1-F1: a placed task reopened from Home", () => { + it("follows its message from A to B through both readers, and keeps B once it is delivered", () => { + reset(); + const queued = task(); + appAtomRegistry.set(harness.queue, keyed(queued)); + openFromHome(queued); + expect(harness.params).toEqual({ + environmentId: "laptop", + threadId: "thread-auto", + pendingMessageId: "message-auto", + }); + using readers = renderReaders(); + expect(readers.seen.selection?.selectedThreadRef).toEqual({ + environmentId: "laptop", + threadId: "thread-auto", + }); + expect(readers.seen.route?.routeFollowsBinding).toBe(true); + + // Its origin binds it to B: the same message moves to B's key. + const bound = task({ + environmentId: box, + placement: { + ...queued.placement!, + bound: { environmentId: box, projectId: ProjectId.make("project-b") }, + }, + }); + act(() => appAtomRegistry.set(harness.queue, keyed(bound))); + expect(readers.seen.selection?.selectedThreadRef).toEqual({ + environmentId: "box", + threadId: "thread-auto", + }); + expect(readers.seen.route).toMatchObject({ environmentId: "box", routeFollowsBinding: false }); + expect(harness.setParams.mock.calls).toEqual([ + [{ environmentId: "box", threadId: "thread-auto" }], + ]); + // The route moves only its own params; the navigator applies them. + harness.params = { ...harness.params, environmentId: "box" }; + readers.render(); + expect(readers.seen.route?.routeFollowsBinding).toBe(true); + + // Delivered at B: the queue entry goes, the outcome stays under B, then is collected. + act(() => { + appAtomRegistry.set(harness.queue, {}); + appAtomRegistry.set(pendingThreadCreationOutcomesAtom, { + "box:thread-auto": { kind: "delivered", message: bound }, + }); + }); + expect(readers.seen.selection?.selectedThreadRef).toEqual({ + environmentId: "box", + threadId: "thread-auto", + }); + act(() => appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {})); + expect(readers.seen.selection?.selectedThreadRef).toEqual({ + environmentId: "box", + threadId: "thread-auto", + }); + // Its detail was never read on A, where the thread never exists; B's once delivered. + expect(harness.detailReads.filter((read) => read.startsWith("laptop:"))).toEqual([]); + expect(harness.detailReads).toContain("box:thread-auto"); + expect(harness.setParams).toHaveBeenCalledTimes(1); + }); + + it("is not moved by another task's binding or completion", () => { + reset(); + const queued = task(); + appAtomRegistry.set(harness.queue, keyed(queued)); + openFromHome(queued); + using readers = renderReaders(); + const other = task({ + environmentId: box, + messageId: MessageId.make("message-other"), + threadId: ThreadId.make("thread-other"), + }); + act(() => { + appAtomRegistry.set(harness.queue, keyed(queued, other)); + appAtomRegistry.set(pendingThreadCreationOutcomesAtom, { + "box:thread-other": { kind: "delivered", message: other }, + }); + }); + expect(readers.seen.selection?.selectedThreadRef).toEqual({ + environmentId: "laptop", + threadId: "thread-auto", + }); + expect(harness.setParams).not.toHaveBeenCalled(); + }); + + it("reopens a fixed task as before: its machine and thread only", () => { + reset(); + const { placement: _placement, ...fixed } = task(); + appAtomRegistry.set(harness.queue, keyed(fixed)); + openFromHome(fixed); + expect(harness.params).toEqual({ environmentId: "laptop", threadId: "thread-auto" }); + }); + + it("never preloads the origin when a held selection is bound elsewhere before it runs", async () => { + reset(); + const queued = task(); + appAtomRegistry.set(harness.queue, keyed(queued)); + // A branch checkout holds thread selection; the task is chosen from Home meanwhile. + const checkout = Promise.withResolvers(); + threadSelectionDeferral.waitFor(checkout.promise); + openFromHome(queued, selectThroughWorkspace); + expect(harness.params).toBeUndefined(); + // Still held, its origin binds it to B: the same message, queued and undelivered there. + const bound = task({ + environmentId: box, + placement: { + ...queued.placement!, + bound: { environmentId: box, projectId: ProjectId.make("project-b") }, + }, + }); + appAtomRegistry.set(harness.queue, keyed(bound)); + checkout.resolve(); + await checkout.promise; + await Promise.resolve(); + // Navigation goes ahead with its message id; nothing was preloaded, on A or on B. + expect(harness.params).toEqual({ + environmentId: "laptop", + threadId: "thread-auto", + pendingMessageId: "message-auto", + }); + expect(harness.preloads).toEqual([]); + // The repaired readers take it from there: B, behind its pending-creation barrier. + using readers = renderReaders(); + expect(readers.seen.selection?.selectedThreadRef).toEqual({ + environmentId: "box", + threadId: "thread-auto", + }); + expect(harness.detailReads).toEqual([]); + harness.params = { ...harness.params, environmentId: "box" }; + readers.render(); + act(() => { + appAtomRegistry.set(harness.queue, {}); + appAtomRegistry.set(pendingThreadCreationOutcomesAtom, { + "box:thread-auto": { kind: "delivered", message: bound }, + }); + }); + act(() => appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {})); + expect(readers.seen.selection?.selectedThreadRef).toEqual({ + environmentId: "box", + threadId: "thread-auto", + }); + expect(harness.detailReads.filter((read) => read.startsWith("laptop:"))).toEqual([]); + expect(harness.detailReads).toContain("box:thread-auto"); + expect(harness.preloads).toEqual([]); + }); + + it("still preloads a held route that names no pending task", async () => { + reset(); + const { placement: _placement, ...fixed } = task(); + appAtomRegistry.set(harness.queue, keyed(fixed)); + const checkout = Promise.withResolvers(); + threadSelectionDeferral.waitFor(checkout.promise); + openFromHome(fixed, selectThroughWorkspace); + selectThroughWorkspace({ environmentId: "box", threadId: "thread-existing" }); + checkout.resolve(); + await checkout.promise; + await Promise.resolve(); + // The gate runs only the latest selection, preloaded as before, then navigated. + expect(harness.preloads).toEqual(["box:thread-existing"]); + expect(harness.params).toEqual({ environmentId: "box", threadId: "thread-existing" }); + const plain = Promise.withResolvers(); + threadSelectionDeferral.waitFor(plain.promise); + openFromHome(fixed, selectThroughWorkspace); + plain.resolve(); + await plain.promise; + await Promise.resolve(); + expect(harness.preloads).toEqual(["box:thread-existing", "laptop:thread-auto"]); + }); +}); diff --git a/apps/mobile/src/features/home/usePendingTaskListActions.ts b/apps/mobile/src/features/home/usePendingTaskListActions.ts index 698df0bfce70..03abe6b8e0ea 100644 --- a/apps/mobile/src/features/home/usePendingTaskListActions.ts +++ b/apps/mobile/src/features/home/usePendingTaskListActions.ts @@ -11,6 +11,7 @@ import { releaseEditingQueuedMessage, } from "../../state/use-thread-outbox"; import { withThreadDismissal } from "./thread-dismissal"; +import { queuedTaskRouteParams } from "../threads/thread-route-state"; export function usePendingTaskListActions( selectThreadRoute: (params: ReactNavigation.RootParamList["Thread"]) => void, @@ -22,10 +23,8 @@ export function usePendingTaskListActions( (pendingTask: PendingNewTask) => { selectThreadRoute( pendingTask.kind === "pending" - ? { - environmentId: String(pendingTask.environmentId), - threadId: String(pendingTask.message.threadId), - } + ? // Reopened as Send opened it: a placed task follows its message to its bound machine. + queuedTaskRouteParams(pendingTask.message) : { draft: { environmentId: String(pendingTask.environmentId), diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceThreadSidebar.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceThreadSidebar.tsx index da1fb44a4604..711002bef023 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceThreadSidebar.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceThreadSidebar.tsx @@ -2,6 +2,7 @@ import type { EnvironmentProject, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; +import { threadBranchDraftParams } from "../../threads/thread-route-state"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useNavigation, useNavigationState } from "@react-navigation/native"; @@ -71,13 +72,7 @@ export function WorkspaceThreadSidebar() { } onNewThreadOnBranch={(thread: EnvironmentThreadShell) => selectThreadRoute({ - draft: { - requestId: uuidv4(), - environmentId: String(thread.environmentId), - projectId: String(thread.projectId), - branch: thread.branch, - worktreePath: thread.worktreePath, - }, + draft: threadBranchDraftParams(thread, uuidv4()), }) } onOpenPendingTask={openPendingTask} diff --git a/apps/mobile/src/features/layout/workspace/useSelectWorkspaceDetail.ts b/apps/mobile/src/features/layout/workspace/useSelectWorkspaceDetail.ts index e487d9af071b..7bd7ec8c16ce 100644 --- a/apps/mobile/src/features/layout/workspace/useSelectWorkspaceDetail.ts +++ b/apps/mobile/src/features/layout/workspace/useSelectWorkspaceDetail.ts @@ -14,6 +14,9 @@ const first = (value: string | readonly string[] | undefined) => /** Starts loading a selected thread before navigation commits; see `startOpeningEnvironmentThread`. */ export function startOpeningDetail(detail: WorkspaceDetail) { if (detail.name !== "Thread") return; + // A pending task runs where its origin binds it, which this route may not name yet: its own + // readers load that thread behind its creation barrier, so nothing is preloaded here. + if (first(detail.params?.pendingMessageId)) return; const environmentId = first(detail.params?.environmentId); const threadId = first(detail.params?.threadId); if (environmentId && threadId) { diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx index 88ec0c06e43b..64c6b58ca9dc 100644 --- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx +++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx @@ -193,6 +193,20 @@ export function NewTaskEnvironmentPickerRouteScreen() { }} showsVerticalScrollIndicator={false} > + {flow.canPlaceAutomatically ? ( + + + { + void Haptics.selectionAsync(); + flow.setEnvironmentSelection(value ? "auto" : "manual"); + }} + /> + + + ) : null} {flow.environments.map((environment, index) => ( ))} diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index 201204a8a57b..7c57a439d064 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -257,7 +257,9 @@ export function NewTaskDraftScreen(props: { states: uploadStates, }) : null; + // An Auto draft's uploads wait for its placement; that wait is not an upload in progress here. const attachmentsUploading = + flow.environmentSelection !== "auto" && environmentConnected && selectedProject !== null && composerAttachmentsStillUploading({ @@ -526,10 +528,12 @@ export function NewTaskDraftScreen(props: { loadBranches(); }, [loadBranches, selectedProject]); - const selectedEnvironmentLabel = + const machineLabel = flow.environments.find( (environment) => environment.environmentId === flow.selectedEnvironmentId, )?.environmentLabel ?? "Environment"; + // Auto names the choice the origin makes at Send; a pinned draft names its machine. + const selectedEnvironmentLabel = flow.routesAutomatically ? "Auto" : machineLabel; const availableCurrentBranchName = flow.availableBranches.find((branch) => branch.current)?.name ?? flow.availableBranches.find((branch) => branch.isDefault)?.name ?? @@ -673,11 +677,7 @@ export function NewTaskDraftScreen(props: { return null; } promptInputRef.current?.blur(); - navigation.dispatch( - CommonActions.setParams( - submittedThreadParams(String(message.environmentId), String(message.threadId)), - ), - ); + navigation.dispatch(CommonActions.setParams(submittedThreadParams(message))); // The composer has moved to the submitted thread; a pick still converting // would otherwise resurrect this draft. abortComposerDraftOperations(draftKey); diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 4d814d3a8a4f..bbfc0dc0b44e 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -69,7 +69,7 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; import { useSelectedThreadDetailState } from "../../state/use-thread-detail"; -import { useThreadSelection } from "../../state/use-thread-selection"; +import { useFollowPendingRoute, useThreadSelection } from "../../state/use-thread-selection"; import { GitActionProgressOverlay } from "./GitActionProgressOverlay"; import { buildTerminalMenuSessions, @@ -82,7 +82,7 @@ import { } from "../terminal/terminalLaunchContext"; import type { ThreadDetailScreenProps } from "./ThreadDetailScreen"; import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost"; -import { draftRouteIdentity } from "./thread-route-state"; +import { draftRouteIdentity, threadEnvironmentDraftParams } from "./thread-route-state"; import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen"; import { GitOverviewSheet } from "./git/GitOverviewSheet"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -166,6 +166,8 @@ function OpeningThreadLoadingScreen() { type ThreadRouteScreenRouteProps = StaticScreenProps<{ readonly environmentId?: string; readonly threadId?: string; + /** A sent task placed by its origin: the route follows that message's binding. */ + readonly pendingMessageId?: string; readonly draft?: NewTaskDraftRouteParams; readonly inspector?: ThreadInspectorTarget; readonly prompt?: string | string[]; @@ -212,13 +214,7 @@ function UnavailableThreadDraftRedirect(props: { readonly environmentId: Environ const project = projects.find((candidate) => candidate.environmentId === props.environmentId); navigation.dispatch( StackActions.replace("Thread", { - draft: project - ? { - requestId: uuidv4(), - environmentId: String(project.environmentId), - projectId: String(project.id), - } - : { requestId: uuidv4() }, + draft: threadEnvironmentDraftParams(project, uuidv4()), }), ); }); @@ -250,8 +246,12 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { const { connectionState } = useRemoteConnectionStatus(); const { selectedThread } = useThreadSelection(); const params = props.route.params ?? {}; - const environmentIdRaw = firstRouteParam(params.environmentId); - const threadIdRaw = firstRouteParam(params.threadId); + // Resolved through the pending task's binding before any scoped key or detail read. + const { + environmentId: environmentIdRaw, + threadId: threadIdRaw, + routeFollowsBinding, + } = useFollowPendingRoute(params); const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null; const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId); const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId); @@ -289,7 +289,7 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { content ); - if (environmentId === null || threadIdRaw === null) { + if (environmentId === null || threadIdRaw === null || !routeFollowsBinding) { return withInspectorHeader(); } diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx index 05ccf29b2ae7..51e770b8d165 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx @@ -6,6 +6,7 @@ import { AuthFilesystemReadScope, DEFAULT_SERVER_SETTINGS, EnvironmentId, + ProviderInstanceId, ProjectId, type VcsListRefsResult, } from "@t3tools/contracts"; @@ -16,7 +17,7 @@ import * as Stream from "effect/Stream"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { act, useLayoutEffect } from "react"; import { createRoot } from "react-dom/client"; -import { expect, it, vi } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import type { ComposerDraft } from "../../state/use-composer-drafts"; const mocks = vi.hoisted(() => ({ @@ -36,6 +37,9 @@ const mocks = vi.hoisted(() => ({ serverConfig: vi.fn(), openScratch: vi.fn(), prepareTriage: vi.fn(), + /** Machines the client has saved and is connected to; empty unless a case sets them. */ + savedConnections: {} as Record, + connected: [] as Array<{ environmentId: string; connectionState: string }>, })); vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: { @@ -58,6 +62,7 @@ vi.mock("../../state/projects", () => ({ })); vi.mock("../../state/session", () => ({ environmentSession: { sessionStateAtom: mocks.session }, + readEnvironmentScope: () => true, })); vi.mock("../../state/presentation", () => ({ useEnvironmentPresentation: mocks.presentation, @@ -73,8 +78,8 @@ vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.openScratch })); vi.mock("../triage/usePrepareTriage", () => ({ usePrepareTriage: () => mocks.prepareTriage })); vi.mock("../../state/use-remote-environment-registry", () => ({ - useSavedRemoteConnections: () => ({ savedConnectionsById: {} }), - useRemoteConnectionStatus: () => ({ connectedEnvironments: [] }), + useSavedRemoteConnections: () => ({ savedConnectionsById: mocks.savedConnections }), + useRemoteConnectionStatus: () => ({ connectedEnvironments: mocks.connected }), setPendingConnectionError: vi.fn(), })); vi.mock("../../state/use-model-option-memory", () => ({ @@ -112,6 +117,11 @@ vi.mock("../../state/shell", () => ({ useEnvironmentShellReadiness: () => ({}) } vi.mock("../../lib/clock", () => ({ useNowMinuteMs: () => 0 })); import { NewTaskFlowProvider, useNewTaskFlow } from "./new-task-flow-provider"; +import { + explicitDraftRouteEntry, + threadBranchDraftParams, + threadEnvironmentDraftParams, +} from "./thread-route-state"; function project(environment: string, id: string): EnvironmentProject { return { @@ -132,6 +142,8 @@ function setup() { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; vi.useFakeTimers(); vi.clearAllMocks(); + mocks.savedConnections = {}; + mocks.connected = []; const registry = AtomRegistry.make(); mocks.registry.mockReturnValue(registry); const projects = [project("one", "a"), project("one", "b"), project("two", "b")]; @@ -202,9 +214,10 @@ function setup() { return (key === null ? undefined : all[key]) ?? empty; }); mocks.snapshot.mockImplementation(snapshot); - mocks.createDraft.mockImplementation((target) => { + // As createNewTaskDraft: the seeded machine intent is stored with the new draft. + mocks.createDraft.mockImplementation((target, environmentSelection) => { const key = `new-task:${Object.keys(registry.get(drafts)).length}`; - write(key, { project: target }); + write(key, { project: target, ...(environmentSelection ? { environmentSelection } : {}) }); return key; }); mocks.retargetDraft.mockImplementation((key, target) => @@ -245,11 +258,22 @@ function setup() { get current() { return current; }, - async render(active: boolean) { + async render( + active: boolean, + route: { + readonly routeEntry?: { readonly environmentId: string; readonly projectId: string }; + readonly routeDraftId?: string; + } = {}, + ) { await act(async () => root.render( - + , @@ -442,3 +466,220 @@ it.each([ expect(screen.current.selectedProject).toEqual(screen.projects[expectedProject]); }, ); + +describe("a new task's machine choice", () => { + const twoMachines = () => { + // Earlier cases leave a provider-less config behind; these cases load none. + mocks.serverConfig.mockReturnValue(null); + mocks.projects.mockReturnValue([project("one", "b"), project("two", "b")]); + mocks.savedConnections = { one: { environmentLabel: "One" }, two: { environmentLabel: "Two" } }; + mocks.connected = [ + { environmentId: "one", connectionState: "connected" }, + { environmentId: "two", connectionState: "connected" }, + ]; + }; + + it("starts a genuinely new draft as Auto when more than one connected machine hosts it", async () => { + using screen = setup(); + twoMachines(); + await screen.render(true); + expect(mocks.createDraft).toHaveBeenCalledWith( + { environmentId: "one", projectId: "b" }, + "auto", + ); + expect(screen.current.environmentSelection).toBe("auto"); + expect(screen.current.routesAutomatically).toBe(true); + expect(screen.current.canPlaceAutomatically).toBe(true); + }); + + it("queues an Auto draft as a placed creation from its origin, without the origin's paths", async () => { + using screen = setup(); + twoMachines(); + await screen.render(true); + const key = screen.current.draftKey!; + act(() => { + mocks.writeText(key, "Fix the build"); + mocks.writeSettings(key, { + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + workspaceSelection: { mode: "worktree", branch: "main", worktreePath: null }, + }); + }); + const metadata = { + threadId: "thread-1", + messageId: "message-1", + commandId: "command-1", + createdAt: "2026-11-18T16:00:00.000Z", + }; + const auto = screen.current.buildPendingTaskMessage(metadata as never); + expect(auto).toMatchObject({ + environmentId: "one", + commandId: "command-1", + messageId: "message-1", + placement: { + originEnvironmentId: "one", + originProjectId: "b", + candidateEnvironmentIds: ["one", "two"], + }, + creation: { projectId: "b", workspaceMode: "worktree", branch: "main", worktreePath: null }, + }); + // Pinned, the same draft queues fixed work there, as before. + act(() => mocks.writeSettings(key, { environmentSelection: "manual" })); + expect(screen.current.buildPendingTaskMessage(metadata as never)?.placement).toBeUndefined(); + }); + + const metadata = { + threadId: "thread-1", + messageId: "message-1", + commandId: "command-1", + createdAt: "2026-11-18T16:00:00.000Z", + }; + const readyToSend = (screen: ReturnType, key: string) => + act(() => { + mocks.writeText(key, "Fix the build"); + mocks.writeSettings(key, { + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + workspaceSelection: { mode: "worktree", branch: "main", worktreePath: null }, + }); + }); + + it("pins a fresh draft from an explicit machine entry, and queues fixed work there", async () => { + using screen = setup(); + twoMachines(); + // The unavailable-thread redirect's own params, read back as Stack reads them. + const entry = explicitDraftRouteEntry( + threadEnvironmentDraftParams(project("one", "b"), "request-1"), + ); + expect(entry).toEqual({ environmentId: "one", projectId: "b" }); + await screen.render(true, { routeEntry: entry }); + expect(mocks.createDraft).toHaveBeenCalledTimes(1); + expect(mocks.createDraft).toHaveBeenCalledWith( + { environmentId: "one", projectId: "b" }, + "manual", + ); + const key = screen.current.draftKey!; + expect(screen.current.routesAutomatically).toBe(false); + readyToSend(screen, key); + const queued = screen.current.buildPendingTaskMessage(metadata as never); + expect(queued).toMatchObject({ environmentId: "one", creation: { projectId: "b" } }); + expect(queued?.placement).toBeUndefined(); + }); + + it("waits for an explicit entry's own machine instead of seeding the default one first", async () => { + using screen = setup(); + twoMachines(); + // A thread-branch entry on machine two, while the flow still shows machine one. + const entry = explicitDraftRouteEntry( + threadBranchDraftParams( + { environmentId: "two", projectId: "b", branch: null, worktreePath: null }, + "request-2", + ), + ); + await screen.render(true, { routeEntry: entry }); + expect(mocks.createDraft).not.toHaveBeenCalled(); + // The route's effect applies its project: the draft is created there, pinned, once. + await act(async () => screen.current.setProject(project("two", "b"))); + expect(mocks.createDraft.mock.calls).toEqual([ + [{ environmentId: "two", projectId: "b" }, "manual"], + ]); + expect(screen.current.environmentSelection).toBe("manual"); + }); + + it("creates no draft for an explicit entry until its own machine's project is there", async () => { + using screen = setup(); + twoMachines(); + // Only B is loaded: the flow would fall back to it, but the entry names A. + mocks.projects.mockReturnValue([project("two", "b")]); + const entry = explicitDraftRouteEntry( + threadEnvironmentDraftParams(project("one", "b"), "request-3"), + ); + await screen.render(true, { routeEntry: entry }); + expect(mocks.createDraft).not.toHaveBeenCalled(); + expect(screen.current.draftKey).toBeNull(); + // Nothing to queue or upload from a fallback draft. + expect(screen.current.buildPendingTaskMessage(metadata as never)).toBeNull(); + // A arrives behind B; the route's project selection (the provider's setProject, as the + // draft route's effect applies it) creates the first and only draft: A, pinned. + mocks.projects.mockReturnValue([project("two", "b"), project("one", "b")]); + await screen.render(true, { routeEntry: entry }); + expect(mocks.createDraft).not.toHaveBeenCalled(); + await act(async () => screen.current.setProject(project("one", "b"))); + expect(mocks.createDraft.mock.calls).toEqual([ + [{ environmentId: "one", projectId: "b" }, "manual"], + ]); + expect(screen.current.environmentSelection).toBe("manual"); + }); + + it("keeps a later deliberate Auto choice when the route is applied again", async () => { + using screen = setup(); + twoMachines(); + const entry = { environmentId: "one", projectId: "b" }; + await screen.render(true, { routeEntry: entry }); + act(() => screen.current.setEnvironmentSelection("auto")); + await screen.render(true, { routeEntry: { ...entry } }); + await act(async () => screen.current.setProject(project("one", "b"))); + expect(screen.current.environmentSelection).toBe("auto"); + expect(mocks.createDraft).toHaveBeenCalledTimes(1); + }); + + it("restores a pinned draft as pinned, and a generic project entry still starts as Auto", async () => { + using screen = setup(); + twoMachines(); + act(() => { + mocks.writeSettings("new-task:restored", { + project: { environmentId: "one", projectId: "b" }, + environmentSelection: "manual", + }); + }); + await screen.render(true, { routeDraftId: "new-task:restored" }); + expect(mocks.createDraft).not.toHaveBeenCalled(); + expect(screen.current.environmentSelection).toBe("manual"); + // A generic project entry names no machine intent: it is not an explicit entry. + expect( + explicitDraftRouteEntry({ requestId: "r", environmentId: "one", projectId: "b" }), + ).toBeUndefined(); + }); + + it("leaves a new draft on its machine when only one machine could take it", async () => { + using screen = setup(); + mocks.projects.mockReturnValue([project("one", "b")]); + mocks.savedConnections = { one: { environmentLabel: "One" } }; + mocks.connected = [{ environmentId: "one", connectionState: "connected" }]; + await screen.render(true); + expect(mocks.createDraft).toHaveBeenCalledWith( + { environmentId: "one", projectId: "b" }, + undefined, + ); + expect(screen.current.routesAutomatically).toBe(false); + }); + + it("pins the draft when a machine is picked, and keeps stored Auto when machines go away", async () => { + using screen = setup(); + twoMachines(); + await screen.render(true); + const key = screen.current.draftKey!; + // Fewer machines later: the stored intent stays Auto, never silently fixed. + mocks.connected = []; + await screen.render(true); + expect(screen.current.environmentSelection).toBe("auto"); + expect(screen.current.routesAutomatically).toBe(true); + await act(async () => { + await screen.current.switchEnvironment(EnvironmentId.make("one")); + }); + expect(screen.snapshot(key).environmentSelection).toBe("manual"); + expect(screen.current.routesAutomatically).toBe(false); + }); + + it("keeps a real locality choice pinned while Auto is selected", async () => { + using screen = setup(); + twoMachines(); + await screen.render(true); + const key = screen.current.draftKey!; + act(() => { + mocks.writeSettings(key, { + workspaceSelection: { mode: "local", branch: "main", worktreePath: null }, + }); + }); + expect(screen.snapshot(key).environmentSelection).toBe("auto"); + expect(screen.current.routesAutomatically).toBe(false); + }); +}); diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 5852206095a8..9ad78fd94039 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -12,6 +12,7 @@ import type { ServerProvider, } from "@t3tools/contracts"; import { + AuthOrchestrationOperateScope, CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, MessageId, @@ -66,6 +67,11 @@ import { import { useBranches, usePaginatedBranches } from "../../state/queries"; import { vcsEnvironment } from "../../state/vcs"; import { type QueuedThreadMessage } from "../../state/thread-outbox"; +import { readEnvironmentScope } from "../../state/session"; +import { + draftRoutesAutomatically, + seedsAutomaticPlacement, +} from "../../state/thread-placement-rule"; import { setPendingConnectionError, useRemoteConnectionStatus, @@ -128,6 +134,29 @@ export function branchBadgeLabel(input: { return null; } +/** Whether a project is the same repository as the reference, as the machine list matches it. */ +function hostsRepositoryOf(reference: { + readonly repositoryKey: string | null; + readonly workspaceBasename: string | null; + readonly title: string | null; +}) { + return (project: EnvironmentProject) => { + if (reference.repositoryKey === null && reference.workspaceBasename === null) { + return true; + } + const projectKey = project.repositoryIdentity + ? repositoryGroupingKeyOf(project.repositoryIdentity) + : null; + if (reference.repositoryKey !== null && projectKey !== null) { + return projectKey === reference.repositoryKey; + } + return ( + project.workspaceRoot.split("/").at(-1) === reference.workspaceBasename || + (reference.title !== null && project.title === reference.title) + ); + }; +} + type NewTaskFlowContextValue = { readonly activeNewTask: { readonly pendingKey: string | null } | null; readonly projectScopes: ReadonlyArray; @@ -181,6 +210,13 @@ type NewTaskFlowContextValue = { readonly draftId: string; readonly kind: "missing" | "pickProject"; } | null; + /** The draft's stored machine intent; absent on drafts from before the choice existed. */ + readonly environmentSelection: "auto" | "manual" | undefined; + /** Whether Send hands the task to its origin to place, rather than running it here. */ + readonly routesAutomatically: boolean; + /** Whether Auto is offered: more than one machine hosts this project. */ + readonly canPlaceAutomatically: boolean; + readonly setEnvironmentSelection: (selection: "auto" | "manual") => void; readonly selectEnvironment: (environmentId: EnvironmentId) => void; readonly switchEnvironment: (environmentId: EnvironmentId) => Promise; readonly switchingToEnvironmentId: EnvironmentId | null; @@ -223,6 +259,8 @@ export function NewTaskFlowProvider( /** Identifies the draft route this flow serves; a new key starts a fresh flow. */ flowKey?: string; routeDraftId?: string; + /** An entry scoped to one machine: a new draft for it is pinned there from its creation. */ + routeEntry?: { readonly environmentId: string; readonly projectId: string }; }>, ) { const projects = useProjects(); @@ -333,6 +371,104 @@ export function NewTaskFlowProvider( const serverConfigs = useServerConfigs(); const { connectedEnvironments } = useRemoteConnectionStatus(); const selectedProjectDraftKey = selectedProject ? activeDraftKey : null; + const scratchEnvironments = connectedEnvironments.filter( + (environment) => + availableScratchWorkspaceRoot( + environment.connectionState, + serverConfigs.get(environment.environmentId), + ) !== null, + ); + + const selectedRepositoryKey = selectedProject?.repositoryIdentity + ? repositoryGroupingKeyOf(selectedProject.repositoryIdentity) + : null; + // Use || null: placeholder workspaceRoot can be empty, and an empty basename rejects real hosts. + const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null; + const selectedProjectTitle = selectedProject?.title ?? null; + const environments = (() => { + if (isScratchDraft) { + return scratchEnvironments.map((environment) => ({ + environmentId: environment.environmentId, + environmentLabel: environment.environmentLabel, + })); + } + const seen = new Set(); + const result: Array<{ + readonly environmentId: EnvironmentId; + readonly environmentLabel: string; + }> = []; + const hostsSelectedRepository = hostsRepositoryOf({ + repositoryKey: selectedRepositoryKey, + workspaceBasename: selectedWorkspaceBasename, + title: selectedProjectTitle, + }); + for (const project of projects) { + if (!hostsSelectedRepository(project)) { + continue; + } + if (seen.has(project.environmentId)) { + continue; + } + const environment = savedConnectionsById[project.environmentId]; + if (!environment) { + continue; + } + seen.add(project.environmentId); + result.push({ + environmentId: project.environmentId, + environmentLabel: environment.environmentLabel, + }); + } + return result; + })(); + + const isRouteEntry = (project: EnvironmentProject) => + props.routeEntry !== undefined && + String(project.environmentId) === props.routeEntry.environmentId && + String(project.id) === props.routeEntry.projectId; + /** + * A genuinely new draft's machine intent, stored once: an explicit machine entry pins its own + * machine; otherwise it starts as Auto when more than one connected, operable machine hosts the + * project now, and from then on that is its intent whatever the connections do. + */ + const newDraftSelection = ( + project: EnvironmentProject, + isScratch: boolean, + ): "auto" | "manual" | undefined => { + if (isRouteEntry(project)) return "manual"; + const hosts = hostsRepositoryOf({ + repositoryKey: project.repositoryIdentity + ? repositoryGroupingKeyOf(project.repositoryIdentity) + : null, + workspaceBasename: project.workspaceRoot.split("/").at(-1) || null, + title: project.title, + }); + const candidates = new Set( + projects + .filter( + (candidate) => + hosts(candidate) && + savedConnectionsById[candidate.environmentId] !== undefined && + connectedEnvironments.some( + (environment) => + environment.environmentId === candidate.environmentId && + environment.connectionState === "connected", + ) && + readEnvironmentScope(candidate.environmentId, AuthOrchestrationOperateScope), + ) + .map((candidate) => candidate.environmentId), + ); + return seedsAutomaticPlacement({ isScratch, candidateCount: candidates.size }) + ? "auto" + : undefined; + }; + // Read at render, so changes to the entry's target, the catalog or the candidates wake creation. + // An explicit machine entry seeds only its own project: while that is unresolved, absent or not + // yet applied, no draft is created at all, never a fallback on another machine. + const awaitsRouteEntry = + props.routeEntry !== undefined && (selectedProject === null || !isRouteEntry(selectedProject)); + const initialSelection = + selectedProject === null ? undefined : newDraftSelection(selectedProject, isScratchDraft); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates the persistent draft in the new-task flow store once a project is selected, before the composer mounts useEffect(() => { // A route that names a draft binds that draft, or returns to the picker. @@ -340,18 +476,30 @@ export function NewTaskFlowProvider( props.active === false || props.routeDraftId !== undefined || activeDraftKey !== null || - selectedProject === null + selectedProject === null || + awaitsRouteEntry ) { return; } // Creates the persistent draft once the project selection is ready; the key must exist before the composer mounts. updateNewTaskFlowState(flowKey, { - draftKey: createNewTaskDraft({ - environmentId: selectedProject.environmentId, - projectId: selectedProject.id, - }), + draftKey: createNewTaskDraft( + { + environmentId: selectedProject.environmentId, + projectId: selectedProject.id, + }, + initialSelection, + ), }); - }, [activeDraftKey, flowKey, selectedProject, props.active, props.routeDraftId]); + }, [ + activeDraftKey, + flowKey, + selectedProject, + props.active, + props.routeDraftId, + awaitsRouteEntry, + initialSelection, + ]); const activePendingKey = props.active === false ? null @@ -567,10 +715,11 @@ export function NewTaskFlowProvider( const target = { environmentId: project.environmentId, projectId: project.id }; const current = readFlow().draftKey; if (current !== null && isNewTaskDraftKey(current)) { + // An existing draft keeps its intent: moving it never re-decides Auto or a pin. retargetNewTaskDraft(current, target, options); return current; } - return createNewTaskDraft(target); + return createNewTaskDraft(target, newDraftSelection(project, false)); }; const setProject = (project: EnvironmentProject) => { @@ -604,14 +753,22 @@ export function NewTaskFlowProvider( null, ); const latestSwitchRef = useRef(null); + // Picking a machine is an explicit pin for the draft that moves there. + const pinDraftToMachine = () => { + const draftKey = readFlow().draftKey; + if (draftKey !== null) + updateComposerDraftSettings(draftKey, { environmentSelection: "manual" }); + }; const switchEnvironment = async (environmentId: EnvironmentId): Promise => { if (environmentId === selectedEnvironmentId) { latestSwitchRef.current = null; setSwitchingToEnvironmentId(null); + pinDraftToMachine(); return true; } if (!isScratchDraft) { selectEnvironment(environmentId); + pinDraftToMachine(); return true; } const request = {}; @@ -760,6 +917,8 @@ export function NewTaskFlowProvider( } const workspaceSelection = resolveWorkspaceSelection(draft.workspaceSelection); const mode = workspaceSelection.mode; + // Placed by its origin: nothing local to this machine (its checkout or paths) goes along. + const placed = draftRoutesAutomatically({ draft, isScratch: isScratchDraft }); return { environmentId: selectedProject.environmentId, threadId: ThreadId.make(metadata.threadId), @@ -786,79 +945,28 @@ export function NewTaskFlowProvider( // Queued local tasks use drain-time checkout; snapshot branches only for immediate sends or explicit choices. branch: resolveProjectThreadCreationBranch({ workspaceMode: mode, - selectedBranch: workspaceSelection?.branch ?? null, - currentCheckoutBranch: options?.currentCheckoutBranch ?? null, + selectedBranch: placed && mode === "local" ? null : (workspaceSelection?.branch ?? null), + currentCheckoutBranch: placed ? null : (options?.currentCheckoutBranch ?? null), }), - worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null), + worktreePath: + mode === "worktree" || placed ? null : (workspaceSelection?.worktreePath ?? null), ...((workspaceSelection?.startFromOrigin ?? startFromOrigin) ? { startFromOrigin: true } : {}), }, + ...(placed + ? { + placement: { + originEnvironmentId: selectedProject.environmentId, + originProjectId: selectedProject.id, + candidateEnvironmentIds: environments.map((environment) => environment.environmentId), + }, + } + : {}), createdAt: metadata.createdAt, }; }; - const scratchEnvironments = connectedEnvironments.filter( - (environment) => - availableScratchWorkspaceRoot( - environment.connectionState, - serverConfigs.get(environment.environmentId), - ) !== null, - ); - - const selectedRepositoryKey = selectedProject?.repositoryIdentity - ? repositoryGroupingKeyOf(selectedProject.repositoryIdentity) - : null; - // Use || null: placeholder workspaceRoot can be empty, and an empty basename rejects real hosts. - const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null; - const selectedProjectTitle = selectedProject?.title ?? null; - const environments = (() => { - if (isScratchDraft) { - return scratchEnvironments.map((environment) => ({ - environmentId: environment.environmentId, - environmentLabel: environment.environmentLabel, - })); - } - const seen = new Set(); - const result: Array<{ - readonly environmentId: EnvironmentId; - readonly environmentLabel: string; - }> = []; - const hostsSelectedRepository = (project: EnvironmentProject) => { - if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) { - return true; - } - const projectKey = project.repositoryIdentity - ? repositoryGroupingKeyOf(project.repositoryIdentity) - : null; - if (selectedRepositoryKey !== null && projectKey !== null) { - return projectKey === selectedRepositoryKey; - } - return ( - project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename || - (selectedProjectTitle !== null && project.title === selectedProjectTitle) - ); - }; - for (const project of projects) { - if (!hostsSelectedRepository(project)) { - continue; - } - if (seen.has(project.environmentId)) { - continue; - } - const environment = savedConnectionsById[project.environmentId]; - if (!environment) { - continue; - } - seen.add(project.environmentId); - result.push({ - environmentId: project.environmentId, - environmentLabel: environment.environmentLabel, - }); - } - return result; - })(); - const value = { activeNewTask, projectScopes, @@ -900,6 +1008,20 @@ export function NewTaskFlowProvider( (routeDraftResolution.kind === "missing" || routeDraftResolution.kind === "pickProject") ? { draftId: props.routeDraftId, kind: routeDraftResolution.kind } : null, + environmentSelection: selectedProjectDraft.environmentSelection, + // Stored Auto stays Auto with fewer machines: its origin may still bind it, even to itself. + routesAutomatically: draftRoutesAutomatically({ + draft: selectedProjectDraft, + isScratch: isScratchDraft, + }), + canPlaceAutomatically: + !isScratchDraft && + (environments.length > 1 || selectedProjectDraft.environmentSelection === "auto"), + setEnvironmentSelection: (selection: "auto" | "manual") => { + if (selectedProjectDraftKey) { + updateComposerDraftSettings(selectedProjectDraftKey, { environmentSelection: selection }); + } + }, selectEnvironment, switchEnvironment, switchingToEnvironmentId, diff --git a/apps/mobile/src/features/threads/thread-route-state.test.ts b/apps/mobile/src/features/threads/thread-route-state.test.ts index 31b684bfaec3..d1ecdef6f3ac 100644 --- a/apps/mobile/src/features/threads/thread-route-state.test.ts +++ b/apps/mobile/src/features/threads/thread-route-state.test.ts @@ -1,4 +1,5 @@ import * as NodeModule from "node:module"; +import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { draftRouteIdentity, @@ -31,7 +32,13 @@ describe("draft thread handoff", () => { expect(isDraftThreadRoute(draft.routes.at(-1))).toBe(true); const submitted = router.getStateForAction( draft, - CommonActions.setParams(submittedThreadParams("environment", "thread")), + CommonActions.setParams( + submittedThreadParams({ + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread"), + messageId: MessageId.make("message"), + }), + ), options, )!; expect(submitted.routes.map((route) => route.key)).toEqual( diff --git a/apps/mobile/src/features/threads/thread-route-state.ts b/apps/mobile/src/features/threads/thread-route-state.ts index e237d9bf6993..800044e6a5ef 100644 --- a/apps/mobile/src/features/threads/thread-route-state.ts +++ b/apps/mobile/src/features/threads/thread-route-state.ts @@ -1,5 +1,12 @@ +import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; + export type NewTaskDraftRouteParams = { readonly requestId?: string; + /** + * Set by an entry scoped to one machine (a thread's own environment or branch): the new draft is + * pinned there from its creation. Generic project entries leave it unset. + */ + readonly environmentSelection?: "manual"; readonly environmentId?: string | string[]; readonly projectId?: string | string[]; readonly branch?: string | null; @@ -23,8 +30,67 @@ export function isDraftThreadRoute( ); } -export function submittedThreadParams(environmentId: string, threadId: string) { - return { draft: undefined, environmentId, threadId }; +/** + * The route of a queued new task, from Send or reopened later. A placed one also names its + * message: the machine it runs on is the one its origin binds, which the route follows. + */ +export function queuedTaskRouteParams( + message: Pick, +) { + return { + environmentId: String(message.environmentId), + threadId: String(message.threadId), + ...(message.placement ? { pendingMessageId: String(message.messageId) } : {}), + }; +} + +export function submittedThreadParams(message: Parameters[0]) { + return { draft: undefined, ...queuedTaskRouteParams(message) }; +} + +/** A new task in a thread's own environment, for its project there: pinned to that machine. */ +export function threadEnvironmentDraftParams( + project: { readonly environmentId: string; readonly id: string } | undefined, + requestId: string, +): NewTaskDraftRouteParams { + return project + ? { + requestId, + environmentId: String(project.environmentId), + projectId: String(project.id), + environmentSelection: "manual", + } + : { requestId }; +} + +/** A new task on a thread's branch, on that thread's machine. */ +export function threadBranchDraftParams( + thread: { + readonly environmentId: string; + readonly projectId: string; + readonly branch: string | null; + readonly worktreePath: string | null; + }, + requestId: string, +): NewTaskDraftRouteParams { + return { + requestId, + environmentId: String(thread.environmentId), + projectId: String(thread.projectId), + branch: thread.branch, + worktreePath: thread.worktreePath, + environmentSelection: "manual", + }; +} + +/** The machine an explicitly scoped draft route pins its new draft to, if it is one. */ +export function explicitDraftRouteEntry(draft: NewTaskDraftRouteParams | undefined) { + const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value); + const environmentId = first(draft?.environmentId); + const projectId = first(draft?.projectId); + return draft?.environmentSelection === "manual" && environmentId && projectId + ? { environmentId, projectId } + : undefined; } export function draftRouteIdentity(draft: NewTaskDraftRouteParams): string { diff --git a/apps/mobile/src/lib/composerAttachmentUploadQueue.ts b/apps/mobile/src/lib/composerAttachmentUploadQueue.ts index 0a28fff2231d..238174613d7c 100644 --- a/apps/mobile/src/lib/composerAttachmentUploadQueue.ts +++ b/apps/mobile/src/lib/composerAttachmentUploadQueue.ts @@ -1,4 +1,9 @@ -import { EnvironmentId, type ServerConfig } from "@t3tools/contracts"; +import { + EnvironmentId, + type CommandId, + type MessageId, + type ServerConfig, +} from "@t3tools/contracts"; import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments"; import { parseLegacyNewTaskDraftKey } from "../state/new-task-draft-key"; @@ -7,6 +12,11 @@ import type { DraftComposerAttachment } from "./composerImages"; export interface ComposerAttachmentUploadRequest { readonly environmentId: EnvironmentId; readonly attachment: DraftComposerAttachment; + /** A placed task's operation, which every attempt and retry of this upload is asked for. */ + readonly owner?: { + readonly messageId: MessageId; + readonly commandId: CommandId; + }; } export type ComposerAttachmentUploadState = diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts index 81a542a5aca1..56073b81809b 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.test.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts @@ -1,5 +1,12 @@ -import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; +import { + CommandId, + EnvironmentId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; type UploadOptions = { signal: AbortSignal; @@ -17,6 +24,13 @@ const native = vi.hoisted(() => ({ nextUuid: 0, mint: Symbol("mint"), remove: Symbol("remove"), + /** A placed task's origin, answering the queue's own admission request. */ + admit: Symbol("admit"), + admissions: [] as Array<{ environmentId: string; commandId: string; candidates: string[] }>, + admitAnswer: "bound" as "bound" | "excluded", + admitHold: null as null | Promise, + onAdmit: null as null | (() => void), + connection: new Map(), transfer: vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(), })); @@ -128,6 +142,26 @@ vi.mock("./session", async () => { }, }; }); +vi.mock("./orchestration", () => ({ + orchestrationEnvironment: { admitThreadPlacement: native.admit }, +})); +vi.mock("../connection/catalog", async () => { + const { Atom: A, AsyncResult: R } = await import("effect/reactivity"); + const generations = new Map(); + return { + environmentCatalog: { + stateAtom: (id: string) => { + if (!native.connection.has(id)) + native.connection.set(id, A.make(R.success({ phase: "connected" })).pipe(A.keepAlive)); + return native.connection.get(id); + }, + sessionGenerationAtom: (id: string) => { + if (!generations.has(id)) generations.set(id, A.make(1).pipe(A.keepAlive)); + return generations.get(id); + }, + }, + }; +}); vi.mock("./attachments", () => ({ attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove }, })); @@ -155,6 +189,39 @@ vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({ value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 }, }; } + if (command === native.admit) { + const { environmentId: origin, input } = target as unknown as { + environmentId: string; + input: { commandId: string; candidateEnvironmentIds: string[] }; + }; + native.admissions.push({ + environmentId: origin, + commandId: input.commandId, + candidates: [...input.candidateEnvironmentIds], + }); + native.onAdmit?.(); + if (native.admitHold) await native.admitHold; + const { AsyncResult: R } = await import("effect/reactivity"); + const CauseModule = await import("effect/Cause"); + const { OrchestrationV2ThreadPlacementAdmitError: Refusal } = + await import("@t3tools/contracts"); + return native.admitAnswer === "bound" + ? R.success({ + environmentId: "environment-1", + projectId: "project-b", + reason: "capacity", + resumed: true, + }) + : R.failure( + CauseModule.fail( + new Refusal({ + commandId: input.commandId as never, + reason: "excluded", + detail: "refused: excluded", + }), + ), + ); + } if (command === native.remove && target.input.attachmentId) { native.deleted.push(target.input.attachmentId); native.server.delete(target.input.attachmentId); @@ -181,7 +248,7 @@ import { composerAttachmentUploadKey, } from "../lib/composerAttachmentUploadQueue"; import type { DraftComposerAttachment } from "../lib/composerImages"; -import { Atom } from "effect/reactivity"; +import { AsyncResult, Atom } from "effect/reactivity"; import { appAtomRegistry } from "./atom-registry"; import { composerAttachmentUploadRequests, @@ -262,6 +329,16 @@ beforeEach(async () => { native.canOperate = true; native.nextId = 0; native.nextUuid = 0; + native.admissions.length = 0; + native.admitAnswer = "bound"; + native.admitHold = null; + native.onAdmit = null; + for (const atom of native.connection.values()) { + appAtomRegistry.set( + atom as Atom.Writable, + AsyncResult.success({ phase: "connected" }), + ); + } native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}')); drafts.resetComposerDraftsLoadState(); appAtomRegistry.set(drafts.composerDraftsAtom, { @@ -407,3 +484,117 @@ it("does not upload a disconnected colon environment's draft to its connected pr }); expect(requests).toEqual([]); }); + +describe("a placed task's uploads", () => { + const origin = EnvironmentId.make("environment-origin"); + /** A new task placed by `origin` on environment-1, bound already unless `unbound`. */ + function placedTask(options: { readonly unbound?: boolean; readonly commandId?: string } = {}) { + return { + ...queuedMessage(), + attachments: [image], + commandId: CommandId.make(options.commandId ?? "command-placed"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + creation: { + projectId: ProjectId.make("project-b"), + workspaceMode: "worktree" as const, + branch: "main", + worktreePath: null, + }, + placement: { + originEnvironmentId: origin, + originProjectId: ProjectId.make("project-a"), + candidateEnvironmentIds: [origin, environmentId], + ...(options.unbound + ? {} + : { bound: { environmentId, projectId: ProjectId.make("project-b") } }), + }, + } satisfies QueuedThreadMessage; + } + + it("holds an Auto draft's bytes, while the same draft pinned to its machine uploads", async () => { + const autoKey = drafts.createNewTaskDraft( + { environmentId, projectId: ProjectId.make("project-a") }, + "auto", + ); + appAtomRegistry.set(drafts.composerDraftsAtom, { + [autoKey]: { ...drafts.getComposerDraftSnapshot(autoKey), attachments: [image] }, + }); + await worker().settled(); + expect(native.nextId).toBe(0); + expect(uploadState()).toBeUndefined(); + disposeWorker?.(); + drafts.updateComposerDraftSettings(autoKey, { environmentSelection: "manual" }); + await worker().settled(); + expect(native.nextId).toBe(1); + }); + + it("mints nothing for a placed task its origin has not bound", async () => { + appAtomRegistry.set(drafts.composerDraftsAtom, {}); + await enqueueThreadOutboxMessage(placedTask({ unbound: true })); + await worker().settled(); + expect(native.admissions).toEqual([]); + expect(native.nextId).toBe(0); + }); + + it("uploads a bound task's bytes only after its origin answers with the same binding", async () => { + appAtomRegistry.set(drafts.composerDraftsAtom, {}); + await enqueueThreadOutboxMessage(placedTask()); + await worker().settled(); + expect(native.admissions).toEqual([ + { environmentId: origin, commandId: "command-placed", candidates: [environmentId] }, + ]); + expect(native.nextId).toBe(1); + expect(native.transfer).toHaveBeenCalledTimes(1); + }); + + it("refuses a queued upload whose owner was replaced before its callback ran", async () => { + appAtomRegistry.set(drafts.composerDraftsAtom, {}); + await enqueueThreadOutboxMessage(placedTask()); + const queue = worker(); + // The same message under another operation, before the queue's callback runs. + void enqueueThreadOutboxMessage(placedTask({ commandId: "command-replacement" })); + await queue.settled(); + // The replaced job never asks for, or uploads as, the operation it was queued for. + expect(native.admissions.every(({ commandId }) => commandId === "command-replacement")).toBe( + true, + ); + expect(native.nextId).toBeLessThanOrEqual(native.admissions.length); + }); + + it.each([ + "the origin refuses", + "the origin's connection drops", + "the same bytes are attached again", + "the task is removed", + ] as const)("mints and transfers nothing when %s while its origin is asked", async (change) => { + appAtomRegistry.set(drafts.composerDraftsAtom, {}); + const message = placedTask(); + await enqueueThreadOutboxMessage(message); + let release!: () => void; + native.admitHold = new Promise((done) => { + release = done; + }); + const reached = Promise.withResolvers(); + native.onAdmit = reached.resolve; + const queue = worker(); + await reached.promise; + if (change === "the origin refuses") native.admitAnswer = "excluded"; + if (change === "the origin's connection drops") + appAtomRegistry.set( + native.connection.get(origin) as Atom.Writable, + AsyncResult.success({ phase: "disconnected" }), + ); + if (change === "the same bytes are attached again") + await threadOutboxManager.update( + { ...message, attachments: [{ ...image }] }, + threadOutboxManager.revisionOf(message.messageId), + ); + if (change === "the task is removed") await threadOutboxManager.remove(message); + release(); + await queue.settled(); + expect(native.nextId).toBe(0); + expect(native.transfer).not.toHaveBeenCalled(); + // Held for the task's own delivery, which asks again: not shown as a failed upload. + expect(uploadState()?.status).not.toBe("failed"); + }); +}); diff --git a/apps/mobile/src/state/composer-attachment-uploads.ts b/apps/mobile/src/state/composer-attachment-uploads.ts index 8e2921c5f62d..d77f062bfd33 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.ts @@ -20,6 +20,7 @@ import { appAtomRegistry } from "./atom-registry"; import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states"; import { environmentServerConfigsAtom } from "./server"; import { + awaitsPlacement, flattenQueuedThreadMessages, threadOutboxManager, threadOutboxRevision, @@ -27,6 +28,7 @@ import { type QueuedThreadMessage, } from "./thread-outbox"; import { editingQueuedMessageIdsAtom } from "./use-thread-outbox"; +import { qualifyPlacedUpload, type PlacedUploadOwner } from "./thread-placement"; import { ComposerDraftPersistenceError, type ComposerDraft, @@ -69,10 +71,23 @@ export function retryComposerAttachmentUpload(environmentId: EnvironmentId, atta type ComposerAttachmentUploadRequest = { readonly environmentId: EnvironmentId; readonly attachment: DraftComposerAttachment; + readonly owner?: PlacedUploadOwner; }; +/** A placed task uploads only once bound, and then only as its own operation. */ +const placedOwner = ( + message: QueuedThreadMessage | undefined, +): { readonly held: boolean; readonly owner?: PlacedUploadOwner } => + message?.placement === undefined + ? { held: false } + : awaitsPlacement(message) + ? { held: true } + : { held: false, owner: { messageId: message.messageId, commandId: message.commandId } }; + export function composerAttachmentUploadRequests(input: { - readonly drafts: Readonly>>; + readonly drafts: Readonly< + Record> + >; readonly queuedMessagesByThreadKey: Parameters[0]; /** An edited message's attachments upload through its editor draft. */ readonly editingQueuedMessageIds: Readonly>; @@ -86,9 +101,13 @@ export function composerAttachmentUploadRequests(input: { >; }): ReadonlyArray { const queued = flattenQueuedThreadMessages(input.queuedMessagesByThreadKey); + const queuedById = new Map( + queued.map((message) => [`pending-task:${message.messageId}`, message]), + ); const uploadable = ( environmentId: EnvironmentId | null, attachments: ReadonlyArray, + owner?: PlacedUploadOwner, ): ReadonlyArray => environmentId === null || !input.connectedEnvironmentIds.has(environmentId) || @@ -98,26 +117,35 @@ export function composerAttachmentUploadRequests(input: { .filter((attachment) => canUploadComposerAttachment(attachment, input.serverConfigs.get(environmentId)), ) - .map((attachment) => ({ environmentId, attachment })); + .map((attachment) => + owner ? { environmentId, attachment, owner } : { environmentId, attachment }, + ); return [ - ...Object.entries(input.drafts).flatMap(([key, draft]) => - uploadable( + ...Object.entries(input.drafts).flatMap(([key, draft]) => { + // An Auto draft's bytes stay here until its origin places it: they never pin it. + if (draft.environmentSelection === "auto") return []; + const placed = placedOwner(queuedById.get(key)); + if (placed.held) return []; + return uploadable( composerDraftEnvironmentId(key, input.knownEnvironmentIds, queued, draft), draft.attachments, - ), - ), + placed.owner, + ); + }), // Sending mid-upload hands the attachment to the outbox; requesting it here keeps that // upload running instead of aborting it for the outbox to start over. - ...queued.flatMap((message) => - input.editingQueuedMessageIds[message.messageId] + ...queued.flatMap((message) => { + const placed = placedOwner(message); + return input.editingQueuedMessageIds[message.messageId] || placed.held ? [] : uploadable( message.environmentId, message.attachments.filter( (attachment) => attachment.uploadedAttachmentId === undefined, ), - ), - ), + placed.owner, + ); + }), ]; } @@ -205,7 +233,13 @@ export function createComposerAttachmentUploadWorker( ensureComposerDraftsLoaded(); const queue = createComposerAttachmentUploadQueue({ onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states), - upload: async ({ environmentId, attachment }, signal, onProgress) => { + upload: async ({ environmentId, attachment, owner }, signal, onProgress) => { + // Qualified at this callback, not when requested: the owner may have changed since. + if (owner !== undefined) { + const qualification = await qualifyPlacedUpload({ owner, environmentId, attachment }); + // Not a failed upload: the task's own delivery asks again before anything goes to B. + if (!qualification.ok || signal.aborted) return false; + } const release = isFileBackedComposerAttachment(attachment) ? retainComposerAttachmentFileForPreview(attachment) : undefined; diff --git a/apps/mobile/src/state/pending-thread-creation.ts b/apps/mobile/src/state/pending-thread-creation.ts index 78c682ec7a2d..319d88820d5e 100644 --- a/apps/mobile/src/state/pending-thread-creation.ts +++ b/apps/mobile/src/state/pending-thread-creation.ts @@ -52,6 +52,44 @@ export function selectThreadCreationDetail(input: { return { pendingCreation, detailRef }; } +/** + * The thread a route that names a pending task's message shows: wherever that message is queued + * or its outcome recorded now. Resolved before any scoped key or detail read, so a task its origin + * placed on another machine is never read, or found missing, on the machine it was sent from. + */ +export function resolvePendingRouteThreadRef< + Ref extends { readonly environmentId: string }, +>(input: { + readonly routeRef: Ref | null; + readonly pendingMessageId: string | null; + readonly queuedMessagesByThreadKey: Readonly< + Record | undefined> + >; + readonly outcomes: Readonly>; +}): + | { + readonly environmentId: QueuedThreadMessage["environmentId"]; + readonly threadId: QueuedThreadMessage["threadId"]; + } + | Ref + | null { + if (input.pendingMessageId === null) return input.routeRef; + const owned = (message: QueuedThreadMessage) => message.messageId === input.pendingMessageId; + const message = + Object.values(input.queuedMessagesByThreadKey) + .flatMap((queue) => queue ?? []) + .find(owned) ?? + Object.values(input.outcomes) + .map((outcome) => outcome?.message) + .find( + (candidate): candidate is QueuedThreadMessage => + candidate !== undefined && owned(candidate), + ); + return message === undefined + ? input.routeRef + : { environmentId: message.environmentId, threadId: message.threadId }; +} + export function resolvePendingThreadCreation(input: { readonly threadKey: string | null; readonly pending: PendingThreadCreation | null; diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index 64fe62d8a15f..b1a125e7e785 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -69,6 +69,27 @@ export const QueuedThreadMessageSchema = Schema.Struct({ const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema); const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema); +const QueuedThreadPlacementSchema = Schema.Struct({ + originEnvironmentId: EnvironmentId, + originProjectId: ProjectId, + candidateEnvironmentIds: Schema.Array(EnvironmentId), + bound: Schema.optional(Schema.Struct({ environmentId: EnvironmentId, projectId: ProjectId })), +}); + +/** + * A new task whose machine its origin chooses. Its own envelope, not a flat record with one more + * field: a reader without it must keep the file unread rather than send it as fixed work there. + */ +export const PlacedQueuedThreadMessageSchema = Schema.Struct({ + schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION), + kind: Schema.Literal("placed-creation"), + placement: QueuedThreadPlacementSchema, + message: QueuedThreadMessageSchema, +}); + +const decodePlacedQueuedThreadMessage = Schema.decodeUnknownSync(PlacedQueuedThreadMessageSchema); +const encodePlacedQueuedThreadMessage = Schema.encodeUnknownSync(PlacedQueuedThreadMessageSchema); + export interface QueuedThreadCreation { readonly projectId: ProjectIdType; readonly projectTitle?: string; @@ -80,6 +101,17 @@ export interface QueuedThreadCreation { readonly pullRequestReference?: string; } +/** Where a new task's origin admits it; delivery fields follow `bound` once the origin answers. */ +export interface QueuedThreadPlacement { + /** The machine and project the task was sent from, which admits it each time; never changes. */ + readonly originEnvironmentId: EnvironmentId; + readonly originProjectId: ProjectIdType; + /** Machines hosting the project when it was sent; admission offers the operable ones. */ + readonly candidateEnvironmentIds: ReadonlyArray; + /** The machine and project the origin bound the launch to. */ + readonly bound?: { readonly environmentId: EnvironmentId; readonly projectId: ProjectIdType }; +} + export interface QueuedThreadMessage { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; @@ -98,6 +130,8 @@ export interface QueuedThreadMessage { /** Starts a new provider session (`/clear`). */ readonly freshContext?: boolean; readonly creation?: QueuedThreadCreation; + /** Set on new tasks placed automatically; their creation is admitted at the origin first. */ + readonly placement?: QueuedThreadPlacement; readonly createdAt: string; } @@ -152,17 +186,40 @@ export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelec } export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown { - return encodeStoredQueuedThreadMessage({ + const { placement, ...flat } = message; + const stored = { schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION, ...flat } as const; + if (placement === undefined) return encodeStoredQueuedThreadMessage(stored); + if (message.creation === undefined) { + throw new Error("Only a new task's creation can be placed by its origin."); + } + return encodePlacedQueuedThreadMessage({ schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION, - ...message, + kind: "placed-creation", + placement, + message: stored, }); } +const isPlacedEnvelope = (value: unknown): boolean => + typeof value === "object" && value !== null && "kind" in value; + export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage { + if (isPlacedEnvelope(value)) { + const { placement, message: stored } = decodePlacedQueuedThreadMessage(value); + const { schemaVersion: _, ...message } = stored; + if (message.creation === undefined) { + throw new Error("A placed record must hold a new task's creation."); + } + return { ...message, placement }; + } const { schemaVersion: _, ...message } = decodeStoredQueuedThreadMessage(value); return message; } +/** Whether this placed task still waits for its origin to bind it to a machine. */ +export const awaitsPlacement = (message: QueuedThreadMessage): boolean => + message.placement !== undefined && message.placement.bound === undefined; + export function groupQueuedThreadMessages( messages: ReadonlyArray, ): Record> { diff --git a/apps/mobile/src/state/thread-placement-rule.ts b/apps/mobile/src/state/thread-placement-rule.ts new file mode 100644 index 000000000000..2587756e17af --- /dev/null +++ b/apps/mobile/src/state/thread-placement-rule.ts @@ -0,0 +1,31 @@ +import type { ComposerDraft } from "./use-composer-drafts"; + +/** Context that only its own machine can resolve keeps a task there. */ +const MACHINE_LOCAL_CONTEXT_KINDS = new Set(["thread", "terminal", "environment"]); + +/** + * Whether a new task's draft is placed by its origin rather than run on the draft's machine. Only + * a stored `auto` intent opts in; real locality (a chosen local checkout or existing worktree, a PR + * checkout, machine-local context, a scratch folder) keeps it where it is. Attachments never decide. + */ +export function draftRoutesAutomatically(input: { + readonly draft: Pick; + readonly isScratch: boolean; +}): boolean { + const { draft } = input; + const selection = draft.workspaceSelection; + return ( + draft.environmentSelection === "auto" && + !input.isScratch && + selection?.mode !== "local" && + !selection?.worktreePath && + selection?.pullRequestReference === undefined && + !(draft.context?.records ?? []).some((record) => MACHINE_LOCAL_CONTEXT_KINDS.has(record.kind)) + ); +} + +/** A genuinely new draft starts as Auto only when more than one machine could take it now. */ +export const seedsAutomaticPlacement = (input: { + readonly isScratch: boolean; + readonly candidateCount: number; +}): boolean => !input.isScratch && input.candidateCount > 1; diff --git a/apps/mobile/src/state/thread-placement.model.test.ts b/apps/mobile/src/state/thread-placement.model.test.ts new file mode 100644 index 000000000000..d497f9977c03 --- /dev/null +++ b/apps/mobile/src/state/thread-placement.model.test.ts @@ -0,0 +1,224 @@ +import { + CommandId, + EnvironmentId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { submittedThreadParams } from "../features/threads/thread-route-state"; +import { resolvePendingRouteThreadRef } from "./pending-thread-creation"; +import { + awaitsPlacement, + decodeQueuedThreadMessage, + encodeQueuedThreadMessage, + QueuedThreadMessageSchema, + type QueuedThreadMessage, +} from "./thread-outbox-model"; +import { draftRoutesAutomatically, seedsAutomaticPlacement } from "./thread-placement-rule"; + +// The flat schema is the v1-v4 reader older builds decode each outbox file with. +const decodeAsOlderBuild = Schema.decodeUnknownSync(QueuedThreadMessageSchema); +const laptop = EnvironmentId.make("laptop"); +const box = EnvironmentId.make("box"); +const fixed: QueuedThreadMessage = { + environmentId: laptop, + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("message-1"), + commandId: CommandId.make("command-1"), + text: "Fix the build", + attachments: [], + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + creation: { + projectId: ProjectId.make("project-a"), + workspaceMode: "worktree", + branch: "main", + worktreePath: null, + }, + createdAt: "2026-11-18T16:00:00.000Z", +}; +const placed: QueuedThreadMessage = { + ...fixed, + placement: { + originEnvironmentId: laptop, + originProjectId: ProjectId.make("project-a"), + candidateEnvironmentIds: [laptop, box], + }, +}; + +describe("a placed task's stored envelope", () => { + it("round-trips, unbound and bound, through this reader", () => { + expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(placed))).toEqual(placed); + const bound: QueuedThreadMessage = { + ...placed, + environmentId: box, + placement: { + ...placed.placement!, + bound: { environmentId: box, projectId: ProjectId.make("project-b") }, + }, + }; + expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(bound))).toEqual(bound); + expect(awaitsPlacement(placed)).toBe(true); + expect(awaitsPlacement(bound)).toBe(false); + expect(awaitsPlacement(fixed)).toBe(false); + }); + + it("is refused by the flat reader every older build has, never read as fixed work", () => { + expect(() => decodeAsOlderBuild(encodeQueuedThreadMessage(placed))).toThrow(); + }); + + it("keeps legacy writes flat at version 3 and reads versions 1 to 4", () => { + expect(encodeQueuedThreadMessage(fixed)).toMatchObject({ + schemaVersion: 3, + environmentId: "laptop", + }); + for (const schemaVersion of [1, 2, 3, 4]) { + expect(decodeQueuedThreadMessage({ ...fixed, schemaVersion })).toEqual(fixed); + } + }); + + it("only ever holds a new task's creation", () => { + const { creation: _creation, ...turn } = placed; + expect(() => encodeQueuedThreadMessage(turn)).toThrow(); + const envelope = encodeQueuedThreadMessage(placed) as { message: Record }; + const { creation: _stored, ...withoutCreation } = envelope.message; + expect(() => decodeQueuedThreadMessage({ ...envelope, message: withoutCreation })).toThrow(); + }); +}); + +describe("a new task draft's Auto routing", () => { + const auto = { environmentSelection: "auto" as const }; + it.each([ + ["Auto with no locality", auto, false, true], + ["a machine pick", { environmentSelection: "manual" as const }, false, false], + ["a draft from before the choice", {}, false, false], + ["a scratch folder", auto, true, false], + [ + "a chosen local checkout", + { + ...auto, + workspaceSelection: { mode: "local" as const, branch: "main", worktreePath: null }, + }, + false, + false, + ], + [ + "an existing worktree", + { + ...auto, + workspaceSelection: { mode: "worktree" as const, branch: "b", worktreePath: "/w" }, + }, + false, + false, + ], + [ + "a PR checkout", + { + ...auto, + workspaceSelection: { + mode: "worktree" as const, + branch: null, + worktreePath: null, + pullRequestReference: "https://example.test/pull/1", + }, + }, + false, + false, + ], + [ + "a new worktree from a chosen base branch", + { + ...auto, + workspaceSelection: { mode: "worktree" as const, branch: "main", worktreePath: null }, + }, + false, + true, + ], + ])("routes %s automatically: %s", (_name, draft, isScratch, expected) => { + expect(draftRoutesAutomatically({ draft, isScratch })).toBe(expected); + }); + + it("keeps a draft whose context names another thread on its machine", () => { + expect( + draftRoutesAutomatically({ + draft: { + ...auto, + context: { version: 1, records: [{ kind: "thread" } as never] }, + }, + isScratch: false, + }), + ).toBe(false); + }); + + it("starts a genuinely new draft as Auto only when more than one machine could take it", () => { + expect(seedsAutomaticPlacement({ isScratch: false, candidateCount: 2 })).toBe(true); + expect(seedsAutomaticPlacement({ isScratch: false, candidateCount: 1 })).toBe(false); + expect(seedsAutomaticPlacement({ isScratch: true, candidateCount: 3 })).toBe(false); + }); +}); + +describe("a submitted placed task's route", () => { + const queuedAt = (message: QueuedThreadMessage) => ({ + [`${message.environmentId}:${message.threadId}`]: [message], + }); + const routeRef = { environmentId: "laptop", threadId: "thread-1" }; + + it("carries its message id", () => { + expect(submittedThreadParams(placed)).toEqual({ + draft: undefined, + environmentId: "laptop", + threadId: "thread-1", + pendingMessageId: "message-1", + }); + // A fixed task's route is unchanged: environment and thread only. + expect(submittedThreadParams(fixed)).toEqual({ + draft: undefined, + environmentId: "laptop", + threadId: "thread-1", + }); + }); + + it("follows the message to the machine its origin bound, before any detail read", () => { + const bound = { ...placed, environmentId: box }; + expect( + resolvePendingRouteThreadRef({ + routeRef, + pendingMessageId: "message-1", + queuedMessagesByThreadKey: queuedAt(bound), + outcomes: {}, + }), + ).toEqual({ environmentId: box, threadId: "thread-1" }); + // Delivered: the outcome, recorded under B, still names B. + expect( + resolvePendingRouteThreadRef({ + routeRef, + pendingMessageId: "message-1", + queuedMessagesByThreadKey: {}, + outcomes: { "box:thread-1": { kind: "delivered", message: bound } }, + }), + ).toEqual({ environmentId: box, threadId: "thread-1" }); + }); + + it("is not moved by another task's binding or outcome", () => { + const other = { ...placed, messageId: MessageId.make("message-other"), environmentId: box }; + expect( + resolvePendingRouteThreadRef({ + routeRef, + pendingMessageId: "message-1", + queuedMessagesByThreadKey: queuedAt(other), + outcomes: { "box:thread-1": { kind: "delivered", message: other } }, + }), + ).toBe(routeRef); + expect( + resolvePendingRouteThreadRef({ + routeRef, + pendingMessageId: null, + queuedMessagesByThreadKey: queuedAt({ ...placed, environmentId: box }), + outcomes: {}, + }), + ).toBe(routeRef); + }); +}); diff --git a/apps/mobile/src/state/thread-placement.ts b/apps/mobile/src/state/thread-placement.ts new file mode 100644 index 000000000000..e95e653466e6 --- /dev/null +++ b/apps/mobile/src/state/thread-placement.ts @@ -0,0 +1,388 @@ +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + AuthOrchestrationOperateScope, + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + managedRuntimeModeDenial, + OrchestrationV2ThreadPlacementAdmitError, + type EnvironmentId, + type OrchestrationMessageContext, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { AsyncResult } from "effect/reactivity"; + +import { isModelSelectionUnavailable } from "../lib/modelOptions"; +import { scopedThreadKey } from "../lib/scopedEntities"; +import type { DraftComposerAttachment } from "../lib/composerImages"; +import { appAtomRegistry } from "./atom-registry"; +import { pendingThreadCreationOutcomesAtom } from "./pending-thread-creation"; +import { environmentProjects } from "./projects"; +import { readEnvironmentScope } from "./session"; +import { serverEnvironment } from "./server"; +import { + confirmThreadOutboxMessageQueued, + flattenQueuedThreadMessages, + threadOutboxManager, + threadOutboxRevision, + updateThreadOutboxMessage, + type QueuedThreadMessage, +} from "./thread-outbox"; +import { composerDraftsAtom } from "./use-composer-drafts"; +import { editingQueuedMessageIdsAtom } from "./use-thread-outbox"; + +type Catalog = (typeof import("../connection/catalog"))["environmentCatalog"]; + +// Loaded only for placed tasks: other sends never need the connection runtime or admission. +async function loadSessions() { + const { environmentCatalog } = await import("../connection/catalog"); + return sessionsOf(environmentCatalog); +} + +function sessionsOf(catalog: Catalog) { + const connectedPhase = (environmentId: EnvironmentId): boolean => + Option.exists( + AsyncResult.value(appAtomRegistry.get(catalog.stateAtom(environmentId))), + (state) => state.phase === "connected", + ); + const sessionGeneration = (environmentId: EnvironmentId): number => + appAtomRegistry.get(catalog.sessionGenerationAtom(environmentId)); + const operable = (environmentId: EnvironmentId): boolean => + connectedPhase(environmentId) && + readEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + return { + operable, + /** Whether these machines stay connected, on the same established sessions, until `settle`. */ + watch: (environmentIds: ReadonlyArray) => + watchSessions(catalog, environmentIds, connectedPhase, sessionGeneration, operable), + }; +} + +function watchSessions( + catalog: Catalog, + environmentIds: ReadonlyArray, + connectedPhase: (environmentId: EnvironmentId) => boolean, + sessionGeneration: (environmentId: EnvironmentId) => number, + operable: (environmentId: EnvironmentId) => boolean, +) { + const generations = environmentIds.map(sessionGeneration); + let held = environmentIds.every(connectedPhase); + const stops = environmentIds.map((environmentId) => + appAtomRegistry.subscribe(catalog.stateAtom(environmentId), () => { + if (!connectedPhase(environmentId)) held = false; + }), + ); + return () => { + for (const stop of stops) stop(); + return ( + held && + environmentIds.every( + (environmentId, index) => + operable(environmentId) && sessionGeneration(environmentId) === generations[index], + ) + ); + }; +} + +const currentMessage = (messageId: QueuedThreadMessage["messageId"]) => + flattenQueuedThreadMessages( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ).find((candidate) => candidate.messageId === messageId); + +const editing = (messageId: QueuedThreadMessage["messageId"]): boolean => + appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId] === true; + +/** Candidates the origin may choose from now: operable here, and able to run this request. */ +function currentPlacementCandidates( + message: QueuedThreadMessage, + operable: (environmentId: EnvironmentId) => boolean, +): Array { + const placement = message.placement; + if (placement === undefined || message.modelSelection === undefined) return []; + return placement.candidateEnvironmentIds.filter((environmentId) => { + if (!operable(environmentId)) return false; + const config = appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId)); + return ( + config !== null && + !isModelSelectionUnavailable(config, message.modelSelection, null) && + managedRuntimeModeDenial( + config.managedPolicy, + message.runtimeMode ?? DEFAULT_RUNTIME_MODE, + ) === undefined + ); + }); +} + +type AdmissionAnswer = + | { readonly kind: "bound"; readonly environmentId: EnvironmentId; readonly projectId: string } + | { readonly kind: "refused"; readonly reason: string; readonly nothingBound: boolean } + | { readonly kind: "uncertain" }; + +const isAdmitRefusal = Schema.is(OrchestrationV2ThreadPlacementAdmitError); + +async function askOrigin( + message: QueuedThreadMessage, + candidateEnvironmentIds: ReadonlyArray, +): Promise { + const placement = message.placement!; + const { orchestrationEnvironment } = await import("./orchestration"); + const answer = await runAtomCommand( + appAtomRegistry, + orchestrationEnvironment.admitThreadPlacement, + { + environmentId: placement.originEnvironmentId, + input: { + commandId: message.commandId, + threadId: message.threadId, + projectId: placement.originProjectId, + modelSelection: message.modelSelection!, + runtimeMode: message.runtimeMode ?? DEFAULT_RUNTIME_MODE, + interactionMode: message.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE, + candidateEnvironmentIds, + }, + }, + { reportFailure: false }, + ); + if (AsyncResult.isSuccess(answer)) { + return { + kind: "bound", + environmentId: answer.value.environmentId, + projectId: answer.value.projectId, + }; + } + if (!AsyncResult.isFailure(answer)) return { kind: "uncertain" }; + const error = squashAtomCommandFailure(answer); + if (isAdmitRefusal(error)) { + return { + kind: "refused", + reason: error.detail, + nothingBound: error.reason === "no-eligible-environment", + }; + } + return { kind: "uncertain" }; +} + +/** The bound message: delivery and presentation follow B; the origin stays admission metadata. */ +function boundMessage( + message: QueuedThreadMessage, + bound: { readonly environmentId: EnvironmentId; readonly projectId: string }, +): QueuedThreadMessage { + const creation = message.creation!; + const project = appAtomRegistry + .get(environmentProjects.projectsAtom) + .find( + (candidate) => + candidate.environmentId === bound.environmentId && candidate.id === bound.projectId, + ); + const { projectCwd: _originCwd, ...ordinary } = creation; + return { + ...message, + environmentId: bound.environmentId, + creation: { + ...ordinary, + projectId: project?.id ?? (bound.projectId as typeof creation.projectId), + ...(project?.title !== undefined ? { projectTitle: project.title } : {}), + // Only B's own root: the origin's path means nothing there. + ...(project?.workspaceRoot ? { projectCwd: project.workspaceRoot } : {}), + }, + // An upload stamped for another machine is not one B can use. + attachments: message.attachments.map((attachment) => + attachment.uploadEnvironmentId !== undefined && + attachment.uploadEnvironmentId !== bound.environmentId + ? (({ uploadedAttachmentId: _id, uploadEnvironmentId: _env, ...rest }) => rest)(attachment) + : attachment, + ), + placement: { + ...message.placement!, + bound: { + environmentId: bound.environmentId, + projectId: project?.id ?? (bound.projectId as typeof creation.projectId), + }, + }, + }; +} + +/** A creation outcome recorded under the origin key moves only if it is this message's. */ +function rekeyOutcome(before: QueuedThreadMessage, after: QueuedThreadMessage): void { + const from = scopedThreadKey(before.environmentId, before.threadId); + const to = scopedThreadKey(after.environmentId, after.threadId); + if (from === to) return; + const outcomes = appAtomRegistry.get(pendingThreadCreationOutcomesAtom); + const outcome = outcomes[from]; + if (outcome === undefined || outcome.message.messageId !== before.messageId) return; + const next = { ...outcomes, [to]: { ...outcome, message: after } }; + delete next[from]; + appAtomRegistry.set(pendingThreadCreationOutcomesAtom, next); +} + +export type PlacementStep = + /** Bound and persisted, abandoned to a newer owner, or not ready: the next pass decides. */ + | { readonly step: "done" } + /** Held with the same origin and IDs; try again after backoff. */ + | { readonly step: "hold" } + /** The origin bound nothing and offers no machine: hand the task back to its draft. */ + | { readonly step: "restore"; readonly reason: string }; + +/** + * Admits a queued Auto creation at its recorded origin, then rebinds the same message to the + * machine it answered with. Nothing is uploaded or prepared before that binding is durable. + */ +export async function admitPlacedCreation(message: QueuedThreadMessage): Promise { + const placement = message.placement; + if (placement === undefined || placement.bound !== undefined) return { step: "done" }; + // A record whose write failed never reaches its origin. + if (!(await confirmThreadOutboxMessageQueued(message)) || editing(message.messageId)) { + return { step: "done" }; + } + const revision = threadOutboxRevision(message.messageId); + const origin = placement.originEnvironmentId; + const sessions = await loadSessions(); + if (!sessions.operable(origin)) return { step: "hold" }; + const candidates = currentPlacementCandidates(message, sessions.operable); + if (candidates.length === 0) return { step: "hold" }; + const sessionsHeld = sessions.watch([origin]); + let originStayed = false; + let answer: AdmissionAnswer; + try { + answer = await askOrigin(message, candidates); + } finally { + originStayed = sessionsHeld(); + } + const stillOwned = () => + !editing(message.messageId) && + threadOutboxRevision(message.messageId) === revision && + currentMessage(message.messageId) === message; + if (answer.kind === "uncertain") return { step: "hold" }; + if (answer.kind === "refused") { + if (!answer.nothingBound) return { step: "hold" }; + return stillOwned() ? { step: "restore", reason: answer.reason } : { step: "done" }; + } + // An answer over a session that changed, or for a message edited meanwhile, is not acted on. + if (!originStayed || !stillOwned()) return { step: "done" }; + const bound = boundMessage(message, answer); + if (!(await updateThreadOutboxMessage(bound, revision))) return { step: "done" }; + rekeyOutcome(message, bound); + return { step: "done" }; +} + +export type PlacedTargetQualification = + | { readonly ok: true } + | { readonly ok: false; readonly reason: string }; + +/** + * Whether a bound placed task may act on its machine now: upload, verify a stored upload, prepare + * or launch there. Asked of its origin again each time, for the same command and binding; a stored + * binding is identity to reconcile, not a standing grant. `stillOwned` checks the caller's owner. + */ +export async function qualifyPlacedTarget(input: { + readonly messageId: QueuedThreadMessage["messageId"]; + readonly commandId: QueuedThreadMessage["commandId"]; + readonly environmentId: EnvironmentId; + readonly stillOwned: () => boolean; +}): Promise { + const message = currentMessage(input.messageId); + const bound = message?.placement?.bound; + if ( + message === undefined || + bound === undefined || + message.commandId !== input.commandId || + bound.environmentId !== input.environmentId + ) { + return { + ok: false, + reason: "This upload belonged to a placed task that no longer holds it.", + }; + } + const origin = message.placement!.originEnvironmentId; + const sessions = await loadSessions(); + if ( + !sessions.operable(origin) || + !sessions.operable(bound.environmentId) || + !input.stillOwned() + ) { + return { ok: false, reason: "Waiting for this task's machines to connect." }; + } + const sessionsHeld = sessions.watch([origin, bound.environmentId]); + let sessionsStayed = false; + let answer: AdmissionAnswer; + try { + answer = await askOrigin(message, [bound.environmentId]); + } finally { + sessionsStayed = sessionsHeld(); + } + if (answer.kind !== "bound") { + return { + ok: false, + reason: + answer.kind === "refused" ? answer.reason : "This task's placement could not be confirmed.", + }; + } + if (answer.environmentId !== bound.environmentId || answer.projectId !== bound.projectId) { + return { ok: false, reason: "This task's origin answered with another machine." }; + } + const now = currentMessage(input.messageId); + if ( + !sessionsStayed || + now?.commandId !== input.commandId || + JSON.stringify(now.placement) !== JSON.stringify(message.placement) || + !input.stillOwned() + ) { + return { ok: false, reason: "This task changed while its placement was confirmed." }; + } + return { ok: true }; +} + +/** The upload owner a queued placed task's attachment carries through the queue and retries. */ +export interface PlacedUploadOwner { + readonly messageId: QueuedThreadMessage["messageId"]; + readonly commandId: QueuedThreadMessage["commandId"]; +} + +/** The current owner record of this attachment: the queued message, or its pending-task editor. */ +function ownedAttachment( + owner: PlacedUploadOwner, + attachmentId: string, +): { + readonly attachment: DraftComposerAttachment; + readonly text: string; + readonly context: OrchestrationMessageContext | undefined; +} | null { + const message = currentMessage(owner.messageId); + if (message === undefined || message.commandId !== owner.commandId) return null; + if (editing(owner.messageId)) { + const editor = appAtomRegistry.get(composerDraftsAtom)[`pending-task:${owner.messageId}`]; + const attachment = editor?.attachments.find((candidate) => candidate.id === attachmentId); + return attachment && editor ? { attachment, text: editor.text, context: editor.context } : null; + } + const attachment = message.attachments.find((candidate) => candidate.id === attachmentId); + return attachment ? { attachment, text: message.text, context: message.context } : null; +} + +/** + * Qualifies one queued upload for a placed task at its actual callback: the same attachment object + * and content must still belong to the same operation before and after its origin answers. + */ +export async function qualifyPlacedUpload(input: { + readonly owner: PlacedUploadOwner; + readonly environmentId: EnvironmentId; + readonly attachment: DraftComposerAttachment; +}): Promise { + const before = ownedAttachment(input.owner, input.attachment.id); + if (before === null || before.attachment !== input.attachment) { + return { ok: false, reason: "This upload belonged to a placed task that no longer holds it." }; + } + return qualifyPlacedTarget({ + messageId: input.owner.messageId, + commandId: input.owner.commandId, + environmentId: input.environmentId, + stillOwned: () => { + const now = ownedAttachment(input.owner, input.attachment.id); + return ( + now !== null && + now.attachment === before.attachment && + now.text === before.text && + now.context === before.context + ); + }, + }); +} diff --git a/apps/mobile/src/state/threadOutboxDelivery.placement.test.ts b/apps/mobile/src/state/threadOutboxDelivery.placement.test.ts new file mode 100644 index 000000000000..b6124ceac3f0 --- /dev/null +++ b/apps/mobile/src/state/threadOutboxDelivery.placement.test.ts @@ -0,0 +1,581 @@ +import { + AuthOrchestrationOperateScope, + CommandId, + EnvironmentId, + MessageId, + OrchestrationV2ThreadPlacementAdmitError, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import { AsyncResult, type Atom } from "effect/reactivity"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { + decodeQueuedThreadMessage, + encodeQueuedThreadMessage, + threadOutboxRetryDelayMs, + type QueuedThreadMessage, +} from "./thread-outbox-model"; + +// A fresh Auto task is admitted at its recorded origin, then rebinds the same queued message to +// the machine it answered with. The outbox, its manager, the drain and the codec are real; only +// network edges (admission, launch, upload preparation), connections and projects are doubles. +const state = vi.hoisted(() => ({ + events: [] as Array, + /** Files on disk, one per message id, as their stored JSON. */ + stored: new Map(), + failWrites: false, + admitAnswer: null as null | (() => unknown), + admitHold: null as null | Promise, + /** Called as each admission request reaches the origin. */ + onAdmit: null as null | (() => void), + delivery: null as { readonly drain: () => void; readonly dispose: () => void } | null, + admit: vi.fn(), + start: vi.fn(), + prepare: vi.fn(), + manager: null as unknown as ReturnType< + typeof import("./thread-outbox-manager").createThreadOutboxManager + >, + connection: new Map(), + generation: new Map(), + config: { + shellThreadFamilies: false, + providers: [{ instanceId: "codex", driver: "codex", models: [] }], + environment: { capabilities: {} }, + }, +})); +vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); +vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + runAtomCommand: (_registry: unknown, command: (input: unknown) => unknown, input: unknown) => + command(input), +})); +vi.mock("./orchestration", () => ({ + orchestrationEnvironment: { admitThreadPlacement: state.admit }, +})); +vi.mock("../connection/catalog", async () => { + const { Atom: A, AsyncResult: R } = await import("effect/reactivity"); + const family = (map: Map, initial: () => unknown) => (id: string) => { + if (!map.has(id)) map.set(id, A.make(initial()).pipe(A.keepAlive)); + return map.get(id); + }; + return { + environmentCatalog: { + stateAtom: family(state.connection, () => R.success({ phase: "connected" })), + sessionGenerationAtom: family(state.generation, () => 1), + }, + }; +}); +vi.mock("./session", async () => { + const { Atom } = await import("effect/reactivity"); + const { appAtomRegistry } = await import("./atom-registry"); + const sessionStateAtom = Atom.family((_id: string) => Atom.make(true).pipe(Atom.keepAlive)); + const sessionHasScope = (granted: boolean, scope: string) => + granted && scope === AuthOrchestrationOperateScope; + return { + environmentSession: { sessionStateAtom }, + sessionHasScope, + readEnvironmentScope: (environmentId: string, scope: string) => + sessionHasScope(appAtomRegistry.get(sessionStateAtom(environmentId)), scope), + }; +}); +vi.mock("./projects", async () => { + const { Atom } = await import("effect/reactivity"); + return { + environmentProjects: { + projectsAtom: Atom.make([ + { environmentId: "laptop", id: "project-a", title: "Repo", workspaceRoot: "/a-root" }, + { environmentId: "box", id: "project-b", title: "Repo", workspaceRoot: "/b-root" }, + ]), + }, + }; +}); +vi.mock("./workspace", async () => { + const { Atom } = await import("effect/reactivity"); + return { + workspaceConnections: { + environmentsAtom: Atom.make([ + { environmentId: "laptop", connectionState: "connected" }, + { environmentId: "box", connectionState: "connected" }, + ]), + }, + }; +}); +vi.mock("./server", async () => { + const { Atom } = await import("effect/reactivity"); + return { + serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) }, + environmentServerConfigsAtom: Atom.make( + new Map([ + ["laptop", state.config], + ["box", state.config], + ]), + ), + }; +}); +vi.mock("./threads", async () => { + const { Atom, AsyncResult: R } = await import("effect/reactivity"); + return { + threadEnvironment: { startTurn: state.start }, + environmentThreadShells: { threadShellsAtom: Atom.make([]).pipe(Atom.keepAlive) }, + threadFamilies: { mount: () => () => {}, familyAtom: () => Atom.make(R.success({})) }, + environmentThreadDetails: { stateAtom: () => Atom.make(null) }, + }; +}); +vi.mock("./git", () => ({ gitEnvironment: {} })); +vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: () => false })); +vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" })); +vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare })); +vi.mock("./thread-outbox", async () => { + const model = await import("./thread-outbox-model"); + const { createThreadOutboxManager } = await import("./thread-outbox-manager"); + const { appAtomRegistry } = await import("./atom-registry"); + state.manager = createThreadOutboxManager({ + registry: appAtomRegistry, + storage: { + load: async () => ({ + messages: [...state.stored.values()].map((raw) => + model.decodeQueuedThreadMessage(JSON.parse(raw)), + ), + errors: [], + }), + write: async (message) => { + if (state.failWrites) throw new Error("disk full"); + state.stored.set( + `${encodeURIComponent(message.messageId)}.json`, + JSON.stringify(model.encodeQueuedThreadMessage(message)), + ); + }, + remove: async (message) => { + state.stored.delete(`${encodeURIComponent(message.messageId)}.json`); + }, + }, + }); + return { + flattenQueuedThreadMessages: model.flattenQueuedThreadMessages, + threadOutboxManager: state.manager, + threadOutboxRevision: (id: MessageId) => state.manager.revisionOf(id), + confirmThreadOutboxMessageQueued: (message: QueuedThreadMessage) => + state.manager.confirmQueued(message), + updateThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) => + state.manager.update(message, revision), + }; +}); +vi.mock("./thread-outbox-removal", () => ({ + removeThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) => + state.manager.remove(message, revision), +})); +vi.mock("./use-thread-outbox", async () => { + const { Atom } = await import("effect/reactivity"); + return { + editingQueuedMessageIdsAtom: Atom.make>({}).pipe(Atom.keepAlive), + dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive), + retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), + threadOutboxShellStatusesAtom: Atom.make( + new Map([ + ["laptop", "live"], + ["box", "live"], + ]), + ), + }; +}); +vi.mock("./use-composer-drafts", async () => { + const { Atom } = await import("effect/reactivity"); + return { + composerDraftsAtom: Atom.make({}), + removeDeliveredCloudQueuedMessage: async () => {}, + appendComposerDraftAttachments: vi.fn(), + flushComposerDrafts: vi.fn(async () => {}), + getComposerDraftSnapshot: vi.fn(() => ({ text: "", attachments: [] })), + mergeComposerDraftContent: vi.fn(async () => {}), + replaceComposerDraftAttachments: vi.fn(), + undoComposerDraftMerge: vi.fn(async () => {}), + updateComposerDraftSettings: vi.fn(), + waitForComposerDraftsLoaded: vi.fn(async () => {}), + }; +}); + +import { appAtomRegistry } from "./atom-registry"; +import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox"; +import { pendingThreadCreationOutcomesAtom } from "./pending-thread-creation"; +import * as drafts from "./use-composer-drafts"; +import { createThreadOutboxDelivery } from "./threadOutboxDelivery"; + +const laptop = EnvironmentId.make("laptop"); +const box = EnvironmentId.make("box"); +const shot = { + id: "shot", + type: "image" as const, + name: "shot.png", + mimeType: "image/png", + sizeBytes: 3, + dataUrl: "data:image/png;base64,YWJj", + previewUri: "data:image/png;base64,YWJj", +}; + +function autoTask(): QueuedThreadMessage { + return { + environmentId: laptop, + threadId: ThreadId.make("thread-auto"), + messageId: MessageId.make("message-auto"), + commandId: CommandId.make("command-auto"), + text: "Fix the build", + attachments: [shot], + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "approval-required", + interactionMode: "plan", + creation: { + projectId: ProjectId.make("project-a"), + projectTitle: "Repo", + projectCwd: "/a-root", + workspaceMode: "worktree", + branch: "main", + worktreePath: null, + }, + placement: { + originEnvironmentId: laptop, + originProjectId: ProjectId.make("project-a"), + candidateEnvironmentIds: [laptop, box], + }, + createdAt: "2026-11-18T16:00:00.000Z", + }; +} + +const bindsTo = (environmentId: string, projectId: string) => () => + AsyncResult.success({ environmentId, projectId, reason: "capacity", resumed: true }); +const refuses = + (reason: "other-session" | "excluded" | "unavailable" | "no-eligible-environment") => () => + AsyncResult.failure( + Cause.fail( + new OrchestrationV2ThreadPlacementAdmitError({ + commandId: CommandId.make("command-auto"), + reason, + detail: `refused: ${reason}`, + }), + ), + ); + +const queued = () => + Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat(); +const storedRecords = () => + [...state.stored.entries()].map(([file, raw]) => ({ file, record: JSON.parse(raw) as unknown })); +const targetEffects = () => state.events.filter((event) => !event.startsWith("admit")); + +const idle = () => appAtomRegistry.get(dispatchingQueuedMessageIdAtom) === null; +/** Resolves when the outbox and its delivery slot reach this state; checked on each change. */ +function until(predicate: () => boolean): Promise { + const done = Promise.withResolvers(); + const check = () => { + if (predicate()) done.resolve(); + }; + const stops = [ + appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, check), + appAtomRegistry.subscribe(state.manager.queuedMessagesByThreadKeyAtom, check), + ]; + check(); + return done.promise.finally(() => { + for (const stop of stops) stop(); + }); +} + +function startDelivery() { + if (state.delivery === null) state.delivery = createThreadOutboxDelivery(); + else state.delivery.drain(); +} + +function setConnected(environmentId: string, connected: boolean) { + const atom = state.connection.get(environmentId) as Atom.Writable; + appAtomRegistry.set( + atom, + AsyncResult.success({ phase: connected ? "connected" : "disconnected" }), + ); +} + +beforeEach(() => { + state.events.length = 0; + state.stored.clear(); + state.failWrites = false; + state.admitAnswer = bindsTo("box", "project-b"); + state.admitHold = null; + state.onAdmit = null; + for (const environmentId of state.connection.keys()) setConnected(environmentId, true); + for (const atom of state.generation.values()) + appAtomRegistry.set(atom as Atom.Writable, 1); + appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {}); + appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null); + appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); + appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {}); + state.admit + .mockReset() + .mockImplementation( + async (target: { + environmentId: string; + input: { candidateEnvironmentIds: ReadonlyArray }; + }) => { + state.events.push( + `admit:${target.environmentId}:${target.input.candidateEnvironmentIds.join(",")}`, + ); + state.onAdmit?.(); + if (state.admitHold) await state.admitHold; + return state.admitAnswer!(); + }, + ); + state.prepare + .mockReset() + .mockImplementation( + async (input: { environmentId: string; attachments: ReadonlyArray }) => { + state.events.push(`prepare:${input.environmentId}`); + return { + status: "ready", + attachments: [], + draftAttachments: input.attachments, + pendingAttachmentIds: [], + }; + }, + ); + state.start.mockReset().mockImplementation(async (target: { environmentId: string }) => { + state.events.push(`start:${target.environmentId}`); + return AsyncResult.success({}); + }); + vi.mocked(drafts.mergeComposerDraftContent).mockClear(); +}); + +afterEach(() => { + state.delivery?.dispose(); + state.delivery = null; + vi.useRealTimers(); +}); + +describe("a fresh Auto task's admission and binding", () => { + it("asks its origin first, rebinds the same message, then uploads and launches only at B", async () => { + const message = autoTask(); + await state.manager.enqueue(message); + // Origin admission, then B's own delivery pass (asked again before upload and before launch). + startDelivery(); + await until(() => queued().length === 0 && idle()); + expect(state.events).toEqual([ + "admit:laptop:laptop,box", + "admit:laptop:box", + "prepare:box", + "admit:laptop:box", + "start:box", + ]); + // Every admission is the same operation, with the exact request the task was sent with. + for (const [target] of state.admit.mock.calls) { + expect(target).toMatchObject({ + environmentId: "laptop", + input: { + commandId: "command-auto", + threadId: "thread-auto", + projectId: "project-a", + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "approval-required", + interactionMode: "plan", + }, + }); + } + // B's launch: same IDs, B's project and root; the origin's path is never used there. + const [launch] = state.start.mock.calls.at(-1)!; + expect(launch).toMatchObject({ + environmentId: "box", + input: { + commandId: "command-auto", + threadId: "thread-auto", + message: { messageId: "message-auto" }, + bootstrap: { + createThread: { projectId: "project-b" }, + prepareWorktree: { projectCwd: "/b-root" }, + }, + }, + }); + expect(queued()).toEqual([]); + }); + + it("persists the binding in the same file before anything reaches B", async () => { + const launched = Promise.withResolvers(); + state.start.mockImplementation(async () => { + launched.resolve(); + return new Promise(() => {}); + }); + await state.manager.enqueue(autoTask()); + startDelivery(); + await until(() => queued()[0]?.placement?.bound !== undefined); + const records = storedRecords(); + expect(records.map(({ file }) => file)).toEqual(["message-auto.json"]); + const bound = decodeQueuedThreadMessage(records[0]!.record); + expect(bound).toMatchObject({ + environmentId: "box", + messageId: "message-auto", + commandId: "command-auto", + creation: { projectId: "project-b", projectCwd: "/b-root" }, + placement: { + originEnvironmentId: "laptop", + originProjectId: "project-a", + bound: { environmentId: "box", projectId: "project-b" }, + }, + }); + // The live entry is that bound object, under B's thread key only. + expect(queued()).toEqual([bound].map((value) => expect.objectContaining(value))); + expect(Object.keys(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom))).toEqual([ + "box:thread-auto", + ]); + // Let this case's own delivery reach B before the next case starts. + await launched.promise; + }); + + it("never asks its origin when the task could not be written", async () => { + state.failWrites = true; + await expect(state.manager.enqueue(autoTask())).rejects.toThrow(); + startDelivery(); + await Promise.resolve(); + expect(state.admit).not.toHaveBeenCalled(); + expect(targetEffects()).toEqual([]); + }); + + it.each(["other-session", "excluded", "unavailable"] as const)( + "holds the task with the same origin and IDs when its origin answers %s", + async (reason) => { + state.admitAnswer = refuses(reason); + const message = autoTask(); + await state.manager.enqueue(message); + startDelivery(); + await until(idle); + expect(targetEffects()).toEqual([]); + expect(queued()).toEqual([message]); + expect(drafts.mergeComposerDraftContent).not.toHaveBeenCalled(); + }, + ); + + it("hands the task back to its origin's draft when no machine can take it", async () => { + state.admitAnswer = refuses("no-eligible-environment"); + await state.manager.enqueue(autoTask()); + startDelivery(); + await until(() => queued().length === 0 && idle()); + expect(targetEffects()).toEqual([]); + expect(queued()).toEqual([]); + expect(drafts.updateComposerDraftSettings).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ + project: expect.objectContaining({ environmentId: "laptop", projectId: "project-a" }), + environmentSelection: "auto", + }), + ); + }); + + it("asks again after a lost answer with the same IDs, never a replacement", async () => { + vi.useFakeTimers(); + state.admitAnswer = () => AsyncResult.failure(Cause.die("connection lost")); + const message = autoTask(); + await state.manager.enqueue(message); + startDelivery(); + await vi.advanceTimersByTimeAsync(0); + expect(queued()).toEqual([message]); + state.admitAnswer = bindsTo("box", "project-b"); + await vi.advanceTimersByTimeAsync(threadOutboxRetryDelayMs(1)); + await vi.advanceTimersByTimeAsync(0); + const asked = state.admit.mock.calls.map(([target]) => target.input); + expect(new Set(asked.map((input) => input.commandId))).toEqual(new Set(["command-auto"])); + expect(new Set(asked.map((input) => input.threadId))).toEqual(new Set(["thread-auto"])); + expect(state.stored.size).toBeLessThanOrEqual(1); + }); + + it.each(["the origin's connection drops", "the task is opened for editing"] as const)( + "acts on no answer when %s while its origin is asked", + async (change) => { + let release!: () => void; + state.admitHold = new Promise((done) => { + release = done; + }); + const message = autoTask(); + await state.manager.enqueue(message); + const reached = Promise.withResolvers(); + state.onAdmit = reached.resolve; + startDelivery(); + await reached.promise; + if (change === "the origin's connection drops") setConnected("laptop", false); + else appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); + release(); + await until(idle); + expect(queued()).toEqual([message]); + expect( + decodeQueuedThreadMessage(storedRecords()[0]!.record).placement?.bound, + ).toBeUndefined(); + expect(targetEffects()).toEqual([]); + }, + ); + + it("uploads and launches nothing at B once its origin refuses the stored binding", async () => { + state.start.mockImplementation(async () => new Promise(() => {})); + await state.manager.enqueue(autoTask()); + // Bound first, then its origin excludes B before B's delivery asks again. + state.admit.mockImplementationOnce( + async (target: { environmentId: string; input: { candidateEnvironmentIds: string[] } }) => { + state.events.push( + `admit:${target.environmentId}:${target.input.candidateEnvironmentIds.join(",")}`, + ); + state.admitAnswer = refuses("excluded"); + return bindsTo("box", "project-b")(); + }, + ); + startDelivery(); + await until(() => state.admit.mock.calls.length >= 2 && idle()); + expect(targetEffects()).toEqual([]); + expect(queued()).toHaveLength(1); + }); + + it("resumes a bound task after a restart as the same operation at B", async () => { + // Its own id: the manager tombstones ids earlier cases removed, and never resurrects them. + const bound: QueuedThreadMessage = { + ...autoTask(), + messageId: MessageId.make("message-restart"), + environmentId: box, + creation: { + ...autoTask().creation!, + projectId: ProjectId.make("project-b"), + projectCwd: "/b-root", + }, + placement: { + ...autoTask().placement!, + bound: { environmentId: box, projectId: ProjectId.make("project-b") }, + }, + }; + state.stored.set("message-restart.json", JSON.stringify(encodeQueuedThreadMessage(bound))); + expect(await state.manager.load()).toBe(true); + expect(queued()).toEqual([bound]); + startDelivery(); + await until(() => queued().length === 0 && idle()); + expect(state.events).toEqual([ + "admit:laptop:box", + "prepare:box", + "admit:laptop:box", + "start:box", + ]); + }); + + it("leaves a legacy fixed creation to its own machine without asking anyone", async () => { + const { placement: _placement, ...fixed } = autoTask(); + await state.manager.enqueue({ ...fixed, messageId: MessageId.make("message-fixed") }); + startDelivery(); + await until(() => queued().length === 0 && idle()); + expect(state.admit).not.toHaveBeenCalled(); + expect(state.events).toEqual(["prepare:laptop", "start:laptop"]); + }); +}); + +describe("a bound task's environment clear", () => { + it("follows its destination B, not its origin", async () => { + const bound: QueuedThreadMessage = { + ...autoTask(), + messageId: MessageId.make("message-clear"), + environmentId: box, + placement: { + ...autoTask().placement!, + bound: { environmentId: box, projectId: ProjectId.make("project-b") }, + }, + }; + await state.manager.enqueue(bound); + expect(await state.manager.clearEnvironment(laptop)).toEqual([]); + expect(await state.manager.clearEnvironment(box)).toEqual([bound]); + }); +}); diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index 74cf7597e0ef..b731160f6d7d 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -62,7 +62,9 @@ import { updateThreadOutboxMessage, } from "./thread-outbox"; import { removeThreadOutboxMessage } from "./thread-outbox-removal"; +import { admitPlacedCreation, qualifyPlacedTarget } from "./thread-placement"; import { + awaitsPlacement, isQueuedThreadCreationSendable, resolveThreadOutboxDeliveryAction, resolveThreadOutboxDispatchStep, @@ -546,12 +548,15 @@ function stampRecoveryDraftProject(queuedMessage: QueuedThreadMessage, draftKey: if (!queuedMessage.creation) { return; } + const placement = queuedMessage.placement; + // A placed task comes back where it was sent from, still placed by its origin. updateComposerDraftSettings(draftKey, { project: { - environmentId: queuedMessage.environmentId, - projectId: queuedMessage.creation.projectId, + environmentId: placement?.originEnvironmentId ?? queuedMessage.environmentId, + projectId: placement?.originProjectId ?? queuedMessage.creation.projectId, createdAt: queuedMessage.createdAt, }, + ...(placement !== undefined ? { environmentSelection: "auto" as const } : {}), }); } @@ -1035,6 +1040,29 @@ export function createThreadOutboxDelivery(): { if (runtimeModeDenial !== undefined) { return restoreQueuedMessage(queuedMessage, runtimeModeDenial); } + // A placed task's origin confirms its binding before anything is uploaded or prepared at B. + const placedTargetQualified = async ( + message: QueuedThreadMessage, + revision: number, + ): Promise => { + if (message.placement === undefined) return null; + const qualification = await qualifyPlacedTarget({ + messageId: message.messageId, + commandId: message.commandId, + environmentId: message.environmentId, + stillOwned: () => + isQueuedMessagePayloadCurrent(message, revision) && + !appAtomRegistry.get(editingQueuedMessageIdsAtom)[message.messageId], + }); + if (qualification.ok) return null; + // Held with the same origin and IDs; a newer owner decides on its own pass. + return !isQueuedMessagePayloadCurrent(message, revision); + }; + const heldBeforeUpload = await placedTargetQualified( + queuedMessage, + threadOutboxRevision(queuedMessage.messageId), + ); + if (heldBeforeUpload !== null) return heldBeforeUpload; let prepared: PreparedTurnAttachments; let persistedMessage: QueuedThreadMessage; let deliveryRevision: number; @@ -1116,6 +1144,8 @@ export function createThreadOutboxDelivery(): { startFromOrigin: false, }; } + const heldBeforeLaunch = await placedTargetQualified(persistedMessage, deliveryRevision); + if (heldBeforeLaunch !== null) return heldBeforeLaunch; launchedCreations.set(persistedMessage.messageId, { revision: deliveryRevision, workspace }); const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, { environmentId: queuedMessage.environmentId, @@ -1285,6 +1315,30 @@ export function createThreadOutboxDelivery(): { if (retryNotBefore(messageId) > Date.now()) { continue; } + if (awaitsPlacement(nextQueuedMessage)) { + // Admission comes before every destination gate: the uploads wait for it, and the origin's + // project and shell say nothing about the machine it binds. + const origin = nextQueuedMessage.placement!.originEnvironmentId; + if ( + !isQueuedThreadCreationSendable(nextQueuedMessage) || + !ready.has(origin) || + !operableEnvironments.has(origin) + ) { + continue; + } + beginDispatchingQueuedMessage(messageId); + settle( + messageId, + admitPlacedCreation(nextQueuedMessage).then((result) => + result.step === "hold" + ? false + : result.step === "restore" + ? restoreQueuedMessage(nextQueuedMessage, result.reason) + : true, + ), + ); + return; + } if ( queuedAttachmentsStillUploading({ environmentId: nextQueuedMessage.environmentId, @@ -1410,7 +1464,11 @@ export function createThreadOutboxDelivery(): { if (!isQueuedThreadCreationSendable(nextQueuedMessage)) { continue; } - if (creationProjectCwd === null && shellStatus !== "live") { + // A placed task's project is B's own; it is never dropped for a list that lags its binding. + if ( + creationProjectCwd === null && + (shellStatus !== "live" || nextQueuedMessage.placement !== undefined) + ) { continue; } } diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index 200b2b165c6b..e39d902591a6 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -213,6 +213,7 @@ import { insertComposerDraftContext, insertComposerDraftText, rememberComposerDraftSelection, + schedulePersistComposerState, setComposerDraftAttachmentUpload, waitForComposerDraftsLoaded, setStickyComposerModelSelection, @@ -2806,3 +2807,73 @@ describe("mobile composer drafts", () => { expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); }); }); + +describe("placement state in the drafts document", () => { + const placedTask = { + environmentId: EnvironmentId.make("environment-1"), + threadId: ThreadId.make("thread-placed"), + messageId: MessageId.make("message-placed"), + commandId: CommandId.make("command-placed"), + text: "Fix it", + attachments: [], + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + creation: { + projectId: ProjectId.make("project-1"), + workspaceMode: "worktree" as const, + branch: "main", + worktreePath: null, + }, + placement: { + originEnvironmentId: EnvironmentId.make("environment-1"), + originProjectId: ProjectId.make("project-1"), + candidateEnvironmentIds: [ + EnvironmentId.make("environment-1"), + EnvironmentId.make("environment-2"), + ], + }, + createdAt: "2026-11-18T16:00:00.000Z", + }; + + it("writes the version older readers refuse only while an Auto draft is held", async () => { + await waitForComposerDraftsLoaded(); + const key = createNewTaskDraft( + { + environmentId: EnvironmentId.make("environment-1"), + projectId: ProjectId.make("project-1"), + }, + "auto", + ); + setComposerDraftText(key, "Auto work"); + await flushComposerDrafts(); + const written = JSON.parse(composerDraftFileMocks.getDocument()); + expect(written.schemaVersion).toBe(2); + expect(written.drafts[key].environmentSelection).toBe("auto"); + // Read back by this reader, the intent is kept: it is never an unmarked fixed draft. + expect(decodePersistedComposerState(written).drafts[key]?.environmentSelection).toBe("auto"); + + // Pinned to its machine, nothing an older reader could misread remains. + updateComposerDraftSettings(key, { environmentSelection: "manual" }); + await flushComposerDrafts(); + expect(JSON.parse(composerDraftFileMocks.getDocument()).schemaVersion).toBe(1); + }); + + it("keeps a signed-out placed task as its envelope, under the version older readers refuse", async () => { + await waitForComposerDraftsLoaded(); + appAtomRegistry.set(composerCloudDraftsAtom, { + accountId: "account-1", + signedOut: { "account-1": { drafts: {}, queuedMessages: [placedTask] } }, + }); + schedulePersistComposerState(); + await flushComposerDrafts(); + const written = JSON.parse(composerDraftFileMocks.getDocument()); + expect(written.schemaVersion).toBe(2); + expect(written.signedOutDrafts["account-1"].queuedMessages[0]).toMatchObject({ + kind: "placed-creation", + placement: { originEnvironmentId: "environment-1" }, + message: { messageId: "message-placed", commandId: "command-placed" }, + }); + expect( + decodePersistedComposerState(written).cloudDrafts.signedOut["account-1"]?.queuedMessages, + ).toEqual([placedTask]); + }); +}); diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 0306d5e7db5e..12dcd8e8ffd9 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -67,6 +67,7 @@ import { import { decodeQueuedThreadMessage, encodeQueuedThreadMessage, + PlacedQueuedThreadMessageSchema, QueuedThreadMessageSchema, type QueuedThreadMessage, } from "./thread-outbox-model"; @@ -74,6 +75,12 @@ import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox"; import { composerDraftEnvironmentId } from "../lib/composerAttachmentUploadQueue"; const COMPOSER_DRAFTS_SCHEMA_VERSION = 1; +/** + * Written only while the document holds state an older reader would misread: an Auto draft (read + * as a fixed draft, its bytes would upload before admission) or a placed queued task. An older + * reader fails to decode it, and its writes wait on a successful load, so it never overwrites it. + */ +const COMPOSER_DRAFTS_PLACEMENT_SCHEMA_VERSION = 2; const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts"; const COMPOSER_DRAFTS_FILE = "drafts.json"; const PERSIST_DEBOUNCE_MS = 200; @@ -448,6 +455,11 @@ export interface ComposerDraft { /** `/clear` armed this draft: its next message starts a fresh provider session. */ readonly freshContext?: boolean; readonly workspaceSelection?: ComposerDraftWorkspaceSelection; + /** + * A new task's machine: `auto` is placed by its origin, `manual` is the machine picked. Absent on + * drafts from before this choice, which keep running on their own machine. + */ + readonly environmentSelection?: "auto" | "manual"; readonly project?: ComposerDraftProject; } @@ -485,6 +497,7 @@ export type ComposerDraftSettingsUpdate = Pick< | "interactionMode" | "freshContext" | "workspaceSelection" + | "environmentSelection" | "project" >; @@ -519,11 +532,15 @@ const ComposerDraftSchema = Schema.Struct({ interactionMode: Schema.optional(ProviderInteractionModeSchema), freshContext: Schema.optional(Schema.Boolean), workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema), + environmentSelection: Schema.optional(Schema.Literals(["auto", "manual"])), project: Schema.optional(ComposerDraftProjectSchema), }); const PersistedComposerDraftsSchema = Schema.Struct({ - schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION), + schemaVersion: Schema.Literals([ + COMPOSER_DRAFTS_SCHEMA_VERSION, + COMPOSER_DRAFTS_PLACEMENT_SCHEMA_VERSION, + ]), drafts: Schema.Record(Schema.String, ComposerDraftSchema), stickyModelSelection: Schema.optional(ModelSelectionSchema), modelOptionMemory: Schema.optional( @@ -538,7 +555,9 @@ const PersistedComposerDraftsSchema = Schema.Struct({ Schema.String, Schema.Struct({ drafts: Schema.Record(Schema.String, ComposerDraftSchema), - queuedMessages: Schema.Array(QueuedThreadMessageSchema), + queuedMessages: Schema.Array( + Schema.Union([PlacedQueuedThreadMessageSchema, QueuedThreadMessageSchema]), + ), }), ), ), @@ -698,7 +717,8 @@ function isEmptyDraft(draft: ComposerDraft): boolean { draft.runtimeMode === undefined && draft.interactionMode === undefined && draft.freshContext !== true && - draft.workspaceSelection === undefined + draft.workspaceSelection === undefined && + draft.environmentSelection === undefined ); } @@ -843,8 +863,19 @@ async function writePersistedComposerState( const nonEmptyDrafts = Object.fromEntries( Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)), ); + const signedOut = Object.values(cloudDrafts.signedOut); + const holdsPlacementState = + [ + ...Object.values(nonEmptyDrafts), + ...signedOut.flatMap((saved) => Object.values(saved.drafts)), + ].some((draft) => draft.environmentSelection === "auto") || + signedOut.some((saved) => + saved.queuedMessages.some((message) => message.placement !== undefined), + ); const document = { - schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION, + schemaVersion: holdsPlacementState + ? COMPOSER_DRAFTS_PLACEMENT_SCHEMA_VERSION + : COMPOSER_DRAFTS_SCHEMA_VERSION, drafts: nonEmptyDrafts, ...(stickyModelSelection ? { stickyModelSelection } : {}), ...(Object.keys(appAtomRegistry.get(modelOptionMemoryAtom)).length > 0 @@ -1254,12 +1285,14 @@ export async function removeDeliveredCloudQueuedMessage( archived.runtimeMode, archived.interactionMode, archived.creation, + archived.placement, ]) !== JSON.stringify([ message.modelSelection, message.runtimeMode, message.interactionMode, message.creation, + message.placement, ]) ) continue; @@ -1876,7 +1909,8 @@ export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): bool a.runtimeMode === b.runtimeMode && a.interactionMode === b.interactionMode && a.freshContext === b.freshContext && - a.workspaceSelection === b.workspaceSelection + a.workspaceSelection === b.workspaceSelection && + a.environmentSelection === b.environmentSelection ); } @@ -2007,10 +2041,14 @@ export function removeComposerDraftsForEnvironment( ); } -export function createNewTaskDraft(project: { - readonly environmentId: EnvironmentId; - readonly projectId: ProjectId; -}): string { +export function createNewTaskDraft( + project: { + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; + }, + /** Seeded once, for a new draft only: it is the draft's intent from then on. */ + environmentSelection?: "auto" | "manual", +): string { const draftKey = newTaskDraftKey(newDraftId()); const stamp: ComposerDraftProject = { environmentId: project.environmentId, @@ -2019,7 +2057,11 @@ export function createNewTaskDraft(project: { }; updateComposerDrafts((current) => ({ ...current, - [draftKey]: { ...EMPTY_DRAFT, project: stamp }, + [draftKey]: { + ...EMPTY_DRAFT, + project: stamp, + ...(environmentSelection ? { environmentSelection } : {}), + }, })); return draftKey; } @@ -2154,13 +2196,21 @@ export const newTaskComposerDraftsAtom = Atom.make((get): ComposerDraftsByKey => return matching.length === 0 ? EMPTY_DRAFTS : Object.fromEntries(matching); }).pipe(Atom.withEquality(sameDrafts)); -type ComposerDraftUploadSource = Pick; +// Routing decides whether a draft's bytes may upload at all, so it is part of the source. +type ComposerDraftUploadSource = Pick< + ComposerDraft, + "attachments" | "project" | "environmentSelection" +>; type ComposerDraftUploadSources = Readonly>; export const composerDraftUploadSourcesAtom = Atom.make((get): ComposerDraftUploadSources => Object.fromEntries( Object.entries(get(composerDraftsAtom)).map(([key, draft]) => [ key, - { attachments: draft.attachments, project: draft.project }, + { + attachments: draft.attachments, + project: draft.project, + environmentSelection: draft.environmentSelection, + }, ]), ), ).pipe( @@ -2169,7 +2219,10 @@ export const composerDraftUploadSourcesAtom = Atom.make((get): ComposerDraftUplo return ( keys.length === Object.keys(b).length && keys.every( - (key) => a[key]?.attachments === b[key]?.attachments && a[key]?.project === b[key]?.project, + (key) => + a[key]?.attachments === b[key]?.attachments && + a[key]?.project === b[key]?.project && + a[key]?.environmentSelection === b[key]?.environmentSelection, ) ); }), diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.ts index 35598d74bc36..4760eb765250 100644 --- a/apps/mobile/src/state/use-thread-selection.ts +++ b/apps/mobile/src/state/use-thread-selection.ts @@ -1,6 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; -import { useRoute, type RouteProp } from "@react-navigation/native"; -import { useState } from "react"; +import { useNavigation, useRoute, type RouteProp } from "@react-navigation/native"; +import { useEffect, useEffectEvent, useState } from "react"; import { EnvironmentId, ThreadId, @@ -23,6 +23,7 @@ import { scopedThreadKey } from "../lib/scopedEntities"; import { useProject, useQuietThreadShell } from "./entities"; import { useEnvironmentThread } from "./threads"; import { + resolvePendingRouteThreadRef, resolvePendingThreadCreation, pendingThreadCreationOutcomesAtom, pendingThreadCreationShell, @@ -37,6 +38,7 @@ import { useThreadOutboxMessages } from "./use-thread-outbox"; type ThreadSelectionRouteParams = { readonly environmentId?: string | string[]; readonly threadId?: string | string[]; + readonly pendingMessageId?: string | string[]; }; function firstRouteParam(value: string | string[] | undefined): string | null { @@ -112,10 +114,57 @@ function threadDetailToShell( }); } -function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) { +/** The route's thread, through its pending task's current binding when it names one. */ +export function usePendingRouteThread(params: ThreadSelectionRouteParams | undefined) { const routeParams = params ?? {}; - const routeEnvironmentId = firstRouteParam(routeParams.environmentId); - const routeThreadId = firstRouteParam(routeParams.threadId); + const environmentId = firstRouteParam(routeParams.environmentId); + const threadId = firstRouteParam(routeParams.threadId); + const queuedMessagesByThreadKey = useThreadOutboxMessages(); + const outcomes = useAtomValue(pendingThreadCreationOutcomesAtom); + const resolved = resolvePendingRouteThreadRef({ + routeRef: environmentId !== null && threadId !== null ? { environmentId, threadId } : null, + pendingMessageId: firstRouteParam(routeParams.pendingMessageId), + queuedMessagesByThreadKey, + outcomes, + }); + return { + environmentId: resolved === null ? null : String(resolved.environmentId), + threadId: resolved === null ? null : String(resolved.threadId), + }; +} + +/** + * The live route's thread through its pending task's binding, moving this route's own params there + * once bound so every later reader uses that thread. Only this route moves, and only while it still + * names the same pending task: a background completion never takes another screen's navigation. + */ +export function useFollowPendingRoute(params: ThreadSelectionRouteParams | undefined) { + const resolved = usePendingRouteThread(params); + const pendingMessageId = firstRouteParam(params?.pendingMessageId); + const routeFollowsBinding = + pendingMessageId === null || + (firstRouteParam(params?.environmentId) === resolved.environmentId && + firstRouteParam(params?.threadId) === resolved.threadId); + const navigation = useNavigation(); + const followBinding = useEffectEvent(() => { + if ( + resolved.environmentId === null || + resolved.threadId === null || + firstRouteParam(params?.pendingMessageId) !== pendingMessageId + ) + return; + navigation.setParams({ environmentId: resolved.environmentId, threadId: resolved.threadId }); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves this route's params to the machine its pending task was bound to, so every later reader uses that thread + useEffect(() => { + if (!routeFollowsBinding) followBinding(); + }, [routeFollowsBinding]); + return { ...resolved, routeFollowsBinding }; +} + +function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) { + const { environmentId: routeEnvironmentId, threadId: routeThreadId } = + usePendingRouteThread(params); // Retain the last complete thread ref while closing routes drop params. const [lastRouteThreadRef, setLastRouteThreadRef] = useState(null); if ( diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index e9f1260b514c..24c4b4d8457c 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -6,6 +6,7 @@ import "vite-plus/test/config"; const reactTests = [ "src/features/threads/git/GitBranchesSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", + "src/features/home/pendingTaskRoute.test.tsx", "src/features/layout/workspace/workspace-tabs-state.test.ts", "src/state/use-thread-pr.demand.test.tsx", "src/features/threads/git/GitBranchesSheet.occupancy.test.tsx",