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