@devries-cameron20 / t3code-1 / commits / 14f295e011
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(terminal): one web viewer answers shared PTY queries (#37233)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 15, 2026 at 16:21 UTC 14f295e011096d712793fc7e3a9537de550618b0
9 files changed +109 -31
apps/server/src/terminal/Manager.test.ts
+33
@@ -741,6 +741,39 @@ it.layer(
741 }),
742 );
743
744 + // Every attached renderer answers the same query; a second DECRQM answer breaks Vim's input.
745 + it.effect("lets one attached viewer answer terminal queries on a shared PTY", () =>
746 + Effect.gen(function* () {
747 + const { manager, ptyAdapter } = yield* createManager();
748 + const attach = (terminalId: string, viewerId: string) =>
749 + manager.attachStream(openInput({ terminalId }), () => Effect.void, undefined, viewerId);
750 + const stopFirst = yield* attach(DEFAULT_TERMINAL_ID, "first");
751 + const stopSecond = yield* attach(DEFAULT_TERMINAL_ID, "second");
752 + const stopOther = yield* attach("other", "second");
753 + yield* Effect.addFinalizer(() => Effect.sync(() => (stopSecond(), stopOther())));
754 + const [shared, other] = ptyAdapter.processes;
755 + const modeReply = "\x1b[?12;2$y";
756 + const write = (terminalId: string, viewerId: string, data: string, reply?: boolean) =>
757 + manager.write(
758 + { threadId: "thread-1", terminalId, data, ...(reply ? { reply } : {}) },
759 + viewerId,
760 + );
761 +
762 + yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true);
763 + yield* write(DEFAULT_TERMINAL_ID, "second", modeReply, true);
764 + yield* write(DEFAULT_TERMINAL_ID, "second", "iHELLO");
765 + yield* write("other", "second", modeReply, true);
766 + expect(shared!.writes).toEqual([modeReply, "iHELLO"]);
767 + expect(other!.writes).toEqual([modeReply]);
768 +
769 + stopFirst();
770 + yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true);
771 + yield* write(DEFAULT_TERMINAL_ID, "second", modeReply, true);
772 + yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true);
773 + expect(shared!.writes).toEqual([modeReply, "iHELLO", modeReply]);
774 + }),
775 + );
776 +
777 it.effect("resumed attaches after close never respawn until the terminal is reopened", () =>
778 Effect.gen(function* () {
779 const { manager, ptyAdapter } = yield* createManager();
apps/server/src/terminal/Manager.ts
+49 -23
@@ -216,7 +216,14 @@ export class TerminalManager extends Context.Service<
216 registerCleanup?: (stop: () => void) => void,
217 ) => Effect.Effect<() => void, TerminalError>;
218
219 - readonly write: (input: TerminalWriteInput) => Effect.Effect<void, TerminalError>;
219 + /**
220 + * Attached viewers share one reply owner per PTY until it detaches. Marked replies
221 + * from other or detached viewer IDs are dropped; identity-free writes do not claim ownership.
222 + */
223 + readonly write: (
224 + input: TerminalWriteInput,
225 + viewerId?: string,
226 + ) => Effect.Effect<void, TerminalError>;
227
228 readonly resize: (
229 input: TerminalResizeInput,
@@ -329,6 +336,7 @@ interface TerminalGrid {
336 interface TerminalViewer {
337 streams: number;
338 grid: TerminalGrid | null;
339 + answersQueries: boolean;
340 }
341
342 interface PersistHistoryRequest {
@@ -1999,7 +2007,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2007 // After a viewer's first size, resizes own it; attach retries resend the original size.
2008 viewer.grid ??= grid;
2009 } else {
2002 - viewers.set(viewerId, { streams: 1, grid });
2010 + viewers.set(viewerId, { streams: 1, grid, answersQueries: false });
2011 }
2012 };
2013
@@ -2015,6 +2023,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2023 return true;
2024 };
2025
2026 + // The first attached viewer to answer a query keeps answering until it detaches.
2027 + const acceptsQueryReply = (sessionKey: string, viewerId: string | undefined) => {
2028 + const viewers = terminalViewers.get(sessionKey);
2029 + const viewer = viewerId === undefined ? undefined : viewers?.get(viewerId);
2030 + if (viewerId !== undefined && !viewer) return false;
2031 + if (viewer?.answersQueries) return true;
2032 + for (const other of viewers?.values() ?? []) {
2033 + if (other.answersQueries) return false;
2034 + }
2035 + if (viewer) viewer.answersQueries = true;
2036 + return true;
2037 + };
2038 +
2039 // The smallest attached viewer bounds each axis, so every viewer can draw the whole grid.
2040 const sharedViewerGrid = (sessionKey: string): TerminalGrid | null => {
2041 let shared: TerminalGrid | null = null;
@@ -3686,29 +3707,34 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3707 );
3708 };
3709
3689 - const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")(function* (input) {
3690 - const terminalId = input.terminalId;
3691 - const session = yield* requireSession(input.threadId, terminalId);
3692 - const process = session.process;
3693 - if (!process || session.status !== "running") {
3694 - if (session.status === "exited") return;
3695 - return yield* new TerminalNotRunningError({
3696 - threadId: input.threadId,
3697 - terminalId,
3698 - });
3699 - }
3700 - session.inputCount += 1;
3701 - yield* Effect.try({
3702 - try: () => process.write(PtyAdapter.ptyInput(input.data, input.binary)),
3703 - catch: (cause) =>
3704 - new TerminalWriteError({
3710 + const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")(
3711 + function* (input, viewerId) {
3712 + const terminalId = input.terminalId;
3713 + const session = yield* requireSession(input.threadId, terminalId);
3714 + const process = session.process;
3715 + if (!process || session.status !== "running") {
3716 + if (session.status === "exited") return;
3717 + return yield* new TerminalNotRunningError({
3718 threadId: input.threadId,
3719 terminalId,
3707 - terminalPid: process.pid,
3708 - cause,
3709 - }),
3710 - });
3711 - });
3720 + });
3721 + }
3722 + if (input.reply && !acceptsQueryReply(toSessionKey(input.threadId, terminalId), viewerId)) {
3723 + return;
3724 + }
3725 + session.inputCount += 1;
3726 + yield* Effect.try({
3727 + try: () => process.write(PtyAdapter.ptyInput(input.data, input.binary)),
3728 + catch: (cause) =>
3729 + new TerminalWriteError({
3730 + threadId: input.threadId,
3731 + terminalId,
3732 + terminalPid: process.pid,
3733 + cause,
3734 + }),
3735 + });
3736 + },
3737 + );
3738
3739 const resizeLocked = Effect.fn("terminal.resize")(function* (
3740 input: TerminalResizeInput,
apps/server/src/ws.ts
+2 -1
@@ -3215,7 +3215,8 @@ export const layerWsRpc = (
3215 ),
3216 ),
3217 ),
3218 - [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
3218 + [WS_METHODS.terminalWrite]: (input, metadata) =>
3219 + terminalManager.write(input, terminalViewerId(metadata)),
3220 [WS_METHODS.terminalResize]: (input, metadata) =>
3221 terminalManager.resize(input, terminalViewerId(metadata)),
3222 [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input),
apps/web/src/components/ThreadTerminalDrawer.tsx
+12 -5
@@ -723,7 +723,8 @@ function TerminalSessionViewport({
723 theme: terminalThemeFromApp(mount),
724 font: terminalFontOptions(setupFont.family, setupFont.size),
725 onData: (data) => handleData(data),
726 - onBinary: (data) => void sendTerminalInput(data, "Terminal write failed", true),
726 + onBinary: (data) => void sendTerminalInput(data, "Terminal write failed", "binary"),
727 + onReply: (data) => void sendTerminalInput(data, "Terminal write failed", "reply"),
728 onResize: (cols, rows) => void resizeTerminal(cols, rows),
729 onSelectionChange: () => {},
730 beforeKey: (event) => handleBeforeKey(event),
@@ -930,12 +931,18 @@ function TerminalSessionViewport({
931
932 const readInputSession = () => appAtomRegistry.get(terminalSessionAtom);
933 const canWriteInput = () => readEnvironmentScope(environmentId, AuthTerminalOperateScope);
933 - const writeInputChunk = (data: string, binary?: true) =>
934 + const writeInputChunk = (data: string, kind?: "binary" | "reply") =>
935 retainedTerminalWrite.current({
936 environmentId,
936 - input: binary ? { threadId, terminalId, data, binary } : { threadId, terminalId, data },
937 + input: kind
938 + ? { threadId, terminalId, data, [kind]: true }
939 + : { threadId, terminalId, data },
940 });
938 - const sendTerminalInput = (data: string, fallbackError: string, binary?: true) => {
941 + const sendTerminalInput = (
942 + data: string,
943 + fallbackError: string,
944 + kind?: "binary" | "reply",
945 + ) => {
946 // The server rejects input until the shell runs, and each rejection would print an error.
947 // Input belongs to the shell and surface it was typed into; a restart the client has seen drops what is left.
948 const session = readTerminalSession();
@@ -963,7 +970,7 @@ function TerminalSessionViewport({
970 ) {
971 return "not-dispatched";
972 }
966 - const result = await writeInputChunk(chunk, binary);
973 + const result = await writeInputChunk(chunk, kind);
974 if (result._tag === "Success") return true;
975 if (terminalRef.current === terminal && !isAtomCommandInterrupted(result)) {
976 const error = squashAtomCommandFailure(result);
apps/web/src/components/settings/ProviderAuthTerminal.tsx
+1
@@ -36,6 +36,7 @@ export default function ProviderAuthTerminal({
36 font: { size: 13 },
37 onData: (data) => respond({ type: "terminal", data }),
38 onBinary: (data) => respond({ type: "terminal", data, binary: true }),
39 + onReply: (data) => respond({ type: "terminal", data }),
40 onResize: (cols, rows) => respond({ type: "terminal", data: "", size: { cols, rows } }),
41 onSelectionChange: () => {},
42 beforeKey: (event) => event.key !== "Tab",
apps/web/src/components/settings/SettingsFontPreviews.tsx
+1
@@ -215,6 +215,7 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
215 font: initialFont,
216 onData: echo,
217 onBinary: noop,
218 + onReply: noop,
219 onResize: noop,
220 onSelectionChange: noop,
221 beforeKey: (event) => event.key !== "Tab",
apps/web/src/terminal/ghostty/surface.test.ts
+5 -1
@@ -250,6 +250,7 @@ describe("GhosttyTerminalSurface visibility", () => {
250 },
251 onData,
252 onBinary() {},
253 + onReply: onData,
254 onResize() {},
255 onSelectionChange() {},
256 beforeKey: () => false,
@@ -774,7 +775,9 @@ describe("GhosttyTerminalSurface visibility", () => {
775 return core;
776 });
777 let currentVisible = !visible;
778 + const onReply = vi.fn();
779 const pending = harness.create({
780 + onReply,
781 get visible() {
782 return currentVisible;
783 },
@@ -788,7 +791,8 @@ describe("GhosttyTerminalSurface visibility", () => {
791 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
792 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
793 surface.write("ready\x1b[5n");
791 - expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
794 + expect(onReply).toHaveBeenCalledWith("\x1b[0n");
795 + expect(harness.onData).not.toHaveBeenCalled();
796 if (!visible) {
797 expect(harness.frames.size).toBe(0);
798 surface.setVisible(true);
apps/web/src/terminal/ghostty/surface.ts
+3 -1
@@ -530,6 +530,8 @@ export interface GhosttyTerminalSurfaceOptions {
530 readonly onData: (data: string) => void;
531 /** Input bytes that are not UTF-8, one UTF-16 code unit per byte. */
532 readonly onBinary: (data: string) => void;
533 + /** The terminal's own answers to queries from the PTY (DA, DSR, DECRQM), never typed input. */
534 + readonly onReply: (data: string) => void;
535 readonly onResize: (cols: number, rows: number) => void;
536 readonly onSelectionChange: () => void;
537 readonly beforeKey: (event: KeyboardEvent) => boolean;
@@ -738,7 +740,7 @@ export class GhosttyTerminalSurface {
740 metrics.width,
741 metrics.height,
742 options.theme,
741 - options.onData,
743 + options.onReply,
744 );
745 const surface = new GhosttyTerminalSurface(
746 mount,
packages/contracts/src/terminal.ts
+3
@@ -200,6 +200,9 @@ export const TerminalWriteInput = Schema.Struct({
200 ),
201 // `data` holds one byte per UTF-16 code unit; older servers write it as UTF-8 text.
202 binary: Schema.optionalKey(Schema.Boolean),
203 + // A renderer's answer to a terminal query (DA, DSR, DECRQM). Every attached renderer
204 + // answers, so the server passes on one viewer's replies; older servers ignore it.
205 + reply: Schema.optionalKey(Schema.Boolean),
206 });
207 export type TerminalWriteInput = Schema.Codec.Encoded<typeof TerminalWriteInput>;
208