Skip to content

Commit 0fdf7c9

Browse files
fix(sidebar): recover deferred settlement and preserve manual behavior
1 parent 30efc88 commit 0fdf7c9

19 files changed

Lines changed: 392 additions & 131 deletions

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

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -393,24 +393,33 @@ describe("buildThreadListV2Items", () => {
393393
expect(layout.items[0]?.variant).toBe("slim");
394394
});
395395

396-
it("files a thread waiting to settle when idle with the settled threads", () => {
397-
const thread = makeThread({
398-
id: ThreadId.make("settles-when-idle"),
399-
title: "Still working",
400-
settleWhenIdleAt: NOW,
401-
});
402-
const layout = buildThreadListV2Items({
403-
threads: [thread],
404-
environmentId: null,
405-
searchQuery: "",
406-
now: NOW,
407-
});
396+
it.each(["working", "monitoring"] as const)(
397+
"shows background %s on the settled shelf until it ends",
398+
(backgroundLiveness) => {
399+
const thread = makeThread({
400+
id: ThreadId.make("settles-when-idle"),
401+
title: "Still working",
402+
settleWhenIdleAt: NOW,
403+
backgroundLiveness,
404+
});
405+
const layout = buildThreadListV2Items({
406+
threads: [thread],
407+
environmentId: null,
408+
searchQuery: "",
409+
now: NOW,
410+
});
408411

409-
expect(layout.settledCount).toBe(1);
410-
expect(
411-
getThreadListV2OrderedSection({ threads: [thread], section: "active", now: NOW }),
412-
).toEqual([]);
413-
});
412+
expect(layout.settledCount).toBe(1);
413+
expect(layout.items[0]?.variant).toBe("slim");
414+
expect(resolveThreadListV2Status(thread)).toBe("working");
415+
expect(resolveThreadListV2Status({ ...thread, hasPendingApprovals: true })).toBe("approval");
416+
expect(resolveThreadListV2Status({ ...thread, hasPendingUserInput: true })).toBe("input");
417+
expect(resolveThreadListV2Status({ ...thread, backgroundLiveness: null })).toBe("ready");
418+
expect(
419+
getThreadListV2OrderedSection({ threads: [thread], section: "active", now: NOW }),
420+
).toEqual([]);
421+
},
422+
);
414423

415424
it("hides snoozed threads and counts them — visibility parity with web", () => {
416425
const layout = buildThreadListV2Items({

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,16 +118,24 @@ export function resolveThreadListV2SnoozeGateExpiryMs(
118118
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
119119
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
120120

121+
/** Attention requests outrank live session or background work, including on the settled shelf. */
121122
export function resolveThreadListV2Status(
122-
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
123+
thread: Pick<
124+
EnvironmentThreadShell,
125+
"hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
126+
>,
123127
): ThreadListV2Status {
124128
if (thread.hasPendingApprovals) {
125129
return "approval";
126130
}
127131
if (thread.hasPendingUserInput) {
128132
return "input";
129133
}
130-
if (thread.session?.status === "running" || thread.session?.status === "starting") {
134+
if (
135+
thread.session?.status === "running" ||
136+
thread.session?.status === "starting" ||
137+
thread.backgroundLiveness != null
138+
) {
131139
return "working";
132140
}
133141
if (thread.session?.status === "error") {

‎apps/mobile/src/state/use-thread-selection.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["
4949
return null;
5050
}
5151

52+
/** Build a navigation fallback from detail state, preserving pending lifecycle intents. */
5253
function threadDetailToShell(
5354
environmentId: EnvironmentId,
5455
thread: OrchestrationThread,

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3721,6 +3721,31 @@ it.effect("reads a full sweep from unsettled threads and every project", () => {
37213721
const unsettled = yield* query.getShellSnapshot({ unsettledOnly: true });
37223722
assert.deepStrictEqual(unsettled.threads, sweep.threads);
37233723
assert.strictEqual(unsettled.updatedAt, "2026-09-04T00:00:00Z");
3724+
3725+
// Recovery reads only persisted intents, including keep-active threads. Unrelated
3726+
// malformed thread/session/turn/link rows must never be hydrated by this query.
3727+
yield* sql`UPDATE projection_threads SET settle_when_idle_at = '2026-09-02T00:00:00Z'
3728+
WHERE thread_id IN ('t-open', 't-resumed', 't-branch', 't-archived')`;
3729+
yield* sql`UPDATE projection_threads SET deleted_at = '2026-09-03T00:00:00Z' WHERE thread_id = 't-branch'`;
3730+
yield* sql`UPDATE projection_threads SET model_selection_json = 'invalid-json' WHERE thread_id = 't-settled'`;
3731+
yield* sql`UPDATE projection_thread_sessions SET status = 'invalid' WHERE thread_id = 't-settled'`;
3732+
yield* sql`UPDATE projection_turns SET checkpoint_files_json = 'invalid-json' WHERE thread_id = 't-settled'`;
3733+
const recovery = yield* query.getShellSnapshot({ settleWhenIdleOnly: true });
3734+
assert.strictEqual(recovery.snapshotSequence, full.snapshotSequence);
3735+
assert.deepStrictEqual(
3736+
recovery.threads.map((thread) => thread.id),
3737+
["t-open", "t-resumed"],
3738+
);
3739+
assert.strictEqual(recovery.threads[0]?.session?.status, "ready");
3740+
assert.strictEqual(recovery.threads[0]?.latestTurn?.turnId, asTurnId("turn-open"));
3741+
assert.strictEqual(recovery.threads[0]?.pullRequests[0]?.number, 7);
3742+
assert.strictEqual(recovery.threads[1]?.settledOverride, "active");
3743+
assert.strictEqual(recovery.updatedAt, "2026-09-04T00:00:00Z");
3744+
yield* sql`UPDATE projection_threads SET settle_when_idle_at = NULL WHERE thread_id IN ('t-open', 't-resumed')`;
3745+
assert.deepStrictEqual(
3746+
(yield* query.getShellSnapshot({ settleWhenIdleOnly: true })).threads,
3747+
[],
3748+
);
37243749
}).pipe(Effect.provide(layer));
37253750
});
37263751

‎apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts‎

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,10 @@ const EventReplayStatsRowSchema = Schema.Struct({
185185
eventCount: Schema.Number,
186186
payloadBytes: Schema.Number,
187187
});
188-
const ActiveThreadRowsRequest = Schema.Struct({ unsettledOnly: Schema.Boolean });
188+
const ActiveThreadRowsRequest = Schema.Struct({
189+
unsettledOnly: Schema.Boolean,
190+
settleWhenIdleOnly: Schema.Boolean,
191+
});
189192
const ProjectionThreadSearchRequest = Schema.Struct({
190193
pattern: Schema.String,
191194
limit: Schema.Int,
@@ -602,11 +605,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
602605
`,
603606
});
604607

605-
// Background sweeps skip settled threads, the same check PR discovery makes.
606-
const unsettledThreadsFilter = (unsettledOnly: boolean) =>
607-
unsettledOnly
608-
? sql`AND threads.settled_at IS NULL AND threads.settled_override IS NOT 'settled'`
609-
: sql``;
608+
/** Apply sweep filters to threads and every joined row, keeping recovery reads narrow. */
609+
const activeThreadsFilter = (request: typeof ActiveThreadRowsRequest.Type) => sql`
610+
${request.unsettledOnly ? sql`AND threads.settled_at IS NULL AND threads.settled_override IS NOT 'settled'` : sql``}
611+
${request.settleWhenIdleOnly ? sql`AND threads.settle_when_idle_at IS NOT NULL` : sql``}
612+
`;
610613

611614
const listActiveThreadRows = SqlSchema.findAll({
612615
Request: ActiveThreadRowsRequest,
@@ -649,7 +652,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
649652
FROM projection_threads threads
650653
WHERE deleted_at IS NULL
651654
AND archived_at IS NULL
652-
${unsettledThreadsFilter(request.unsettledOnly)}
655+
${activeThreadsFilter(request)}
653656
ORDER BY project_id ASC, created_at ASC, thread_id ASC
654657
`,
655658
});
@@ -809,7 +812,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
809812
ON threads.thread_id = links.thread_id
810813
WHERE threads.deleted_at IS NULL
811814
AND threads.archived_at IS NULL
812-
${unsettledThreadsFilter(request.unsettledOnly)}
815+
${activeThreadsFilter(request)}
813816
ORDER BY links.thread_id ASC, links.linked_at ASC, links.number ASC
814817
`,
815818
});
@@ -939,7 +942,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
939942
ON threads.thread_id = sessions.thread_id
940943
WHERE threads.deleted_at IS NULL
941944
AND threads.archived_at IS NULL
942-
${unsettledThreadsFilter(request.unsettledOnly)}
945+
${activeThreadsFilter(request)}
943946
ORDER BY sessions.thread_id ASC
944947
`,
945948
});
@@ -1035,7 +1038,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
10351038
WHERE threads.deleted_at IS NULL
10361039
AND threads.archived_at IS NULL
10371040
AND threads.latest_turn_id IS NOT NULL
1038-
${unsettledThreadsFilter(request.unsettledOnly)}
1041+
${activeThreadsFilter(request)}
10391042
ORDER BY turns.thread_id ASC
10401043
`,
10411044
});
@@ -2111,6 +2114,7 @@ pending_approval_requests AS (
21112114
`,
21122115
});
21132116

2117+
/** Read complete persisted orchestration state for consumers that need thread bodies. */
21142118
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
21152119
sql
21162120
.withTransaction(
@@ -2671,8 +2675,12 @@ pending_approval_requests AS (
26712675
}),
26722676
);
26732677

2678+
/** Read navigation state or a filtered recovery snapshot with a consistent sequence guard. */
26742679
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = (options) => {
2675-
const unsettledOnly = options?.unsettledOnly === true;
2680+
const request = {
2681+
unsettledOnly: options?.unsettledOnly === true,
2682+
settleWhenIdleOnly: options?.settleWhenIdleOnly === true,
2683+
};
26762684
return sql
26772685
.withTransaction(
26782686
Effect.all([
@@ -2684,31 +2692,31 @@ pending_approval_requests AS (
26842692
),
26852693
),
26862694
),
2687-
listActiveThreadRows({ unsettledOnly }).pipe(
2695+
listActiveThreadRows(request).pipe(
26882696
Effect.mapError(
26892697
toPersistenceSqlOrDecodeError(
26902698
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
26912699
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows",
26922700
),
26932701
),
26942702
),
2695-
listActiveThreadSessionRows({ unsettledOnly }).pipe(
2703+
listActiveThreadSessionRows(request).pipe(
26962704
Effect.mapError(
26972705
toPersistenceSqlOrDecodeError(
26982706
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
26992707
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows",
27002708
),
27012709
),
27022710
),
2703-
listActiveThreadPullRequestRows({ unsettledOnly }).pipe(
2711+
listActiveThreadPullRequestRows(request).pipe(
27042712
Effect.mapError(
27052713
toPersistenceSqlOrDecodeError(
27062714
"ProjectionSnapshotQuery.getShellSnapshot:listThreadPullRequests:query",
27072715
"ProjectionSnapshotQuery.getShellSnapshot:listThreadPullRequests:decodeRows",
27082716
),
27092717
),
27102718
),
2711-
listActiveLatestTurnRows({ unsettledOnly }).pipe(
2719+
listActiveLatestTurnRows(request).pipe(
27122720
Effect.mapError(
27132721
toPersistenceSqlOrDecodeError(
27142722
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
@@ -2862,6 +2870,7 @@ pending_approval_requests AS (
28622870
),
28632871
);
28642872

2873+
/** Read archived navigation rows separately from active-client and recovery snapshots. */
28652874
const getArchivedShellSnapshot: ProjectionSnapshotQueryShape["getArchivedShellSnapshot"] = () =>
28662875
sql
28672876
.withTransaction(
@@ -3270,6 +3279,7 @@ pending_approval_requests AS (
32703279
});
32713280
});
32723281

3282+
/** Read one thread's lifecycle and live-work state without loading its conversation history. */
32733283
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
32743284
Effect.gen(function* () {
32753285
const [threadRow, latestTurnRow, sessionRow, pullRequestRows] = yield* Effect.all([

‎apps/server/src/orchestration/Normalizer.settle.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { expect, it } from "@effect/vitest";
33
import {
44
CommandId,
5+
EventId,
56
ProjectId,
67
ProviderInstanceId,
78
ThreadId,
@@ -14,6 +15,7 @@ import * as Option from "effect/Option";
1415
import * as ServerConfig from "../config.ts";
1516
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
1617
import { normalizeDispatchCommand } from "./Normalizer.ts";
18+
import { decideOrchestrationCommand } from "./decider.ts";
1719
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
1820

1921
const NOW = "2026-08-28T12:00:00.000Z";
@@ -61,6 +63,8 @@ const threads = [
6163
makeThread("running", { session: { ...idle.session!, status: "running" } }),
6264
// The turn ended, but a watch loop still runs.
6365
makeThread("watching", { backgroundLiveness: "monitoring" }),
66+
makeThread("question", { hasPendingUserInput: true }),
67+
makeThread("approval", { hasPendingApprovals: true }),
6468
];
6569

6670
const testLayer = Layer.mergeAll(
@@ -86,4 +90,71 @@ it.layer(testLayer)("normalizeDispatchCommand settle", (it) => {
8690
expect(yield* settle("watching")).toBe("thread.settle-when-idle");
8791
}),
8892
);
93+
94+
it.effect(
95+
"preserves manual dismissal of message questions while blocking native questions and approvals",
96+
() =>
97+
Effect.gen(function* () {
98+
for (const request of ["message", "native", "approval"] as const) {
99+
const shell = threads.find(
100+
(thread) => thread.id === (request === "approval" ? "approval" : "question"),
101+
)!;
102+
const command = yield* normalizeDispatchCommand({
103+
type: "thread.settle",
104+
commandId: CommandId.make(`settle-${request}`),
105+
threadId: shell.id,
106+
});
107+
expect(command.type).toBe("thread.settle");
108+
const decision = decideOrchestrationCommand({
109+
command,
110+
readModel: {
111+
snapshotSequence: 0,
112+
projects: [],
113+
updatedAt: NOW,
114+
threads: [
115+
{
116+
...shell,
117+
deletedAt: null,
118+
messages: [],
119+
checkpoints: [],
120+
proposedPlans: [],
121+
activities: [
122+
{
123+
id: EventId.make(`request-${request}`),
124+
kind: request === "approval" ? "approval.requested" : "user-input.requested",
125+
summary: "Response needed",
126+
tone: "approval",
127+
turnId: null,
128+
createdAt: NOW,
129+
payload: {
130+
requestId: request,
131+
...(request === "message" ? { responseMode: "message" } : {}),
132+
},
133+
},
134+
],
135+
},
136+
],
137+
},
138+
});
139+
if (request !== "message") {
140+
expect((yield* decision.pipe(Effect.flip))._tag).toBe(
141+
"OrchestrationThreadSettleBlockedError",
142+
);
143+
continue;
144+
}
145+
const result = yield* decision;
146+
const events = Array.isArray(result) ? result : [result];
147+
expect(events.map((event) => event.type)).toEqual([
148+
"thread.settled",
149+
"thread.activity-appended",
150+
]);
151+
expect(events[1]?.payload).toMatchObject({
152+
activity: {
153+
kind: "user-input.resolved",
154+
payload: { requestId: "message", responseMode: "message" },
155+
},
156+
});
157+
}
158+
}),
159+
);
89160
});

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import { ServerConfig } from "../config.ts";
2424
import { parseBase64DataUrl } from "../imageMime.ts";
2525
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
2626
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
27-
import { isThreadIdleForSettlement } from "./ThreadSettlementPolicy.ts";
27+
import { isThreadWorkingForSettlement } from "./ThreadSettlementPolicy.ts";
2828

2929
export const canonicalizeClientCommandTimestamps = (
3030
command: ClientOrchestrationCommand,
@@ -77,6 +77,7 @@ const removeClaimedAttachmentPaths = Effect.fn("Normalizer.removeClaimedAttachme
7777
},
7878
);
7979

80+
/** Canonicalize client commands, claim attachments, and defer settlement only while work is live. */
8081
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
8182
Effect.gen(function* () {
8283
const receivedAt = DateTime.formatIso(yield* DateTime.now);
@@ -141,7 +142,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
141142
const thread = yield* snapshots
142143
.getThreadShellById(canonicalCommand.threadId)
143144
.pipe(Effect.orElseSucceed(() => Option.none()));
144-
if (Option.isSome(thread) && !isThreadIdleForSettlement(thread.value, receivedAt)) {
145+
if (Option.isSome(thread) && isThreadWorkingForSettlement(thread.value, receivedAt)) {
145146
return {
146147
...canonicalCommand,
147148
type: "thread.settle-when-idle",

‎apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ export interface ProjectionSnapshotQueryShape {
128128
*/
129129
readonly getShellSnapshot: (options?: {
130130
readonly unsettledOnly?: boolean;
131+
/** Recover explicit deferred intents without reading unrelated thread state. */
132+
readonly settleWhenIdleOnly?: boolean;
131133
}) => Effect.Effect<OrchestrationShellSnapshot, ProjectionRepositoryError>;
132134

133135
/**

0 commit comments

Comments
 (0)