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