Skip to content

Commit 7f4c625

Browse files
donjor-agent[bot]donjor
authored andcommitted
fix(terminal): close T3 viewers of a settled lane's removed zmux session (#1876)
## Problem Settling a lane removes its zmux session, but T3 only suspends its own viewer of that session. The suspended viewer still counts as running. On reopen it resumes as a plain shell that keeps the old lane history. ## Change After `binder.unbind` confirms the session is gone (`unbound` or `not-found`), `SettledLaneSessions` calls the new `TerminalManager.closeSettledManagedAttachments({ target })`. - **Viewers:** live and retained ones close - **History:** deleted; T3 closes the tab - **Refusal:** any other outcome closes nothing - **Reopen while settled:** labeled read-only shell - **Unsettle:** new terminal opens fresh session Known limit: a shell opened while settled stays a plain shell after unsettle; open a new terminal. ## Scope and approval Closes #1671. #1738 dropped its settlement work and asked for a simpler design; this is that design. - [ ] **Cause:** identify the stale lifecycle path. - [ ] **Settle:** define visible terminal behavior. - [ ] **Unsettle:** define fresh-session display. - [ ] **Proof:** verify the policy beside Ghostty. ## Verification - [x] **Red first:** new settlement test fails on trunk - [x] **Targeted tests:** 28 passed - [x] `vp run typecheck` (apps/server) → exit 0 - [x] `vp run build` (apps/server) → exit 0 - [x] `vp run fork:ci` → exit 0 - [x] `vp run check:changed` → exit 0 - [x] **Sidebar reopen, hard reload:** no old history - [x] **Settled row:** no stale running count **Build:** `5a398845f8d` on an isolated dev server. Before (trunk, 81 s, uncut): reopen after Settle resumes a plain shell that keeps the old lane history. https://github.com/user-attachments/assets/4a9b3145-e2e6-42da-a806-95da7f68a702 After (T3 beside Ghostty, 22 s): Settle closes the T3 terminal as Ghostty drops `lane-1671`; Unsettle restores it; a new terminal opens the fresh session. https://github.com/user-attachments/assets/fd5ed777-b5ef-4137-8a62-5093a7d6ca0d | Span | Real | Clip | | --- | --- | --- | | 0–7 s | 7 s | kept | | 7–19 s, idle | 12 s | cut | | 24–30 s, idle | 6 s | cut | | 34–108 s, zmux busy retry and dialogs | 74 s | cut | | after 114 s | 24 s | cut | Sidebar reopen after Settle, from another thread: labeled plain shell, no old marker. ![Sidebar reopen after Settle](https://github.com/user-attachments/assets/d99a4f64-9329-411c-bc4f-f7e3db432ff7) Opus 5.5 via Claude Code. ## Fork trailers Squashes: - 9529335 fix(terminal): close T3 viewers of a settled lane's removed zmux session (#1876) (#1876) - ba5ad54 fixup! fix(terminal): close T3 viewers of a settled lane's removed zmux session (#1876) (#1876) Fork-Domain: zmux-estate Fork-Tier: bugfix Fork-Upstreamable: no Co-authored-by: donjor <[email protected]>
1 parent cf2e183 commit 7f4c625

6 files changed

Lines changed: 130 additions & 13 deletions

File tree

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,5 +109,41 @@ it.layer(NodeServices.layer, { excludeTestServices: true })(
109109
yield* manager.close({ threadId: input.threadId });
110110
}),
111111
);
112+
113+
it.effect("closes viewers of a removed session instead of resuming them as plain shells", () =>
114+
Effect.gen(function* () {
115+
let removed = false;
116+
const live = resolvedZmuxProcessRunner().service;
117+
const runner = new FakeProcessRunner((runInput) =>
118+
removed
119+
? Effect.succeed(processResult({ stdout: '{"status":"not-found"}' }))
120+
: live.run(runInput),
121+
);
122+
const { manager, ptyAdapter, getEvents } = yield* createManager(5, {
123+
terminalSessionMode: "zmux",
124+
shellResolver: () => "/bin/bash",
125+
resolveOnlyForSettledThread: () => Effect.succeed(removed),
126+
}).pipe(Effect.provideService(ProcessRunner.ProcessRunner, runner.service));
127+
const input = openInput({ worktreePath: process.cwd() });
128+
const release = yield* manager.attachStream(input, () => Effect.void);
129+
const ptyProcess = ptyAdapter.processes[0]!;
130+
const kill = ptyProcess.kill.bind(ptyProcess);
131+
ptyProcess.kill = (signal) => {
132+
kill(signal);
133+
ptyProcess.emitExit({ exitCode: 0, signal: 15 });
134+
};
135+
yield* manager.releaseSettledManagedAttachments({ threadId: input.threadId });
136+
removed = true;
137+
yield* manager.closeSettledManagedAttachments({ target: "zmux/main" });
138+
release();
139+
140+
expect(yield* getEvents).toContainEqual(
141+
expect.objectContaining({ type: "closed", terminalId: input.terminalId }),
142+
);
143+
const resumed = yield* manager.attachStream({ ...input, resume: true }, () => Effect.void);
144+
expect(ptyAdapter.spawnInputs).toHaveLength(1);
145+
resumed();
146+
}),
147+
);
112148
},
113149
);

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

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@ import * as PortScanner from "../preview/PortScanner.ts";
8282
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
8383
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
8484
import * as ZmuxSessionBinder from "../zmux/ZmuxSessionBinder.ts";
85-
import { makeSettlementAttachmentReleaseFork } from "./SettlementAttachmentRelease.fork.ts"; // fork-hook: zmux-estate/settled-lane-release-import
85+
import {
86+
makeSettledSessionCloseFork,
87+
makeSettlementAttachmentReleaseFork,
88+
} from "./SettlementAttachmentRelease.fork.ts"; // fork-hook: zmux-estate/settled-lane-release-import
8689
import { terminalModeForSessionFork } from "./SettlementHookShell.fork.ts"; // fork-hook: zmux-estate/settle-hook-shell-mode-import
8790
import { SettledLaneAttachGuard } from "../zmux/SettledLaneAttachGuard.fork.ts"; // fork-hook: zmux-estate/settled-lane-attach-guard-import
8891
import {
@@ -276,6 +279,10 @@ export class TerminalManager extends Context.Service<
276279
readonly threadId: string;
277280
}) => Effect.Effect<boolean>; // fork-hook: zmux-estate/settled-lane-release-contract
278281

282+
readonly closeSettledManagedAttachments: (input: {
283+
readonly target: string;
284+
}) => Effect.Effect<void>; // fork-hook: zmux-estate/settled-lane-close-contract
285+
279286
readonly subscribe: (
280287
listener: (event: TerminalEvent) => Effect.Effect<void>,
281288
registerCleanup?: (stop: () => void) => void,
@@ -2198,11 +2205,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
21982205
yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS);
21992206
}
22002207

2201-
const parsed = Schema.decodeUnknownOption(
2202-
Schema.fromJsonString(
2203-
Schema.Tuple([Schema.String, Schema.String, Schema.NullOr(Schema.String)]),
2204-
),
2205-
)(sessionKey);
2208+
const parsed = decodeSessionKey(sessionKey); // fork-hook: zmux-estate/persist-history-key
22062209
if (Option.isNone(parsed)) {
22072210
return;
22082211
}
@@ -2828,10 +2831,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
28282831
// and the re-resolution keeps the strict readiness receipt.
28292832
options.ensureZmuxSession && !(yield* resolveOnlyForSettledThread(session.threadId))
28302833
? ensureZmuxSession(targetDir, expectedMatch).pipe(
2831-
Effect.flatMap((ensured) =>
2832-
ensured.target
2833-
? resolveZmuxSession(targetDir, expectedMatch, spawnEnv)
2834-
: Effect.succeed(ensured),
2834+
Effect.filterOrElse(
2835+
(ensured) => !ensured.target,
2836+
() => resolveZmuxSession(targetDir, expectedMatch, spawnEnv),
28352837
),
28362838
)
28372839
: resolveZmuxSession(targetDir, expectedMatch, spawnEnv)
@@ -4914,6 +4916,22 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
49144916
processKillGraceMs,
49154917
}); // fork-hook: zmux-estate/settled-lane-release-implementation
49164918

4919+
const closeSettledManagedAttachments = makeSettledSessionCloseFork({
4920+
viewers: readManagerState.pipe(
4921+
Effect.map((state) => [
4922+
...state.sessions.values(),
4923+
...state.retainedManagedSessions.values(),
4924+
]),
4925+
),
4926+
close: (viewer) =>
4927+
close({
4928+
threadId: viewer.threadId,
4929+
terminalId: viewer.terminalId,
4930+
...(viewer.attachmentId ? { attachmentId: viewer.attachmentId } : {}),
4931+
deleteHistory: true,
4932+
}),
4933+
}); // fork-hook: zmux-estate/settled-lane-close-implementation
4934+
49174935
return TerminalManager.of({
49184936
open,
49194937
attachStream,
@@ -4926,6 +4944,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
49264944
close,
49274945
closeIdle,
49284946
releaseSettledManagedAttachments, // fork-hook: zmux-estate/settled-lane-release-service
4947+
closeSettledManagedAttachments, // fork-hook: zmux-estate/settled-lane-close-service
49294948
subscribe,
49304949
subscribeMetadata,
49314950
});

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,39 @@ export const makeSettlementAttachmentReleaseFork =
6767
}).pipe(Effect.as(false)),
6868
),
6969
);
70+
71+
interface SettledViewer {
72+
readonly threadId: string;
73+
readonly terminalId: string;
74+
readonly attachmentId: string | null;
75+
readonly managedSessionIdentity: { readonly target: string } | null;
76+
}
77+
78+
/**
79+
* Close every viewer of a native session settlement removed. A suspended viewer
80+
* would otherwise keep counting as running and resume as a plain shell.
81+
*/
82+
export const makeSettledSessionCloseFork =
83+
<E extends Error>(input: {
84+
readonly viewers: Effect.Effect<ReadonlyArray<SettledViewer>>;
85+
readonly close: (viewer: SettledViewer) => Effect.Effect<void, E>;
86+
}) =>
87+
({ target }: { readonly target: string }) =>
88+
input.viewers.pipe(
89+
Effect.flatMap((viewers) =>
90+
Effect.forEach(
91+
viewers.filter((viewer) => viewer.managedSessionIdentity?.target === target),
92+
(viewer) =>
93+
input.close(viewer).pipe(
94+
Effect.catch((error) =>
95+
Effect.logWarning("failed to close viewer of removed settled session", {
96+
threadId: viewer.threadId,
97+
terminalId: viewer.terminalId,
98+
error: error.name,
99+
}),
100+
),
101+
),
102+
{ discard: true },
103+
),
104+
),
105+
);

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

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ const harness = () =>
114114
calls.push("release");
115115
return releaseSucceeded;
116116
}),
117+
closeSettledManagedAttachments: ({ target }) =>
118+
Effect.sync(() => {
119+
calls.push(`close:${target}`);
120+
}),
117121
}),
118122
Layer.mock(Binder.ZmuxSessionBinder)({
119123
bind: (lane) =>
@@ -211,7 +215,12 @@ describe("settled checkout sessions", () => {
211215
Effect.gen(function* () {
212216
const h = yield* harness();
213217
yield* h.reactor.reconcile(id);
214-
expect(h.calls).toEqual(["release", "prepare:/repo-feature", "unbind"]);
218+
expect(h.calls).toEqual([
219+
"release",
220+
"prepare:/repo-feature",
221+
"unbind",
222+
"close:proof/feature",
223+
]);
215224
expect(yield* h.removed).toEqual(identity);
216225
}),
217226
);
@@ -252,7 +261,12 @@ describe("settled checkout sessions", () => {
252261
if (timing === "before reconciliation") h.deleteProject();
253262
else h.setBeforeCleanup(Effect.sync(h.deleteProject));
254263
yield* h.reactor.reconcile(id);
255-
expect(h.calls).toEqual(["release", "prepare:/repo-feature", "unbind"]);
264+
expect(h.calls).toEqual([
265+
"release",
266+
"prepare:/repo-feature",
267+
"unbind",
268+
"close:proof/feature",
269+
]);
256270
expect(yield* h.removed).toEqual(identity);
257271
}),
258272
);
@@ -338,7 +352,13 @@ describe("settled checkout sessions", () => {
338352
h.setThread({ settledOverride: null });
339353
yield* h.emit("thread.unsettled");
340354
yield* h.bound;
341-
expect(h.calls).toEqual(["release", "prepare:/repo-feature", "unbind", "bind:/repo-feature"]);
355+
expect(h.calls).toEqual([
356+
"release",
357+
"prepare:/repo-feature",
358+
"unbind",
359+
"close:proof/feature",
360+
"bind:/repo-feature",
361+
]);
342362
}),
343363
);
344364

@@ -364,6 +384,7 @@ describe("settled checkout sessions", () => {
364384
h.refuse();
365385
yield* h.reactor.reconcile(id);
366386
expect(h.calls.filter((call) => call === "unbind")).toHaveLength(1);
387+
expect(h.calls.some((call) => call.startsWith("close:"))).toBe(false);
367388
h.forgetProject();
368389
yield* h.reactor.reconcile(id);
369390
expect(h.calls.filter((call) => call === "unbind")).toHaveLength(1);

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,10 @@ export const makeSettledLaneReactor = Effect.gen(function* () {
131131
retry: ZmuxSessionBinder.protectedCleanupCommand(prepared.identity),
132132
});
133133
}
134+
// Only a confirmed absence ends the viewers; any other outcome keeps them resumable.
135+
if (removed.status === "unbound" || removed.status === "not-found") {
136+
yield* terminals.closeSettledManagedAttachments({ target: prepared.identity.target });
137+
}
134138
}),
135139
);
136140
}).pipe(

‎docs/fork/user/managed-terminals.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ Update or configure zmux on the host, then retry.
2828

2929
Settling or deleting a worktree thread removes its entire zmux session, including every tab and running command.
3030
This also disconnects other viewers and threads using that session.
31+
T3 Code closes its terminals on that session; a new terminal after unsettling opens the fresh session.
3132
Settlement keeps the worktree and branch, but discards the session permanently.
3233
Unsettling, or new activity on a settled thread, creates a fresh session when automatic sessions are on.
3334
Otherwise opening a zmux terminal creates it.

0 commit comments

Comments
 (0)