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 readonly latestTurn?: { readonly turnId: string } | null;
61 readonly session?: { readonly status: string } | null;
62 } | null;
63}): PendingThreadCreation | null {
64 const creation = input.pending ?? input.previous;
65 if (
66 creation === null ||
67 scopedThreadKey(creation.message.environmentId, creation.message.threadId) !== input.threadKey
68 ) {
69 return null;
70 }
71 if (creation.outcome?.kind === "failed") return creation;
72 const detail = input.detail;
73 const latestRun = detail?.runs?.at(-1);
74 const terminalStatus = latestRun?.status ?? detail?.session?.status;
75 if (
76 terminalStatus === "failed" ||
77 terminalStatus === "error" ||
78 terminalStatus === "cancelled" ||
79 terminalStatus === "stopped" ||
80 terminalStatus === "interrupted"
81 )
82 return null;
83 // Message delivery can precede startup; wait for turn timing before replacing the preparing pill.
84 if (
85 detail !== null &&
86 (latestRun !== undefined || detail.latestTurn != null) &&
87 !isPendingThreadCreationVisible({
88 creationMessageId: creation.message.messageId,
89 loadedMessageIds: detail.messages.map((message) => message.id),
90 })
91 ) {
92 return null;
93 }
94 return creation;
95}
96
97export const pendingThreadCreationOutcomesAtom = Atom.make<
98 Readonly<Record<string, PendingThreadCreationOutcome>>
99>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:pending-thread-creation:outcomes"));
100
101export function recordPendingThreadCreationOutcome(outcome: PendingThreadCreationOutcome): void {
102 const key = scopedThreadKey(outcome.message.environmentId, outcome.message.threadId);
103 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {
104 ...appAtomRegistry.get(pendingThreadCreationOutcomesAtom),
105 [key]: outcome,
106 });
107}
108
109export function clearPendingThreadCreationOutcome(threadKey: string): void {
110 const current = appAtomRegistry.get(pendingThreadCreationOutcomesAtom);
111 if (!current[threadKey]) {
112 return;
113 }
114 const next = { ...current };
115 delete next[threadKey];
116 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, next);
117}
118
119/** Thread shell and empty detail precede the prompt: worktree setup runs between creation and turn start. */
120export function isPendingThreadCreationVisible(input: {
121 readonly creationMessageId: string;
122 readonly loadedMessageIds: ReadonlyArray<string> | null;
123}): boolean {
124 return !input.loadedMessageIds?.includes(input.creationMessageId);
125}
126
127export function pendingThreadCreationMessage(message: QueuedThreadMessage): LocalThreadMessage {
128 return {
129 id: message.messageId,
130 role: "user",
131 text: message.text,
132 context: message.context,
133 // Local draft ids cannot resolve server-side and would spin forever on rejected creation.
134 streaming: false,
135 createdAt: message.createdAt,
136 updatedAt: message.createdAt,
137 };
138}
139
140export function pendingThreadCreationShell(
141 message: QueuedThreadMessage,
142): EnvironmentThreadShell | null {
143 const creation = message.creation;
144 if (!creation || !message.modelSelection) {
145 return null;
146 }
147 const timestamp = DateTime.makeUnsafe(message.createdAt);
148 return presentThreadShell(message.environmentId, {
149 id: message.threadId,
150 projectId: creation.projectId,
151 title: deriveThreadTitleFromPrompt(message.text),
152 providerInstanceId: message.modelSelection.instanceId,
153 modelSelection: message.modelSelection,
154 runtimeMode: message.runtimeMode ?? DEFAULT_RUNTIME_MODE,
155 interactionMode: message.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
156 branch: creation.branch,
157 pullRequests: [],
158 worktreePath: creation.workspaceMode === "worktree" ? null : creation.worktreePath,
159 linkedPullRequest: null,
160 branchPullRequest: null,
161 lineage: { rootThreadId: message.threadId, parentThreadId: null, relationshipToParent: null },
162 forkedFrom: null,
163 createdBy: "user",
164 creationSource: "mobile",
165 activeProviderThreadId: null,
166 latestRunId: null,
167 activeRunId: null,
168 status: "preparing",
169 pendingRuntimeRequest: null,
170 latestVisibleMessage: null,
171 latestUserMessageAt: timestamp,
172 hasActionableProposedPlan: false,
173 itemCount: 0,
174 visibleItemCount: 0,
175 createdAt: timestamp,
176 updatedAt: timestamp,
177 archivedAt: null,
178 settledOverride: null,
179 settledAt: null,
180 unsettledAt: null,
181 snoozedUntil: null,
182 snoozedAt: null,
183 pinnedAt: null,
184 pinOrderKey: null,
185 activeOrderKey: null,
186 deletedAt: null,
187 });
188}