Open History to see the last commit
1import {
2 presentThreadShell,
3 type EnvironmentThreadShell,
4} from "@t3tools/client-runtime/state/shell";
5import type { LocalThreadMessage } from "../lib/threadActivity";
6import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts";
7import { Atom } from "effect/reactivity";
8import * as DateTime from "effect/DateTime";
9
10import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
11import { scopedThreadKey } from "../lib/scopedEntities";
12import { appAtomRegistry } from "./atom-registry";
13import type { QueuedThreadMessage } from "./thread-outbox-model";
14
15export type PendingThreadCreationOutcome =
16 | { readonly kind: "delivered"; readonly message: QueuedThreadMessage }
17 | { readonly kind: "failed"; readonly message: QueuedThreadMessage; readonly reason: string };
18
19export type PendingThreadCreation = {
20 readonly message: QueuedThreadMessage;
21 readonly outcome: PendingThreadCreationOutcome | null;
22};
23
24export function selectThreadCreationDetail<Ref>(input: {
25 readonly threadRef: Ref | null;
26 readonly threadKey: string | null;
27 readonly queuedMessagesByThreadKey: Readonly<
28 Record<string, ReadonlyArray<QueuedThreadMessage> | undefined>
29 >;
30 readonly outcomes: Readonly<Record<string, PendingThreadCreationOutcome | undefined>>;
31}): { readonly pendingCreation: PendingThreadCreation | null; readonly detailRef: Ref | null } {
32 const pendingCreation = ((): PendingThreadCreation | null => {
33 if (input.threadKey === null) {
34 return null;
35 }
36 const queued = input.queuedMessagesByThreadKey[input.threadKey]?.find(
37 (message) => message.creation !== undefined,
38 );
39 const outcome = input.outcomes[input.threadKey] ?? null;
40 const message = queued ?? outcome?.message ?? null;
41 return message === null ? null : { message, outcome };
42 })();
43 // The shell can arrive before creation is acknowledged. Wait for delivery
44 // before subscribing: an early not-found is cached as a deleted thread.
45 // Every detail reader must use this ref, not the route id.
46 const detailRef =
47 pendingCreation === null || pendingCreation.outcome?.kind === "delivered"
48 ? input.threadRef
49 : null;
50 return { pendingCreation, detailRef };
51}
52
53export function resolvePendingThreadCreation(input: {
54 readonly threadKey: string | null;
55 readonly pending: PendingThreadCreation | null;
56 readonly previous: PendingThreadCreation | null;
57 readonly detail: {
58 readonly messages: ReadonlyArray<{ readonly id: string }>;
59 readonly runs: ReadonlyArray<{ readonly status: string }>;
60 } | null;
61}): PendingThreadCreation | null {
62 const creation = input.pending ?? input.previous;
63 if (
64 creation === null ||
65 scopedThreadKey(creation.message.environmentId, creation.message.threadId) !== input.threadKey
66 ) {
67 return null;
68 }
69 if (creation.outcome?.kind === "failed") return creation;
70 const detail = input.detail;
71 const latestRun = detail?.runs.at(-1);
72 const terminalStatus = latestRun?.status;
73 if (
74 terminalStatus === "failed" ||
75 terminalStatus === "cancelled" ||
76 terminalStatus === "interrupted"
77 )
78 return null;
79 // Message delivery can precede startup; wait for turn timing before replacing the preparing pill.
80 if (
81 detail !== null &&
82 latestRun !== undefined &&
83 !isPendingThreadCreationVisible({
84 creationMessageId: creation.message.messageId,
85 loadedMessageIds: detail.messages.map((message) => message.id),
86 })
87 ) {
88 return null;
89 }
90 return creation;
91}
92
93export const pendingThreadCreationOutcomesAtom = Atom.make<
94 Readonly<Record<string, PendingThreadCreationOutcome>>
95>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:pending-thread-creation:outcomes"));
96
97export function recordPendingThreadCreationOutcome(outcome: PendingThreadCreationOutcome): void {
98 const key = scopedThreadKey(outcome.message.environmentId, outcome.message.threadId);
99 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {
100 ...appAtomRegistry.get(pendingThreadCreationOutcomesAtom),
101 [key]: outcome,
102 });
103}
104
105export function clearPendingThreadCreationOutcome(threadKey: string): void {
106 const current = appAtomRegistry.get(pendingThreadCreationOutcomesAtom);
107 if (!current[threadKey]) {
108 return;
109 }
110 const next = { ...current };
111 delete next[threadKey];
112 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, next);
113}
114
115/** Thread shell and empty detail precede the prompt: worktree setup runs between creation and turn start. */
116function isPendingThreadCreationVisible(input: {
117 readonly creationMessageId: string;
118 readonly loadedMessageIds: ReadonlyArray<string> | null;
119}): boolean {
120 return !input.loadedMessageIds?.includes(input.creationMessageId);
121}
122
123export function pendingThreadCreationMessage(message: QueuedThreadMessage): LocalThreadMessage {
124 return {
125 id: message.messageId,
126 role: "user",
127 text: message.text,
128 context: message.context,
129 // Local draft ids cannot resolve server-side and would spin forever on rejected creation.
130 streaming: false,
131 createdAt: message.createdAt,
132 updatedAt: message.createdAt,
133 };
134}
135
136export function pendingThreadCreationShell(
137 message: QueuedThreadMessage,
138): EnvironmentThreadShell | null {
139 const creation = message.creation;
140 if (!creation || !message.modelSelection) {
141 return null;
142 }
143 const timestamp = DateTime.makeUnsafe(message.createdAt);
144 return presentThreadShell(message.environmentId, {
145 id: message.threadId,
146 projectId: creation.projectId,
147 title: deriveThreadTitleFromPrompt(message.text),
148 providerInstanceId: message.modelSelection.instanceId,
149 modelSelection: message.modelSelection,
150 runtimeMode: message.runtimeMode ?? DEFAULT_RUNTIME_MODE,
151 interactionMode: message.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
152 branch: creation.branch,
153 pullRequests: [],
154 worktreePath: creation.workspaceMode === "worktree" ? null : creation.worktreePath,
155 linkedPullRequest: null,
156 branchPullRequest: null,
157 lineage: { rootThreadId: message.threadId, parentThreadId: null, relationshipToParent: null },
158 forkedFrom: null,
159 createdBy: "user",
160 creationSource: "mobile",
161 activeProviderThreadId: null,
162 latestRunId: null,
163 activeRunId: null,
164 status: "preparing",
165 pendingRuntimeRequest: null,
166 latestVisibleMessage: null,
167 latestUserMessageAt: timestamp,
168 hasActionableProposedPlan: false,
169 itemCount: 0,
170 visibleItemCount: 0,
171 createdAt: timestamp,
172 updatedAt: timestamp,
173 archivedAt: null,
174 settledOverride: null,
175 settledAt: null,
176 unsettledAt: null,
177 snoozedUntil: null,
178 snoozedAt: null,
179 pinnedAt: null,
180 pinOrderKey: null,
181 activeOrderKey: null,
182 deletedAt: null,
183 });
184}