Skip to content

Commit 2f74ffb

Browse files
donjor-agent[bot]rsi-pr-agent
authored andcommitted
feat(terminal): choose zmux or plain per terminal and restore sessions on unsettle (#1699)
## Problem With **Managed zmux session** selected, a terminal opened by mouse started as a plain shell. Unsettling a thread did not bring its zmux session back. One Appearance setting mixed two choices: launch mode and automatic session creation. Before ([issue](#1697)): ![Mouse-opened Terminal 1 is a plain shell](https://github.com/user-attachments/assets/468bcbf3-07f9-488f-b7fd-649e55cdb193) ## Change ### Launch - **Click events:** no longer mean "open plain" - **Per terminal:** each carries its own mode - **Menus:** offer the other shell - **Server:** honors the per-terminal mode ### Settings New **Terminal** section in Settings: | Setting | Values | | --- | --- | | Default terminal | Plain shell, zmux shell | | Create zmux sessions automatically | on, off; follows the default until set | ### Settlement - **Unsettle:** eagerly recreates the session - **Gate:** the auto-create toggle - **Docs:** `managed-terminals.md` updated ## Scope and approval Closes #1697. Design decisions are recorded in the issue: eager recreate, one toggle, new Terminal section. Not built: the issue's "zmux session created" launch-timeline row. ## Close conditions ### Launch - [x] Mouse open: follows the default mode - [x] Keyboard open: follows the default mode - [x] Test: covers the click-event path - [x] Menus: offer zmux and plain shells ### Settings - [x] Launch mode: its own setting - [x] Auto-create: its own toggle - [x] Home: new Terminal section ### Settlement - [x] Unsettle: recreates the session eagerly - [x] Toggle off: unsettle creates nothing - [x] Docs: managed-terminals.md matches ## Verification Build `894fd10bab0`, isolated web dev server, scratch repo with one worktree thread. ### Checks | Check | Exit | | --- | --- | | `tsc` contracts, web, server | 0 | | Web tests (4 files, 28 tests) | 0 | | Server fork tests (3 files) | 0 | | Upstream client compat test | 0 | | Web and server builds | 0 | | `vp run fork:ci` | 0 | ### Settings ![Terminal settings section](https://github.com/user-attachments/assets/df5701e6-c1ca-4f1b-ac95-82de2f60d565) ### Launch Clip: click **Terminal** in the empty right panel, then **New plain shell** from the + menu. `echo "TMUX=[${TMUX%%,*}]"` prints the socket for zmux and `TMUX=[]` for plain. | Span | Real | Clip | | --- | --- | --- | | page settle | 1.5s | cut | | idle before menu | 5s | cut | | tail | 1.9s | cut | https://github.com/user-attachments/assets/c3ced7e1-a050-45fd-8eb5-726986c19c3c ![New-terminal menu offers New plain shell](https://github.com/user-attachments/assets/def6429a-9086-4616-b1f1-d9b54b1a9b3e) ![Plain shell prints TMUX=[]](https://github.com/user-attachments/assets/667db423-2730-435d-8c8c-8dbf69f3bfa3) ### Settlement Measured with `zmux ls` on the scratch project: | Toggle | Settle | Unsettle | | --- | --- | --- | | on | session removed | `zmux-proof/t3/reply-only-ok` recreated at the worktree | | off | session removed | no session | No console errors during the runs. Claude Opus 5.5 in Claude Code, hosted by T3 Code. ## Fork trailers Squashes: - aeed704 feat(terminal): choose zmux or plain per terminal and restore sessions on unsettle (#1699) (#1699) - 92d6a4a fixup! feat(terminal): choose zmux or plain per terminal and restore sessions on unsettle (#1699) (#1699) - 6a65388 feat(terminal): choose zmux or plain per terminal and restore sessions on unsettle (#1699) (#1699) - d4d07d5 fixup! feat(terminal): choose zmux or plain per terminal and restore sessions on unsettle (#1699) (#1699) - 807fff4 feat(terminal): choose zmux or plain per terminal and restore sessions on unsettle (#1699) (#1699) - ac65619 fixup! feat(terminal): choose zmux or plain per terminal and restore sessions on unsettle (#1699) (#1699) Fork-Domain: zmux-estate Fork-Tier: qol Fork-Upstreamable: no
1 parent de9176b commit 2f74ffb

31 files changed

Lines changed: 769 additions & 169 deletions

‎apps/server/src/terminal/Manager.fork.test.ts‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ it.layer(
116116
subprocessInspector: () =>
117117
Effect.succeed({ hasRunningSubprocess: false, childCommand: null, processIds: [] }),
118118
}).pipe(Effect.provideService(ProcessRunner.ProcessRunner, processRunner.service));
119-
const input = openInput({ attachmentId: "plain-viewer", plainShellFork: true });
119+
const input = openInput({ attachmentId: "plain-viewer", sessionModeFork: "shell" });
120120
yield* manager.open(input);
121121
const release = yield* manager.attachStream(input, () => Effect.void);
122122
yield* Effect.addFinalizer(() => Effect.sync(release));
@@ -135,6 +135,18 @@ it.layer(
135135
expect(ptyAdapter.spawnInputs[3]?.shell).toBe("zmux");
136136
}),
137137
);
138+
it.effect("opens a requested zmux shell when the default is a plain shell", () =>
139+
Effect.gen(function* () {
140+
const processRunner = resolvedZmuxProcessRunner();
141+
const { manager, ptyAdapter } = yield* createManager(5, {
142+
shellResolver: () => "/bin/bash",
143+
terminalSessionMode: "shell",
144+
}).pipe(Effect.provideService(ProcessRunner.ProcessRunner, processRunner.service));
145+
yield* manager.open(openInput({ worktreePath: process.cwd(), sessionModeFork: "zmux" }));
146+
yield* manager.open(openInput({ terminalId: "term-2", worktreePath: process.cwd() }));
147+
expect(ptyAdapter.spawnInputs.map((spawn) => spawn.shell)).toEqual(["zmux", "/bin/bash"]);
148+
}),
149+
);
138150
it.effect("uses fresh activity when deciding whether an unmanaged terminal can retarget", () =>
139151
Effect.gen(function* () {
140152
let running = false;
@@ -1510,6 +1522,56 @@ it.layer(
15101522
reopenedRelease();
15111523
}).pipe(Effect.provide(TestClock.layer())),
15121524
);
1525+
it.effect("keeps a chosen zmux mode through eviction under a plain shell default", () =>
1526+
Effect.gen(function* () {
1527+
const processRunner = resolvedZmuxProcessRunner();
1528+
const { manager, ptyAdapter } = yield* createManager(5, {
1529+
shellResolver: () => "/bin/bash",
1530+
terminalSessionMode: "shell",
1531+
managedAttachmentSuspendGraceMs: 10,
1532+
maxRetainedInactiveSessions: 1,
1533+
}).pipe(Effect.provideService(ProcessRunner.ProcessRunner, processRunner.service));
1534+
yield* Effect.addFinalizer(() =>
1535+
Effect.forEach(
1536+
["thread-1", "thread-2"],
1537+
(threadId) => manager.close({ threadId }).pipe(Effect.ignore),
1538+
{ discard: true },
1539+
),
1540+
);
1541+
const firstClosed = yield* Deferred.make<TerminalEvent>();
1542+
const suspended = yield* Ref.make<ReadonlyArray<string>>([]);
1543+
const unsubscribe = yield* manager.subscribe((event) =>
1544+
event.type === "closed" && event.threadId === "thread-1"
1545+
? Deferred.succeed(firstClosed, event).pipe(Effect.asVoid)
1546+
: event.type === "activity" && event.attachmentStatus === "suspended"
1547+
? Ref.update(suspended, (ids) => [...ids, event.threadId])
1548+
: Effect.void,
1549+
);
1550+
yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1551+
for (const threadId of ["thread-1", "thread-2"]) {
1552+
const release = yield* manager.attachStream(
1553+
openInput({ threadId, worktreePath: process.cwd(), sessionModeFork: "zmux" }),
1554+
() => Effect.void,
1555+
);
1556+
release();
1557+
yield* TestClock.adjust("10 millis");
1558+
}
1559+
yield* Deferred.await(firstClosed);
1560+
expect(yield* Ref.get(suspended)).toEqual(["thread-1", "thread-2"]);
1561+
const release = yield* manager.attachStream(
1562+
{ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID },
1563+
() => Effect.void,
1564+
);
1565+
expect(ptyAdapter.spawnInputs.at(-1)?.shell).toBe("zmux");
1566+
yield* manager.restart({
1567+
...openInput({ threadId: "thread-1", worktreePath: process.cwd() }),
1568+
cols: 100,
1569+
rows: 24,
1570+
});
1571+
expect(ptyAdapter.spawnInputs.at(-1)?.shell).toBe("zmux");
1572+
release();
1573+
}).pipe(Effect.provide(TestClock.layer())),
1574+
);
15131575
it.effect("bounds compact exact-target identities separately from full records", () =>
15141576
Effect.gen(function* () {
15151577
const processRunner = resolvedZmuxProcessRunner();

‎apps/server/src/terminal/Manager.ts‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClie
8383
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
8484
import * as ZmuxSessionBinder from "../zmux/ZmuxSessionBinder.ts";
8585
import { makeSettlementAttachmentReleaseFork } from "./SettlementAttachmentRelease.fork.ts"; // fork-hook: zmux-estate/settled-lane-release-import
86-
import { settlementHookTerminalModeFork } from "./SettlementHookShell.fork.ts"; // fork-hook: zmux-estate/settle-hook-shell-mode-import
86+
import { terminalModeForSessionFork } from "./SettlementHookShell.fork.ts"; // fork-hook: zmux-estate/settle-hook-shell-mode-import
8787
import { SettledLaneAttachGuard } from "../zmux/SettledLaneAttachGuard.fork.ts"; // fork-hook: zmux-estate/settled-lane-attach-guard-import
8888
import {
8989
INITIAL_MANAGED_ATTACHMENT_LIFECYCLE,
@@ -411,7 +411,7 @@ interface TerminalSessionState {
411411
managedAttachment: ManagedAttachmentLifecycle;
412412
managedSuspendFiber: Fiber.Fiber<void, never> | null;
413413
runtimeEnv: Record<string, string> | null;
414-
plainShellFork: boolean; // fork-hook: zmux-estate/plain-shell-state
414+
sessionModeFork: TerminalSessionMode | null; // fork-hook: zmux-estate/session-mode-state
415415
}
416416

417417
interface PersistHistoryRequest {
@@ -460,6 +460,7 @@ interface RetainedManagedSessionIdentity {
460460
readonly childCommandLabel: string | null;
461461
readonly updatedAt: string;
462462
readonly eventSequence: number;
463+
readonly sessionModeFork: TerminalSessionMode | null; // fork-hook: zmux-estate/session-mode-retained
463464
}
464465

465466
interface TerminalManagerState {
@@ -1799,7 +1800,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
17991800
const registerTerminalProcesses = options.registerTerminalProcesses ?? (() => Effect.void);
18001801
const unregisterTerminal = options.unregisterTerminal ?? (() => Effect.void);
18011802
const terminalSessionMode = options.terminalSessionMode ?? Effect.succeed("shell" as const);
1802-
const effectiveTerminalSessionMode = settlementHookTerminalModeFork(terminalSessionMode); // fork-hook: zmux-estate/settle-hook-shell-mode
1803+
const sessionModeFor = (session: TerminalSessionState) =>
1804+
terminalModeForSessionFork(session.sessionModeFork, terminalSessionMode); // fork-hook: zmux-estate/settle-hook-shell-mode
18031805

18041806
const resolveZmuxSession = Effect.fn("terminal.resolveZmuxSession")(function* (
18051807
targetDir: string,
@@ -2491,6 +2493,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
24912493
childCommandLabel: session.childCommandLabel,
24922494
updatedAt: session.updatedAt,
24932495
eventSequence,
2496+
sessionModeFork: session.sessionModeFork, // fork-hook: zmux-estate/session-mode-retained
24942497
});
24952498
}
24962499
events.push({
@@ -2776,8 +2779,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
27762779
session: TerminalSessionState,
27772780
input: TerminalStartInput,
27782781
): Effect.fn.Return<PreparedManagedRetarget | null, TerminalError> {
2779-
if (session.plainShellFork) return null; // fork-hook: zmux-estate/plain-shell-retarget
2780-
if ((yield* effectiveTerminalSessionMode) !== "zmux") return null; // fork-hook: zmux-estate/settle-hook-shell-retarget-mode
2782+
if ((yield* sessionModeFor(session)) !== "zmux") return null; // fork-hook: zmux-estate/settle-hook-shell-retarget-mode
27812783

27822784
const worktreePath = input.worktreePath ?? null;
27832785
if (worktreePath !== null) {
@@ -3163,7 +3165,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
31633165
}
31643166
}
31653167
}
3166-
const mode = session.plainShellFork ? "shell" : yield* effectiveTerminalSessionMode; // fork-hook: zmux-estate/settle-hook-shell-open-mode
3168+
const mode = yield* sessionModeFor(session); // fork-hook: zmux-estate/settle-hook-shell-open-mode
31673169
let shellCandidates = plainShellCandidates;
31683170
let spawnEnv = terminalEnv;
31693171
let managedTarget: string | null = null;
@@ -4012,7 +4014,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
40124014
},
40134015
managedSuspendFiber: null,
40144016
runtimeEnv: current.runtimeEnv,
4015-
plainShellFork: false, // fork-hook: zmux-estate/plain-shell-retained
4017+
sessionModeFork: current.sessionModeFork, // fork-hook: zmux-estate/session-mode-retained
40164018
};
40174019
const sessions = new Map(state.sessions);
40184020
sessions.set(key, session);
@@ -4076,7 +4078,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
40764078
managedAttachment: INITIAL_MANAGED_ATTACHMENT_LIFECYCLE,
40774079
managedSuspendFiber: null,
40784080
runtimeEnv: normalizedRuntimeEnv(input.env),
4079-
plainShellFork: input.plainShellFork === true, // fork-hook: zmux-estate/plain-shell-open-state
4081+
sessionModeFork: input.sessionModeFork ?? null, // fork-hook: zmux-estate/session-mode-open-state
40804082
};
40814083

40824084
const createdSession = session;
@@ -4710,7 +4712,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
47104712
managedAttachment: INITIAL_MANAGED_ATTACHMENT_LIFECYCLE,
47114713
managedSuspendFiber: null,
47124714
runtimeEnv: normalizedRuntimeEnv(input.env),
4713-
plainShellFork: input.plainShellFork === true, // fork-hook: zmux-estate/plain-shell-restart-state
4715+
sessionModeFork: input.sessionModeFork ?? null, // fork-hook: zmux-estate/session-mode-restart-state
47144716
};
47154717
const createdSession = session;
47164718
yield* modifyManagerState((state) => {

‎apps/server/src/terminal/SettlementHookShell.fork.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,15 @@ export const inSettlementHookShellFork = <A, E, R>(
1414
settle: boolean,
1515
) => Effect.provideService(effect, SettlementHookShell, settle);
1616

17-
export const settlementHookTerminalModeFork = (configured: Effect.Effect<TerminalSessionMode>) =>
17+
/** A terminal's chosen mode wins over the default; settle hooks still force a shell. */
18+
export const terminalModeForSessionFork = (
19+
chosen: TerminalSessionMode | null,
20+
configured: Effect.Effect<TerminalSessionMode>,
21+
) =>
1822
Effect.flatMap(SettlementHookShell, (settle) =>
19-
settle ? Effect.succeed("shell" as const) : configured,
23+
settle
24+
? Effect.succeed("shell" as const)
25+
: chosen === null
26+
? configured
27+
: Effect.succeed(chosen),
2028
);

‎apps/server/src/zmux/SettledLaneSessions.fork.test.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ const harness = () =>
6161
let projectDeleted = false;
6262
const calls: string[] = [];
6363
const removed = yield* Queue.unbounded<Binder.ZmuxUnbindIdentity>();
64+
const bound = yield* Deferred.make<void>();
6465
const subscribed = yield* Deferred.make<void>();
6566
const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
6667
const dependencies = Layer.mergeAll(
@@ -118,6 +119,7 @@ const harness = () =>
118119
bind: (lane) =>
119120
Effect.sync(() => {
120121
calls.push(`bind:${lane}`);
122+
Deferred.doneUnsafe(bound, Effect.void);
121123
return { status: "bound", target, outcome: "created" } as const;
122124
}),
123125
prepareUnbind: (lane) =>
@@ -153,6 +155,7 @@ const harness = () =>
153155
dependencies,
154156
subscribed: Deferred.await(subscribed),
155157
removed: Queue.take(removed),
158+
bound: Deferred.await(bound),
156159
emit: (type: "thread.settled" | "thread.deleted" | "thread.unsettled" | "thread.pinned") =>
157160
Queue.offer(events, { type, threadId: id } as OrchestrationV2DomainEvent),
158161
setThread: (value: Partial<OrchestrationV2AppThread>) => {
@@ -325,14 +328,33 @@ describe("settled checkout sessions", () => {
325328
}),
326329
);
327330

328-
it.effect("unsettling leaves the removed session gone", () =>
331+
it.effect("unsettling restores the removed session", () =>
329332
Effect.gen(function* () {
330333
const h = yield* harness();
331-
yield* h.reactor.reconcile(id);
334+
yield* h.reactor.start();
335+
yield* h.subscribed;
336+
yield* h.emit("thread.settled");
332337
expect(yield* h.removed).toEqual(identity);
333-
h.setThread({ settledOverride: "active" });
334-
yield* h.reactor.reconcile(id);
335-
expect(h.calls).not.toContain("bind:/repo-feature");
338+
h.setThread({ settledOverride: null });
339+
yield* h.emit("thread.unsettled");
340+
yield* h.bound;
341+
expect(h.calls).toEqual(["release", "prepare:/repo-feature", "unbind", "bind:/repo-feature"]);
342+
}),
343+
);
344+
345+
it.effect.each([
346+
["a settled", {}],
347+
[
348+
"a deleted",
349+
{ settledOverride: null, deletedAt: DateTime.makeUnsafe("2026-10-10T00:00:00Z") },
350+
],
351+
["a base checkout", { settledOverride: null, worktreePath: "/repo" }],
352+
] as const)("restore skips %s thread", ([, thread]) =>
353+
Effect.gen(function* () {
354+
const h = yield* harness();
355+
h.setThread(thread);
356+
yield* h.reactor.restore(id);
357+
expect(h.calls).toEqual([]);
336358
}),
337359
);
338360

‎apps/server/src/zmux/SettledLaneSessions.fork.ts‎

Lines changed: 63 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Settling or deleting a worktree thread tears down its checkout's whole
2-
// managed session. The base checkout and main session remain separate.
3-
import { type ThreadId } from "@t3tools/contracts";
2+
// managed session; unsettling restores it when automatic sessions are on. The
3+
// base checkout and main session remain separate.
4+
import { type OrchestrationV2AppThread, type ThreadId } from "@t3tools/contracts";
45
import * as Effect from "effect/Effect";
56
import * as FileSystem from "effect/FileSystem";
67
import * as Layer from "effect/Layer";
@@ -21,6 +22,7 @@ import { withCheckoutSessionCleanupFork } from "./CheckoutSessionStateLease.fork
2122

2223
export interface SettledLaneReactor {
2324
readonly reconcile: (threadId: ThreadId) => Effect.Effect<void>;
25+
readonly restore: (threadId: ThreadId) => Effect.Effect<void>;
2426
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
2527
}
2628

@@ -43,25 +45,38 @@ export const makeSettledLaneReactor = Effect.gen(function* () {
4345
const sameCheckout = (left: string | null, right: string) =>
4446
left !== null && path.resolve(left) === path.resolve(right);
4547

48+
const isSettled = (thread: OrchestrationV2AppThread) =>
49+
thread.settledOverride === "settled" || thread.deletedAt !== null;
50+
51+
/** The thread's linked worktree and its project root; none for the base checkout. */
52+
const linkedLane = Effect.fn("SettledLaneSessions.linkedLane")(function* (
53+
thread: OrchestrationV2AppThread,
54+
) {
55+
const lane = thread.worktreePath;
56+
if (lane === null) return Option.none();
57+
const project = yield* projects.get(thread.projectId, { includeDeleted: true });
58+
// Missing ownership information is never permission to touch a session.
59+
if (Option.isNone(project)) return Option.none();
60+
const root = project.value.workspaceRoot;
61+
const laneIdentity = yield* checkoutRootOf(lane);
62+
const rootIdentity = yield* checkoutRootOf(root);
63+
if (
64+
Option.isNone(laneIdentity) ||
65+
Option.isNone(rootIdentity) ||
66+
laneIdentity.value === rootIdentity.value
67+
)
68+
return Option.none();
69+
return Option.some({ lane, root, laneIdentity: laneIdentity.value });
70+
});
71+
4672
const reconcile = (threadId: ThreadId) =>
4773
permits.withPermits(1)(
4874
Effect.gen(function* () {
4975
const thread = yield* projections.getThread(threadId);
50-
const lane = thread.worktreePath;
51-
if (lane === null) return;
52-
if (thread.settledOverride !== "settled" && thread.deletedAt === null) return;
53-
const project = yield* projects.get(thread.projectId, { includeDeleted: true });
54-
// Missing ownership information is never permission to remove a session.
55-
if (Option.isNone(project)) return;
56-
const root = project.value.workspaceRoot;
57-
const laneIdentity = yield* checkoutRootOf(lane);
58-
const rootIdentity = yield* checkoutRootOf(root);
59-
if (
60-
Option.isNone(laneIdentity) ||
61-
Option.isNone(rootIdentity) ||
62-
laneIdentity.value === rootIdentity.value
63-
)
64-
return;
76+
if (!isSettled(thread)) return;
77+
const linked = yield* linkedLane(thread);
78+
if (Option.isNone(linked)) return;
79+
const { lane, root, laneIdentity } = linked.value;
6580

6681
// Detach local viewers first, but a missing exit acknowledgement must
6782
// not leave the session's tabs and background processes running.
@@ -89,19 +104,15 @@ export const makeSettledLaneReactor = Effect.gen(function* () {
89104
yield* withCheckoutSessionCleanupFork(
90105
Effect.gen(function* () {
91106
const latest = yield* projections.getThread(threadId);
92-
if (
93-
(latest.settledOverride !== "settled" && latest.deletedAt === null) ||
94-
!sameCheckout(latest.worktreePath, lane)
95-
)
96-
return;
107+
if (!isSettled(latest) || !sameCheckout(latest.worktreePath, lane)) return;
97108
const latestProject = yield* projects.get(latest.projectId, { includeDeleted: true });
98109
if (Option.isNone(latestProject)) return;
99110
const latestLaneIdentity = yield* checkoutRootOf(lane);
100111
const latestRootIdentity = yield* checkoutRootOf(latestProject.value.workspaceRoot);
101112
if (
102113
Option.isNone(latestLaneIdentity) ||
103114
Option.isNone(latestRootIdentity) ||
104-
latestLaneIdentity.value !== laneIdentity.value ||
115+
latestLaneIdentity.value !== laneIdentity ||
105116
latestLaneIdentity.value === latestRootIdentity.value
106117
)
107118
return;
@@ -132,14 +143,42 @@ export const makeSettledLaneReactor = Effect.gen(function* () {
132143
),
133144
);
134145

146+
// The binder creates nothing while automatic sessions are off.
147+
const restore = (threadId: ThreadId) =>
148+
permits.withPermits(1)(
149+
Effect.gen(function* () {
150+
const thread = yield* projections.getThread(threadId);
151+
if (isSettled(thread)) return;
152+
const linked = yield* linkedLane(thread);
153+
if (Option.isNone(linked)) return;
154+
const bound = yield* binder.bind(linked.value.lane, { projectPath: linked.value.root });
155+
if (bound.status === "failed") {
156+
yield* Effect.logWarning("could not restore unsettled checkout session", {
157+
threadId,
158+
detail: bound.notice.detail,
159+
});
160+
}
161+
}).pipe(
162+
Effect.catch((error) =>
163+
Effect.logWarning("checkout unsettle restore failed", {
164+
threadId,
165+
detail: error.message,
166+
}),
167+
),
168+
),
169+
);
170+
135171
return {
136172
reconcile,
173+
restore,
137174
start: () =>
138175
forkParked(
139176
Stream.runForEach(orchestrator.streamDomainEvents, (event) =>
140177
event.type === "thread.settled" || event.type === "thread.deleted"
141178
? reconcile(event.threadId)
142-
: Effect.void,
179+
: event.type === "thread.unsettled"
180+
? restore(event.threadId)
181+
: Effect.void,
143182
).pipe(
144183
Effect.catchCause((cause) =>
145184
Effect.logWarning("checkout settlement stream failed", { cause }),

0 commit comments

Comments
 (0)