Skip to content

Commit 04c0791

Browse files
t3dotggclaude
andcommitted
Address round-2 stack review: queued turns, capability gating, races
- Queued turn starts are unsettleable: new hasQueuedTurnStart (client) detects a user message no turn has picked up (newest user message strictly newer than every latestTurn timestamp; a failed session start clears the block); canSettle and effectiveSettled refuse it, and the decider enforces the same invariant server-side, so just-requested work can be neither settled nor auto-settled by a closed PR. - Capability-aware classification: threads on environments without threadSettlement (old server, or descriptor not yet loaded) never partition into the settled tail on web or mobile — a tail with no working un-settle/pin affordances was strandable. Unknown is treated as unsupported. - Post-settle navigation validates the CURRENT route before firing: a navigation made while the settle was in flight wins. - Scope flips clear the thread selection, and the bulk context menu derives one exact actionable set (rendered rows only) so labels count exactly what actions will touch. - Settle/unsettle re-emissions are projected no-ops: duplicates keep the existing updatedAt instead of churning ordering. - Web settle-blocked failures use a settlement-specific error matching mobile copy instead of ThreadArchiveBlockedError's archive wording. - New coverage: queued-turn tests (client + decider), settled event round-trip through the DB ProjectionPipeline, capability-gated partition fixtures. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent afcce06 commit 04c0791

10 files changed

Lines changed: 297 additions & 22 deletions

File tree

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import type { SavedRemoteConnection } from "../../lib/connection";
2727
import { scopedProjectKey } from "../../lib/scopedEntities";
2828
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
2929
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
30+
import { environmentServerConfigsAtom } from "../../state/server";
3031
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
3132
import {
3233
PendingTaskListRow,
@@ -345,6 +346,18 @@ export function HomeScreen(props: HomeScreenProps) {
345346
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
346347
return () => clearInterval(id);
347348
}, [threadListV2Enabled]);
349+
// Threads on servers without the settlement capability never classify as
350+
// settled (the user could neither un-settle nor pin them).
351+
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
352+
const settlementEnvironmentIds = useMemo(() => {
353+
const supported = new Set<EnvironmentId>();
354+
for (const [environmentId, config] of serverConfigs) {
355+
if (config.environment.capabilities.threadSettlement === true) {
356+
supported.add(environmentId);
357+
}
358+
}
359+
return supported;
360+
}, [serverConfigs]);
348361
const threadListV2Layout = useMemo(() => {
349362
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
350363
// Settled threads are live shells; archived threads keep their original
@@ -354,13 +367,15 @@ export function HomeScreen(props: HomeScreenProps) {
354367
environmentId: props.selectedEnvironmentId,
355368
searchQuery: props.searchQuery,
356369
changeRequestStateByKey,
370+
settlementEnvironmentIds,
357371
settledLimit: settledVisibleCount,
358372
now: `${nowMinute}:00.000Z`,
359373
});
360374
}, [
361375
changeRequestStateByKey,
362376
nowMinute,
363377
settledVisibleCount,
378+
settlementEnvironmentIds,
364379
props.searchQuery,
365380
props.selectedEnvironmentId,
366381
props.threads,

‎apps/mobile/src/features/home/useThreadListActions.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ function useThreadActionExecutor(
8585
}
8686
// Settle may only target what effectiveSettled could classify as
8787
// settled: not starting/running sessions, not threads waiting on
88-
// approvals or user input. Anything else would archive live work.
88+
// approvals or user input. Anything else would hide live work.
8989
if (action === "settle" && !canSettle(thread)) {
9090
Alert.alert(
9191
actionFailureTitle(action),

‎apps/mobile/src/features/threads/threadListV2.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2-
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2+
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
33
import { describe, expect, it } from "vite-plus/test";
44

55
import {
@@ -166,6 +166,16 @@ describe("buildThreadListV2Items settled paging", () => {
166166
settledOverride: "settled",
167167
settledAt: NOW,
168168
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
169+
// A turn adopted the message (same requestedAt): without it the
170+
// thread reads as a queued turn start, which never settles.
171+
latestTurn: {
172+
turnId: TurnId.make(`turn-${index}`),
173+
state: "completed",
174+
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
175+
startedAt: `2026-06-01T0${index}:00:00.000Z`,
176+
completedAt: `2026-06-01T0${index}:10:00.000Z`,
177+
assistantMessageId: null,
178+
},
169179
}),
170180
),
171181
];

‎apps/mobile/src/features/threads/threadListV2.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ export function buildThreadListV2Items(input: {
9292
readonly searchQuery: string;
9393
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
9494
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
95+
/** Environments whose server supports thread.settle/unsettle. Threads on
96+
other environments never classify as settled — the user could neither
97+
un-settle nor pin them. Absent = no gating (tests). */
98+
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
9599
readonly autoSettleAfterDays?: number;
96100
/** Max settled rows to render; the rest are counted, not built. */
97101
readonly settledLimit?: number;
@@ -109,9 +113,13 @@ export function buildThreadListV2Items(input: {
109113
// and partition into the tail via effectiveSettled.
110114
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
111115
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
116+
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
112117
const changeRequestState =
113118
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
114-
if (effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })) {
119+
if (
120+
supportsSettlement &&
121+
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
122+
) {
115123
settled.push(thread);
116124
} else {
117125
active.push(thread);

‎apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,70 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
171171
for (const row of stateRows) {
172172
assert.equal(row.lastAppliedSequence, 3);
173173
}
174+
175+
// Settled lifecycle through the DB pipeline: thread.settled writes the
176+
// override + timestamp, thread.unsettled(user) flips to the active pin.
177+
yield* eventStore.append({
178+
type: "thread.settled",
179+
eventId: EventId.make("evt-settle-1"),
180+
aggregateKind: "thread",
181+
aggregateId: ThreadId.make("thread-1"),
182+
occurredAt: "2026-01-01T00:00:01.000Z",
183+
commandId: CommandId.make("cmd-settle-1"),
184+
causationEventId: null,
185+
correlationId: CommandId.make("cmd-settle-1"),
186+
metadata: {},
187+
payload: {
188+
threadId: ThreadId.make("thread-1"),
189+
settledAt: "2026-01-01T00:00:01.000Z",
190+
updatedAt: "2026-01-01T00:00:01.000Z",
191+
},
192+
});
193+
yield* projectionPipeline.bootstrap;
194+
195+
const settledRows = yield* sql<{
196+
readonly settledOverride: string | null;
197+
readonly settledAt: string | null;
198+
}>`
199+
SELECT
200+
settled_override AS "settledOverride",
201+
settled_at AS "settledAt"
202+
FROM projection_threads
203+
WHERE thread_id = 'thread-1'
204+
`;
205+
assert.deepEqual(settledRows, [
206+
{ settledOverride: "settled", settledAt: "2026-01-01T00:00:01.000Z" },
207+
]);
208+
209+
yield* eventStore.append({
210+
type: "thread.unsettled",
211+
eventId: EventId.make("evt-unsettle-1"),
212+
aggregateKind: "thread",
213+
aggregateId: ThreadId.make("thread-1"),
214+
occurredAt: "2026-01-01T00:00:02.000Z",
215+
commandId: CommandId.make("cmd-unsettle-1"),
216+
causationEventId: null,
217+
correlationId: CommandId.make("cmd-unsettle-1"),
218+
metadata: {},
219+
payload: {
220+
threadId: ThreadId.make("thread-1"),
221+
reason: "user",
222+
updatedAt: "2026-01-01T00:00:02.000Z",
223+
},
224+
});
225+
yield* projectionPipeline.bootstrap;
226+
227+
const unsettledRows = yield* sql<{
228+
readonly settledOverride: string | null;
229+
readonly settledAt: string | null;
230+
}>`
231+
SELECT
232+
settled_override AS "settledOverride",
233+
settled_at AS "settledAt"
234+
FROM projection_threads
235+
WHERE thread_id = 'thread-1'
236+
`;
237+
assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]);
174238
}),
175239
);
176240
});

‎apps/server/src/orchestration/decider.ts‎

Lines changed: 49 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -348,14 +348,49 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
348348
}),
349349
);
350350
}
351+
// A queued turn start — a user message no turn has picked up yet — is
352+
// work in flight even though session is still null (turn.start emits
353+
// message-sent + turn-start-requested; the session arrives later).
354+
// Settling in that window would hide just-requested work. Detection
355+
// mirrors the client's hasQueuedTurnStart: the newest user message is
356+
// strictly newer than every latestTurn timestamp (adoption stamps the
357+
// new turn's requestedAt with the message time, clearing this). A
358+
// failed session start (status "error") clears the block so the
359+
// thread does not become permanently unsettleable.
360+
const latestUserMessageAtMs = thread.messages.reduce(
361+
(latest, message) =>
362+
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
363+
Number.NEGATIVE_INFINITY,
364+
);
365+
const latestTurnAtMs =
366+
thread.latestTurn === null
367+
? Number.NEGATIVE_INFINITY
368+
: Math.max(
369+
...[
370+
thread.latestTurn.requestedAt,
371+
thread.latestTurn.startedAt,
372+
thread.latestTurn.completedAt,
373+
].map((candidate) =>
374+
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
375+
),
376+
);
377+
const hasQueuedTurnStart =
378+
thread.session?.status !== "error" &&
379+
Number.isFinite(latestUserMessageAtMs) &&
380+
latestUserMessageAtMs > latestTurnAtMs;
381+
if (hasQueuedTurnStart) {
382+
return yield* Effect.fail(
383+
new OrchestrationCommandInvariantError({
384+
commandType: command.type,
385+
detail: `thread ${command.threadId} has a queued turn start and cannot be settled`,
386+
}),
387+
);
388+
}
351389
const occurredAt = yield* nowIso;
352390
// Settling an already-settled thread re-emits with the original
353391
// settledAt: the engine rejects zero-event commands, and bulk-settle /
354392
// double-click must stay silent no-ops rather than surface errors.
355-
const settledAt =
356-
thread.settledOverride === "settled" && thread.settledAt !== null
357-
? thread.settledAt
358-
: occurredAt;
393+
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
359394
return {
360395
...(yield* withEventBase({
361396
aggregateKind: "thread",
@@ -366,23 +401,25 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
366401
type: "thread.settled",
367402
payload: {
368403
threadId: command.threadId,
369-
settledAt,
370-
// Always the command time: a re-settle keeps the original
371-
// settledAt but must not rewind updatedAt (sorting and relative-
372-
// time labels key on it).
373-
updatedAt: occurredAt,
404+
settledAt: alreadySettled ? thread.settledAt : occurredAt,
405+
// A re-emission is a projected no-op: keep the existing updatedAt
406+
// so duplicate settles neither rewind nor churn ordering. A fresh
407+
// settle stamps the command time.
408+
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
374409
},
375410
};
376411
}
377412

378413
case "thread.unsettle": {
379-
yield* requireThreadNotArchived({
414+
const thread = yield* requireThreadNotArchived({
380415
readModel,
381416
command,
382417
threadId: command.threadId,
383418
});
384419
// Idempotent by re-emission (see thread.settle): reducing the event a
385-
// second time lands on the same override state.
420+
// second time lands on the same override state. A re-emission keeps
421+
// the existing updatedAt so duplicates do not churn ordering.
422+
const alreadyPinnedActive = thread.settledOverride === "active";
386423
const occurredAt = yield* nowIso;
387424
return {
388425
...(yield* withEventBase({
@@ -395,7 +432,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
395432
payload: {
396433
threadId: command.threadId,
397434
reason: command.reason,
398-
updatedAt: occurredAt,
435+
updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
399436
},
400437
};
401438
}

‎apps/web/src/components/SidebarV2.tsx‎

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ import {
5555
import { useClientSettings } from "../hooks/useSettings";
5656
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
5757
import { useProjects, useThreadShells } from "../state/entities";
58-
import { primaryServerKeybindingsAtom } from "../state/server";
58+
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
5959
import { vcsEnvironment } from "../state/vcs";
6060
import { threadEnvironment } from "../state/threads";
6161
import { useEnvironmentQuery } from "../state/query";
@@ -624,6 +624,11 @@ export default function SidebarV2() {
624624
select: (params) => resolveThreadRouteRef(params),
625625
});
626626
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
627+
// Post-settle navigation validates against the CURRENT route, not the one
628+
// captured when the settle started: if the user navigated elsewhere while
629+
// the command was in flight, completing it must not yank them away.
630+
const routeThreadKeyRef = useRef(routeThreadKey);
631+
routeThreadKeyRef.current = routeThreadKey;
627632

628633
const environmentLabelById = useMemo(
629634
() =>
@@ -711,11 +716,17 @@ export default function SidebarV2() {
711716
setProjectScopeKey(null);
712717
}
713718
}, [projectScopeKey, projects]);
719+
// Scope flips drop the selection: rows selected under the old scope may be
720+
// hidden now, and bulk actions must never count or touch invisible rows.
721+
useEffect(() => {
722+
clearSelection();
723+
}, [clearSelection, projectScopeKey]);
714724

715725
// Settled threads stay in the live shell stream (settled ≠ archived), so
716726
// the partition works directly off live shells: no archived-snapshot
717727
// merging, no optimistic holds. Archived threads remain hidden here —
718728
// archive keeps its original "remove from sidebar" meaning.
729+
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
719730
const { activeThreads, settledThreads } = useMemo(() => {
720731
const now = `${nowMinute}:00.000Z`;
721732
const visible = threads.filter(
@@ -728,9 +739,18 @@ export default function SidebarV2() {
728739
const active: EnvironmentThreadShell[] = [];
729740
const settled: EnvironmentThreadShell[] = [];
730741
for (const thread of visible) {
742+
// Threads on servers without the settlement capability (old server,
743+
// or descriptor not loaded yet) never classify as settled: the user
744+
// could neither un-settle nor pin them, so auto-settling them would
745+
// strand rows in a tail with no working affordances.
746+
const supportsSettlement =
747+
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true;
731748
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
732749
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
733-
if (effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })) {
750+
if (
751+
supportsSettlement &&
752+
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
753+
) {
734754
settled.push(thread);
735755
} else {
736756
active.push(thread);
@@ -744,7 +764,14 @@ export default function SidebarV2() {
744764
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
745765
),
746766
};
747-
}, [autoSettleAfterDays, changeRequestStateByKey, nowMinute, scopedProject, threads]);
767+
}, [
768+
autoSettleAfterDays,
769+
changeRequestStateByKey,
770+
nowMinute,
771+
scopedProject,
772+
serverConfigs,
773+
threads,
774+
]);
748775

749776
// The settled tail renders in pages: history shouldn't dominate the
750777
// sidebar, and the common lookups are recent. Expansion resets when the
@@ -959,7 +986,11 @@ export default function SidebarV2() {
959986
}
960987
return;
961988
}
962-
navigateAfterSettle?.();
989+
// Only move forward if the user is still on the settled thread —
990+
// a navigation made during the await wins over ours.
991+
if (routeThreadKeyRef.current === threadKey) {
992+
navigateAfterSettle?.();
993+
}
963994
} finally {
964995
settlingThreadKeysRef.current.delete(threadKey);
965996
}
@@ -991,7 +1022,13 @@ export default function SidebarV2() {
9911022
async (position: { x: number; y: number }) => {
9921023
const api = readLocalApi();
9931024
if (!api) return;
994-
const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys];
1025+
// One exact actionable set: keys whose rows are actually rendered
1026+
// right now. Selections can outlive their rows (settled-tail paging,
1027+
// thread deletion elsewhere) and the menu labels must count only what
1028+
// the actions will touch.
1029+
const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys].filter(
1030+
(threadKey) => threadByKeyRef.current.has(threadKey),
1031+
);
9951032
if (threadKeys.length === 0) return;
9961033
const count = threadKeys.length;
9971034
const clicked = await settlePromise(() =>

‎apps/web/src/hooks/useThreadActions.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,18 @@ export class ThreadSettlementUnsupportedError extends Schema.TaggedErrorClass<Th
5757
}
5858
}
5959

60+
export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSettleBlockedError>()(
61+
"ThreadSettleBlockedError",
62+
{
63+
environmentId: EnvironmentId,
64+
threadId: ThreadId,
65+
},
66+
) {
67+
override get message(): string {
68+
return "This thread still needs attention. Resolve or interrupt it first, then try again.";
69+
}
70+
}
71+
6072
export function useThreadActions() {
6173
const closeTerminal = useAtomCommand(terminalEnvironment.close);
6274
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
@@ -390,7 +402,7 @@ export function useThreadActions() {
390402
if (resolved && !canSettle(resolved.thread)) {
391403
return AsyncResult.failure(
392404
Cause.fail(
393-
new ThreadArchiveBlockedError({
405+
new ThreadSettleBlockedError({
394406
environmentId: resolved.threadRef.environmentId,
395407
threadId: resolved.threadRef.threadId,
396408
}),

0 commit comments

Comments
 (0)