Skip to content

Commit a0efdae

Browse files
fix: new threads move from draft to Working in one step (#33783)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 1161141 commit a0efdae

16 files changed

Lines changed: 315 additions & 17 deletions

‎apps/mobile/src/features/home/HomeRouteScreen.tsx‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616

1717
import { useProjects } from "../../state/entities";
1818
import { environmentThreadShells } from "../../state/threads";
19-
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
19+
import { useLaunchingThreads, usePendingNewTasks } from "../../state/use-pending-new-tasks";
2020
import { useWorkspaceState } from "../../state/workspace";
2121
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
2222
import {
@@ -46,9 +46,8 @@ export function HomeRouteScreen() {
4646
const projects = useProjects();
4747
// Stop rebuilding the streaming thread list while Thread covers Home.
4848
const visible = useHomeRouteVisible();
49-
const threads = useAtomValueWhileVisible(
50-
environmentThreadShells.navigationThreadShellsAtom,
51-
visible,
49+
const threads = useLaunchingThreads(
50+
useAtomValueWhileVisible(environmentThreadShells.navigationThreadShellsAtom, visible),
5251
);
5352
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
5453
const { savedConnectionsById } = useSavedRemoteConnections();

‎apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@ import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-pref
3232
import { useThreadListNow } from "./use-thread-list-now";
3333
import { usePendingThreadOrder } from "../../state/thread-order";
3434
import { threadListEnvironmentsAtom } from "../../state/presentation";
35-
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
35+
import {
36+
useLaunchingThreads,
37+
usePendingNewTasks,
38+
type PendingNewTask,
39+
} from "../../state/use-pending-new-tasks";
3640
import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
3741
import { useWorkspaceState } from "../../state/workspace";
3842
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -136,6 +140,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
136140
regenerateThreadTitle,
137141
} = useThreadListActions();
138142
const pendingTasks = usePendingNewTasks();
143+
const launchingThreads = useLaunchingThreads(threads);
139144
const activeNewTask = useActiveNewTask();
140145
const queuedThreadKeys = useQueuedThreadKeys();
141146
const selectDetail = useSelectWorkspaceDetail();
@@ -264,7 +269,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
264269
contentOnlyThreadKeys,
265270
olderSettledShelf,
266271
} = useThreadListV2({
267-
threads,
272+
threads: launchingThreads,
268273
pendingTasks,
269274
environmentId: options.selectedEnvironmentId,
270275
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,

‎apps/mobile/src/state/composer-attachment-uploads.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ vi.mock("./use-thread-outbox", async () => {
170170
dispatchingQueuedMessageIdAtom: Atom.make<Record<string, string>>({}).pipe(Atom.keepAlive),
171171
useThreadOutboxMessages: () =>
172172
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
173+
retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
173174
threadOutboxShellStatusesAtom: Atom.make(new Map()),
174175
};
175176
});

‎apps/mobile/src/state/pending-new-tasks-model.test.ts‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
1-
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
1+
import {
2+
CommandId,
3+
EnvironmentId,
4+
MessageId,
5+
ProjectId,
6+
ProviderInstanceId,
7+
ThreadId,
8+
} from "@t3tools/contracts";
29
import { describe, expect, it } from "vite-plus/test";
310

411
import {
12+
buildPendingNewTasks,
513
type PendingDraftProjectDefaults,
614
pendingDraftBranchNeedsRefs,
715
resolvePendingDraftBranch,
816
} from "./pending-new-tasks-model";
17+
import type { QueuedThreadMessage } from "./thread-outbox-model";
918
import type { ComposerDraft, ComposerDraftWorkspaceSelection } from "./use-composer-drafts";
1019

1120
const projectCwd = "/repo";
@@ -82,3 +91,55 @@ describe("resolvePendingDraftBranch", () => {
8291
expect(resolve({ draft: chosen, branches, projectCwd })).toBe("release");
8392
});
8493
});
94+
95+
function queuedCreation(environmentId: string): QueuedThreadMessage {
96+
return {
97+
environmentId: EnvironmentId.make(environmentId),
98+
threadId: ThreadId.make(`thread-${environmentId}`),
99+
messageId: MessageId.make(`message-${environmentId}`),
100+
commandId: CommandId.make(`command-${environmentId}`),
101+
text: "Test",
102+
attachments: [],
103+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },
104+
creation: {
105+
projectId: ProjectId.make("project-1"),
106+
workspaceMode: "local",
107+
branch: null,
108+
worktreePath: null,
109+
},
110+
createdAt: "2026-11-10T01:10:00.000Z",
111+
};
112+
}
113+
114+
describe("buildPendingNewTasks", () => {
115+
it("lists only creations the outbox is not sending yet", () => {
116+
const sending = EnvironmentId.make("sending");
117+
const syncing = EnvironmentId.make("syncing");
118+
const readOnly = EnvironmentId.make("read-only");
119+
const retrying = EnvironmentId.make("retrying");
120+
const { modelSelection: _model, ...modelless } = queuedCreation("sending");
121+
const tasks = buildPendingNewTasks({
122+
queuedMessages: [
123+
...["sending", "syncing", "read-only", "retrying", "offline"].map(queuedCreation),
124+
{ ...modelless, messageId: MessageId.make("message-modelless") },
125+
],
126+
drafts: {},
127+
sendGate: {
128+
connectedEnvironmentIds: new Set([sending, syncing, readOnly, retrying]),
129+
operableEnvironmentIds: new Set([sending, syncing, retrying]),
130+
shellStatuses: new Map([
131+
[sending, "live"],
132+
[syncing, "synchronizing"],
133+
[readOnly, "live"],
134+
[retrying, "live"],
135+
]),
136+
retryingMessageIds: { [MessageId.make("message-retrying")]: true },
137+
},
138+
});
139+
140+
expect(tasks).toHaveLength(5);
141+
expect(new Set(tasks.map((task) => task.environmentId))).toEqual(
142+
new Set(["syncing", "read-only", "retrying", "offline", "sending"]),
143+
);
144+
});
145+
});

‎apps/mobile/src/state/pending-new-tasks-model.ts‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1-
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
1+
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
2+
import type { EnvironmentId, MessageId, ProjectId } from "@t3tools/contracts";
23

34
import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
4-
import type { QueuedThreadCreation, QueuedThreadMessage } from "./thread-outbox-model";
5+
import {
6+
isQueuedThreadCreationSendable,
7+
resolveThreadOutboxDeliveryAction,
8+
type QueuedThreadCreation,
9+
type QueuedThreadMessage,
10+
} from "./thread-outbox-model";
511
import { isNewTaskDraftKey } from "./new-task-draft-key";
612
import type { ComposerDraft } from "./use-composer-drafts";
713
import { resolveNewTaskDraftWorkspace } from "../features/threads/new-task-context-presentation";
@@ -85,13 +91,41 @@ export function resolvePendingDraftBranch(input: {
8591
}).branch;
8692
}
8793

94+
export interface ThreadOutboxSendGate {
95+
readonly connectedEnvironmentIds: ReadonlySet<EnvironmentId>;
96+
readonly operableEnvironmentIds: ReadonlySet<EnvironmentId>;
97+
readonly shellStatuses: ReadonlyMap<EnvironmentId, EnvironmentShellStatus>;
98+
readonly retryingMessageIds: Readonly<Partial<Record<MessageId, true>>>;
99+
}
100+
101+
/** The outbox drain's gate for a creation: sendable, connected, shell live, operate granted, not backing off. */
102+
export function isQueuedCreationSending(
103+
message: QueuedThreadMessage,
104+
gate: ThreadOutboxSendGate,
105+
): boolean {
106+
const environmentId = message.environmentId;
107+
return (
108+
isQueuedThreadCreationSendable(message) &&
109+
gate.retryingMessageIds[message.messageId] !== true &&
110+
gate.operableEnvironmentIds.has(environmentId) &&
111+
resolveThreadOutboxDeliveryAction({
112+
isCreation: true,
113+
threadExists: false,
114+
shellStatus: gate.shellStatuses.get(environmentId) ?? "empty",
115+
environmentConnected: gate.connectedEnvironmentIds.has(environmentId),
116+
}) === "send"
117+
);
118+
}
119+
88120
export function buildPendingNewTasks(input: {
89121
readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
90122
readonly drafts: Readonly<Record<string, ComposerDraft>>;
123+
readonly sendGate: ThreadOutboxSendGate;
91124
}): ReadonlyArray<PendingNewTask> {
92125
const tasks: PendingNewTask[] = [];
93126
for (const message of input.queuedMessages) {
94-
if (!message.creation) {
127+
// Listing a creation already being sent would flash an "Unsent" row.
128+
if (!message.creation || isQueuedCreationSending(message, input.sendGate)) {
95129
continue;
96130
}
97131
tasks.push({

‎apps/mobile/src/state/pending-thread-creation.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,17 @@ import {
44
MessageId,
55
ProjectId,
66
ProviderInstanceId,
7+
RunId,
78
ThreadId,
89
} from "@t3tools/contracts";
10+
import { isThreadWorking } from "@t3tools/client-runtime/state/thread-inbox";
911
import { describe, expect, it } from "vite-plus/test";
1012

1113
import {
14+
pendingThreadCreationShell,
1215
resolvePendingThreadCreation,
1316
selectThreadCreationDetail,
17+
withLaunchingThreads,
1418
type PendingThreadCreation,
1519
} from "./pending-thread-creation";
1620
import type { QueuedThreadMessage } from "./thread-outbox-model";
@@ -186,3 +190,30 @@ describe("selectThreadCreationDetail", () => {
186190
).toEqual({ pendingCreation: null, detailRef: threadRef });
187191
});
188192
});
193+
194+
describe("withLaunchingThreads", () => {
195+
it("reads as working from Send until the thread's first run arrives", () => {
196+
const launch = (threads: Parameters<typeof withLaunchingThreads>[0]["threads"]) =>
197+
withLaunchingThreads({ threads, launches: [creation], hiddenThreadKeys: new Set() });
198+
// Before the shell arrives, and after the server commits the thread without its run.
199+
const created = { ...pendingThreadCreationShell(creation)!, title: "Server title" };
200+
for (const threads of [launch([]), launch([created])]) {
201+
expect(threads).toHaveLength(1);
202+
expect(isThreadWorking(threads[0]!)).toBe(true);
203+
}
204+
expect(launch([created])[0]!.title).toBe("Server title");
205+
206+
const started = {
207+
...created,
208+
latestRun: {
209+
runId: RunId.make("run-1"),
210+
status: "completed" as const,
211+
requestedAt: null,
212+
startedAt: null,
213+
completedAt: null,
214+
assistantMessageId: null,
215+
},
216+
};
217+
expect(launch([started])[0]).toBe(started);
218+
});
219+
});

‎apps/mobile/src/state/pending-thread-creation.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import {
44
} from "@t3tools/client-runtime/state/shell";
55
import type { LocalThreadMessage } from "../lib/threadActivity";
66
import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts";
7+
import { threadKey } from "@t3tools/client-runtime/state/entities";
8+
import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox";
79
import { Atom } from "effect/reactivity";
810
import * as DateTime from "effect/DateTime";
911

@@ -133,6 +135,33 @@ export function pendingThreadCreationMessage(message: QueuedThreadMessage): Loca
133135
};
134136
}
135137

138+
/** Launches show as preparing from Send, before the server's shell exists, until their first run. */
139+
export function withLaunchingThreads(input: {
140+
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
141+
readonly launches: ReadonlyArray<QueuedThreadMessage>;
142+
readonly hiddenThreadKeys: ReadonlySet<string>;
143+
}): ReadonlyArray<EnvironmentThreadShell> {
144+
if (input.launches.length === 0) return input.threads;
145+
const launchByKey = new Map<string, QueuedThreadMessage>();
146+
for (const message of input.launches) {
147+
if (!message.creation || input.hiddenThreadKeys.has(threadKey(message))) continue;
148+
launchByKey.set(scopedThreadKey(message.environmentId, message.threadId), message);
149+
}
150+
if (launchByKey.size === 0) return input.threads;
151+
const threads = input.threads.map((thread) => {
152+
const key = scopedThreadKey(thread.environmentId, thread.id);
153+
const launch = launchByKey.get(key);
154+
if (!launch) return thread;
155+
launchByKey.delete(key);
156+
return asLaunchingThread(thread);
157+
});
158+
for (const launch of launchByKey.values()) {
159+
const shell = pendingThreadCreationShell(launch);
160+
if (shell) threads.push(asLaunchingThread(shell));
161+
}
162+
return threads;
163+
}
164+
136165
export function pendingThreadCreationShell(
137166
message: QueuedThreadMessage,
138167
): EnvironmentThreadShell | null {

‎apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ vi.mock("./use-thread-outbox", async () => {
136136
return {
137137
editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
138138
dispatchingQueuedMessageIdAtom: Atom.make<MessageId | null>(null).pipe(Atom.keepAlive),
139+
retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
139140
threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])),
140141
};
141142
});

‎apps/mobile/src/state/threadOutboxDelivery.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ vi.mock("./use-thread-outbox", async () => {
120120
return {
121121
editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
122122
dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive),
123+
retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
123124
threadOutboxShellStatusesAtom: Atom.make(new Map()),
124125
};
125126
});

‎apps/mobile/src/state/threadOutboxDelivery.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ import {
8787
import {
8888
dispatchingQueuedMessageIdAtom,
8989
editingQueuedMessageIdsAtom,
90+
retryingQueuedMessageIdsAtom,
9091
threadOutboxShellStatusesAtom,
9192
} from "./use-thread-outbox";
9293
import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
@@ -155,7 +156,20 @@ function logThreadOutboxUploadFailure(queuedMessage: QueuedThreadMessage, error:
155156
}
156157
}
157158

159+
function setQueuedMessageRetrying(queuedMessageId: MessageId, retrying: boolean): void {
160+
const { [queuedMessageId]: current, ...others } = appAtomRegistry.get(
161+
retryingQueuedMessageIdsAtom,
162+
);
163+
if ((current === true) === retrying) return;
164+
appAtomRegistry.set(
165+
retryingQueuedMessageIdsAtom,
166+
retrying ? { ...others, [queuedMessageId]: true } : others,
167+
);
168+
}
169+
158170
function beginDispatchingQueuedMessage(queuedMessageId: MessageId): void {
171+
// An attempt in flight is sending, even while its retry count is kept.
172+
setQueuedMessageRetrying(queuedMessageId, false);
159173
appAtomRegistry.set(dispatchingQueuedMessageIdAtom, queuedMessageId);
160174
}
161175

@@ -701,13 +715,15 @@ export function createThreadOutboxDelivery(): {
701715
notBefore: Date.now() + delayMs,
702716
timer: setTimeout(drain, delayMs),
703717
});
718+
setQueuedMessageRetrying(messageId, true);
704719
};
705720

706721
const clearRetry = (messageId: MessageId): void => {
707722
const retry = retries.get(messageId);
708723
if (retry === undefined) return;
709724
clearTimeout(retry.timer);
710725
retries.delete(messageId);
726+
setQueuedMessageRetrying(messageId, false);
711727
};
712728

713729
// A delivery that throws backs off like any failure. Releasing the slot
@@ -1412,6 +1428,7 @@ export function createThreadOutboxDelivery(): {
14121428
stopCollectingOutcomes();
14131429
for (const retry of retries.values()) clearTimeout(retry.timer);
14141430
retries.clear();
1431+
appAtomRegistry.set(retryingQueuedMessageIdsAtom, {});
14151432
for (const blocked of blockedRecoveries.values()) blocked.unsubscribe();
14161433
blockedRecoveries.clear();
14171434
for (const release of familyMounts.values()) release();

0 commit comments

Comments
 (0)