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 resolvePendingThreadCreation(input: {
25 readonly threadKey: string | null;
26 readonly pending: PendingThreadCreation | null;
27 readonly previous: PendingThreadCreation | null;
28 readonly detail: {
29 readonly messages: ReadonlyArray<{ readonly id: string }>;
30 readonly runs?: ReadonlyArray<{ readonly status: string }>;
31 readonly latestTurn?: { readonly turnId: string } | null;
32 readonly session?: { readonly status: string } | null;
33 } | null;
34}): PendingThreadCreation | null {
35 const creation = input.pending ?? input.previous;
36 if (
37 creation === null ||
38 scopedThreadKey(creation.message.environmentId, creation.message.threadId) !== input.threadKey
39 ) {
40 return null;
41 }
42 if (creation.outcome?.kind === "failed") return creation;
43 const detail = input.detail;
44 const latestRun = detail?.runs?.at(-1);
45 const terminalStatus = latestRun?.status ?? detail?.session?.status;
46 if (
47 terminalStatus === "failed" ||
48 terminalStatus === "error" ||
49 terminalStatus === "cancelled" ||
50 terminalStatus === "stopped" ||
51 terminalStatus === "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.
56 if (
57 detail !== null &&
58 (latestRun !== undefined || detail.latestTurn != null) &&
59 !isPendingThreadCreationVisible({
60 creationMessageId: creation.message.messageId,
61 loadedMessageIds: detail.messages.map((message) => message.id),
62 })
63 ) {
64 return null;
65 }
66 return creation;
67}
68
69export const pendingThreadCreationOutcomesAtom = Atom.make<
70 Readonly<Record<string, PendingThreadCreationOutcome>>
71>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:pending-thread-creation:outcomes"));
72
73export function recordPendingThreadCreationOutcome(outcome: PendingThreadCreationOutcome): void {
74 const key = scopedThreadKey(outcome.message.environmentId, outcome.message.threadId);
75 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {
76 ...appAtomRegistry.get(pendingThreadCreationOutcomesAtom),
77 [key]: outcome,
78 });
79}
80
81export function clearPendingThreadCreationOutcome(threadKey: string): void {
82 const current = appAtomRegistry.get(pendingThreadCreationOutcomesAtom);
83 if (!current[threadKey]) {
84 return;
85 }
86 const next = { ...current };
87 delete next[threadKey];
88 appAtomRegistry.set(pendingThreadCreationOutcomesAtom, next);
89}
90
91/**
92 * The server creates the thread, then builds the worktree, and only then starts
93 * the turn, so the thread shell and an empty detail arrive seconds ahead of the
94 * prompt.
95 */
96export function isPendingThreadCreationVisible(input: {
97 readonly creationMessageId: string;
98 readonly loadedMessageIds: ReadonlyArray<string> | null;
99}): boolean {
100 return !input.loadedMessageIds?.includes(input.creationMessageId);
101}
102
103export function pendingThreadCreationMessage(message: QueuedThreadMessage): LocalThreadMessage {
104 return {
105 id: message.messageId,
106 role: "user",
107 text: message.text,
108 context: message.context,
109 // Deliberately no attachments. Their ids are local draft ids the server
110 // cannot resolve, so the feed's attachment rows would sit on a spinner that
111 // only ends when the real message arrives — and never, if the creation is
112 // rejected.
113 streaming: false,
114 createdAt: message.createdAt,
115 updatedAt: message.createdAt,
116 };
117}
118
119export function pendingThreadCreationShell(
120 message: QueuedThreadMessage,
121): EnvironmentThreadShell | null {
122 const creation = message.creation;
123 if (!creation || !message.modelSelection) {
124 return null;
125 }
126 const timestamp = DateTime.makeUnsafe(message.createdAt);
127 return presentThreadShell(message.environmentId, {
128 id: message.threadId,
129 projectId: creation.projectId,
130 title: deriveThreadTitleFromPrompt(message.text),
131 providerInstanceId: message.modelSelection.instanceId,
132 modelSelection: message.modelSelection,
133 runtimeMode: message.runtimeMode ?? DEFAULT_RUNTIME_MODE,
134 interactionMode: message.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
135 branch: creation.branch,
136 pullRequests: [],
137 worktreePath: creation.workspaceMode === "worktree" ? null : creation.worktreePath,
138 linkedPullRequest: null,
139 branchPullRequest: null,
140 lineage: { rootThreadId: message.threadId, parentThreadId: null, relationshipToParent: null },
141 forkedFrom: null,
142 createdBy: "user",
143 creationSource: "mobile",
144 activeProviderThreadId: null,
145 latestRunId: null,
146 activeRunId: null,
147 status: "preparing",
148 pendingRuntimeRequest: null,
149 latestVisibleMessage: null,
150 latestUserMessageAt: timestamp,
151 hasActionableProposedPlan: false,
152 itemCount: 0,
153 visibleItemCount: 0,
154 createdAt: timestamp,
155 updatedAt: timestamp,
156 archivedAt: null,
157 settledOverride: null,
158 settledAt: null,
159 unsettledAt: null,
160 snoozedUntil: null,
161 snoozedAt: null,
162 pinnedAt: null,
163 pinOrderKey: null,
164 activeOrderKey: null,
165 deletedAt: null,
166 });
167}