Open History to see the last commit
1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import type { OrchestrationThread } from "@t3tools/contracts";
3import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts";
4import { Atom } from "effect/unstable/reactivity";
5
6import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
7import { scopedThreadKey } from "../lib/scopedEntities";
8import { appAtomRegistry } from "./atom-registry";
9import type { QueuedThreadMessage } from "./thread-outbox-model";
10
11/**
12 * A new task navigates to its thread screen the moment it is queued, before the
13 * server has created the thread. Until the shell arrives the screen renders a
14 * stand-in built from the queued creation. The outcome recorded by the outbox
15 * drain covers the two windows that stand-in cannot: the gap between delivery
16 * and the first turn (keep showing setup) and a rejected creation
17 * (the drain restored the content into the project draft; offer to reopen it).
18 */
19export type PendingThreadCreationOutcome =
20 | { readonly kind: "delivered"; readonly message: QueuedThreadMessage }
21 | { readonly kind: "failed"; readonly message: QueuedThreadMessage; readonly reason: string };
22
23export type PendingThreadCreation = {
24 readonly message: QueuedThreadMessage;
25 readonly outcome: PendingThreadCreationOutcome | null;
26};
27
28/** Keep the screen's creation state until its detail can take over the pill. */
29export function resolvePendingThreadCreation(input: {
30 readonly threadKey: string | null;
31 readonly pending: PendingThreadCreation | null;
32 readonly previous: PendingThreadCreation | null;
33 readonly detail: {
34 readonly messages: ReadonlyArray<{ readonly id: string }>;
35 readonly latestTurn: { readonly turnId: string } | null;
36 readonly session: { readonly status: string } | null;
37 } | null;
38}): PendingThreadCreation | null {
39 const creation = input.pending ?? input.previous;
40 if (
41 creation === null ||
42 scopedThreadKey(creation.message.environmentId, creation.message.threadId) !== input.threadKey
43 ) {
44 return null;
45 }
46 if (creation.outcome?.kind === "failed") return creation;
47 const detail = input.detail;
48 if (
49 detail?.session?.status === "error" ||
50 detail?.session?.status === "stopped" ||
51 detail?.session?.status === "interrupted"
52 )
53 return null;
54 // Message delivery and turn startup are separate events. The prompt alone
55 // cannot replace the preparing pill; wait for the turn's timing too. Retain
56 // the local creation if the outbox has already collected its shell outcome.
57 if (
58 detail !== null &&
59 detail.latestTurn !== null &&
60 !isPendingThreadCreationVisible({
61 creationMessageId: creation.message.messageId,
62 loadedMessageIds: detail.messages.map((message) => message.id),
63 })
64 ) {
65 return null;
66 }
67 return creation;
68}
69
70export const pendingThreadCreationOutcomesAtom = Atom.make<
71 Readonly<Record<string, PendingThreadCreationOutcome>>
72>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:pending-thread-creation:outcomes"));
73
74export function recordPendingThreadCreationOutcome(outcome: PendingThreadCreationOutcome): void {
75 const key = scopedThreadKey(outcome.message.environmentId, outcome.message.threadId);
76 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {
77 ...appAtomRegistry.get(pendingThreadCreationOutcomesAtom),
78 [key]: outcome,
79 });
80}
81
82export function clearPendingThreadCreationOutcome(threadKey: string): void {
83 const current = appAtomRegistry.get(pendingThreadCreationOutcomesAtom);
84 if (!current[threadKey]) {
85 return;
86 }
87 const next = { ...current };
88 delete next[threadKey];
89 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, next);
90}
91
92/**
93 * Whether the queued prompt still has to stand in for the real message.
94 *
95 * The server creates the thread, then builds the worktree, and only then
96 * starts the turn, so the thread shell and an empty detail arrive seconds
97 * ahead of the prompt. Keying this on the shell's arrival left the thread
98 * showing "No conversation yet" for that whole window. The queued message id
99 * is reused as the delivered message id, so its presence is the exact signal.
100 */
101export function isPendingThreadCreationVisible(input: {
102 readonly creationMessageId: string;
103 /** Null while no detail has loaded; empty during a worktree checkout. */
104 readonly loadedMessageIds: ReadonlyArray<string> | null;
105}): boolean {
106 return !input.loadedMessageIds?.includes(input.creationMessageId);
107}
108
109export function pendingThreadCreationMessage(
110 message: QueuedThreadMessage,
111): OrchestrationThread["messages"][number] {
112 return {
113 id: message.messageId,
114 role: "user",
115 text: message.text,
116 // Deliberately no attachments. Their ids are local draft ids the server
117 // cannot resolve, so the feed's attachment rows would sit on a spinner
118 // that only ends when the real message arrives — and never, if the
119 // creation is rejected. The delivered message renders them moments later.
120 turnId: null,
121 streaming: false,
122 createdAt: message.createdAt,
123 updatedAt: message.createdAt,
124 };
125}
126
127/**
128 * Thread shell shaped from a queued creation. `modelSelection` is required on
129 * the shell; a creation is only sendable with one, so the fallback never sends.
130 */
131export function pendingThreadCreationShell(
132 message: QueuedThreadMessage,
133): EnvironmentThreadShell | null {
134 const creation = message.creation;
135 if (!creation || !message.modelSelection) {
136 return null;
137 }
138 return {
139 environmentId: message.environmentId,
140 id: message.threadId,
141 projectId: creation.projectId,
142 title: deriveThreadTitleFromPrompt(message.text),
143 modelSelection: message.modelSelection,
144 runtimeMode: message.runtimeMode ?? DEFAULT_RUNTIME_MODE,
145 interactionMode: message.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
146 branch: creation.branch,
147 worktreePath: creation.workspaceMode === "worktree" ? null : creation.worktreePath,
148 linkedPullRequest: null,
149 latestTurn: null,
150 createdAt: message.createdAt,
151 updatedAt: message.createdAt,
152 archivedAt: null,
153 settledOverride: null,
154 settledAt: null,
155 snoozedUntil: null,
156 snoozedAt: null,
157 session: null,
158 latestUserMessageAt: message.createdAt,
159 hasPendingApprovals: false,
160 hasPendingUserInput: false,
161 hasActionableProposedPlan: false,
162 };
163}