@devries-cameron20 / t3code-1 / commits / 83a276dfdd
Fork 0

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

fix(server): setup scripts complete with shell line editors (#25472)

Co-authored-by: Abid A Gafoor <40262245+sgaabdu4@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

maria committed Nov 14, 2026 at 09:09 UTC 83a276dfdd6981e31bfb5ce97b647e65d05e493c
2 files changed +167 -6
apps/server/src/project/ProjectSetupScriptRunner.test.ts
+115 -4
@@ -1,16 +1,20 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 -import { describe, expect, it } from "@effect/vitest";
2 +import * as NodeServices from "@effect/platform-node/NodeServices";
3 +import { assert, describe, expect, it } from "@effect/vitest";
4 import {
5 ProjectId,
6 TerminalNotRunningError,
7 type TerminalEvent,
8 type TerminalSessionSnapshot,
9 } from "@t3tools/contracts";
10 +import * as HostProcess from "@t3tools/shared/HostProcess";
11 import * as Deferred from "effect/Deferred";
12 import * as Effect from "effect/Effect";
13 import * as Fiber from "effect/Fiber";
14 import * as Layer from "effect/Layer";
15 import * as Queue from "effect/Queue";
16 +import * as Stream from "effect/Stream";
17 +import { ChildProcess, ChildProcessSpawner } from "effect/process";
18 import { TestClock } from "effect/testing";
19
20 import * as ServerSettings from "../serverSettings.ts";
@@ -164,7 +168,7 @@ describe("ProjectSetupScriptRunner", () => {
168
169 yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
170 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
167 - expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
171 + expect(yield* Queue.take(writes)).toContain("vp i");
172 }),
173 );
174
@@ -172,7 +176,7 @@ describe("ProjectSetupScriptRunner", () => {
176 Effect.gen(function* () {
177 const { writes } = yield* setup();
178 yield* TestClock.adjust("3 seconds");
175 - expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
179 + expect(yield* Queue.take(writes)).toContain("vp i");
180 }),
181 );
182
@@ -194,7 +198,7 @@ describe("ProjectSetupScriptRunner", () => {
198 yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
199 // The restart lands inside a quiet window, so the next full window decides.
200 yield* TestClock.adjust("6 seconds");
197 - expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
201 + expect(yield* Queue.take(writes)).toContain("vp i");
202 }),
203 );
204
@@ -227,3 +231,110 @@ describe("ProjectSetupScriptRunner", () => {
231 }),
232 );
233 });
234 +
235 +const runObservedSetup = Effect.fnUntraced(function* (command: string) {
236 + const { writes, outputLines, emit, completion } = yield* setup({ command });
237 + yield* emit({ ...event, type: "output", data: "\x1b[?2004h" });
238 + const submitted = yield* Queue.take(writes);
239 + const cwd = yield* HostProcess.WorkingDirectory;
240 + const env = yield* HostProcess.Environment;
241 +
242 + // Enter becomes a newline at the terminal boundary; transport assertions below
243 + // cover line-editor submissions and canonical TTY limits that bash -c bypasses.
244 + const child = yield* Effect.gen(function* () {
245 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
246 + const handle = yield* spawner.spawn(
247 + ChildProcess.make(
248 + "/bin/bash",
249 + ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")],
250 + {
251 + cwd,
252 + env: { PATH: env.PATH },
253 + },
254 + ),
255 + );
256 + return yield* Effect.all(
257 + {
258 + stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
259 + stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
260 + exitCode: handle.exitCode,
261 + },
262 + { concurrency: "unbounded" },
263 + );
264 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
265 + yield* emit({ ...event, type: "output", data: submitted + "\n" });
266 + yield* emit({ ...event, type: "output", data: child.stdout + child.stderr });
267 + yield* emit({ ...event, type: "closed" });
268 + return {
269 + submitted,
270 + lines: yield* Queue.clear(outputLines),
271 + exitCode: (yield* completion).exitCode,
272 + };
273 +});
274 +
275 +describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => {
276 + it.live("submits one line while preserving multiline shell syntax and literal text", () =>
277 + Effect.gen(function* () {
278 + const result = yield* runObservedSetup(
279 + [
280 + "printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'",
281 + "cat <<'END'",
282 + "$literal \\path 雪",
283 + "END",
284 + "printf '%s\\n' done # trailing comment",
285 + ].join("\r\n"),
286 + );
287 + assert.equal(result.submitted.at(-1), "\r");
288 + assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/);
289 + assert.deepEqual(result.lines, [
290 + "it's ready",
291 + "literal \\n $(printf wrong) `printf wrong` café",
292 + "$literal \\path 雪",
293 + "done",
294 + ]);
295 + assert.equal(result.exitCode, 0);
296 + }),
297 + );
298 +
299 + it.live("completes long scripts without exceeding canonical terminal line limits", () =>
300 + Effect.gen(function* () {
301 + const expected = Array.from(
302 + { length: 120 },
303 + (_, index) => `line-${index}: café 雪 'quoted' \\path`,
304 + );
305 + const command = expected
306 + .map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`)
307 + .join("\n");
308 + const utf8 = new TextEncoder();
309 + assert.isAbove(utf8.encode(command).byteLength, 4_096);
310 +
311 + const result = yield* runObservedSetup(command);
312 + assert.deepEqual(result.lines, expected);
313 + assert.equal(result.exitCode, 0);
314 + assert.equal(result.submitted.at(-1), "\r");
315 + assert.notInclude(result.submitted, "\n");
316 + // The runner can write before the shell switches the terminal out of canonical mode.
317 + for (const line of result.submitted.slice(0, -1).split("\r")) {
318 + assert.isBelow(utf8.encode(line).byteLength, 1_024);
319 + }
320 + }),
321 + );
322 +
323 + it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () =>
324 + Effect.gen(function* () {
325 + const result = yield* runObservedSetup("printf '%s\\n' direct\\\n");
326 + assert.deepEqual(result.lines, ["direct"]);
327 + assert.equal(result.exitCode, 0);
328 + }),
329 + );
330 +
331 + it.live.each([
332 + { name: "an explicit exit", command: "exit 7", exitCode: 7 },
333 + { name: "a syntax error", command: "if then", exitCode: 2 },
334 + ])("reports a nonzero completion for $name", ({ command, exitCode }) =>
335 + Effect.gen(function* () {
336 + const result = yield* runObservedSetup(command);
337 + assert.equal(result.exitCode, exitCode);
338 + }),
339 + );
340 +});
apps/server/src/project/ProjectSetupScriptRunner.ts
+52 -2
@@ -177,7 +177,57 @@ function resolveCompletionShell(shell: string): CompletionShell | null {
177 return "posix";
178 }
179
180 -// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin.
180 +const utf8 = new TextEncoder();
181 +// Canonical TTY input (before a line editor starts reading) caps a line below 1 KiB on Linux.
182 +const POSIX_MAX_LINE_BYTES = 1_023;
183 +const POSIX_APPEND = '__t3_command="$__t3_command"';
184 +
185 +function encodePosixScript(text: string): string {
186 + let encoded = "";
187 + for (const character of text) {
188 + const code = character.charCodeAt(0);
189 + if (character === "'") {
190 + encoded += "'\\''";
191 + } else if (character === "\\" || code <= 0x1f || code === 0x7f) {
192 + encoded += `\\0${code.toString(8).padStart(3, "0")}`;
193 + } else {
194 + encoded += character;
195 + }
196 + }
197 + return encoded;
198 +}
199 +
200 +// Line editors run each submitted line on its own, so every line must be a complete command.
201 +function wrapPosixCommand(command: string, sentinel: string): string {
202 + const normalized = command.replace(/\r\n/g, "\n");
203 + // The `_` suffix keeps trailing newlines; the subshell contains exits and syntax errors.
204 + const evaluate = (payload: string) =>
205 + `( __t3_command=$(printf '%b_' ${payload}); eval "\${__t3_command%_}" ); printf '\\n${sentinel}%s\\n' "$?"`;
206 + const inline = evaluate(`'${encodePosixScript(normalized)}'`);
207 + if (utf8.encode(` ${inline}\r`).byteLength <= POSIX_MAX_LINE_BYTES) return inline;
208 +
209 + const maxChunkBytes = POSIX_MAX_LINE_BYTES - utf8.encode(` ${POSIX_APPEND}''\r`).byteLength;
210 + const lines: string[] = [];
211 + let prefix = "__t3_command=";
212 + let chunk = "";
213 + let chunkBytes = 0;
214 + for (const character of normalized) {
215 + const encoded = encodePosixScript(character);
216 + const bytes = utf8.encode(encoded).byteLength;
217 + if (chunkBytes + bytes > maxChunkBytes) {
218 + lines.push(`${prefix}'${chunk}'`);
219 + prefix = POSIX_APPEND;
220 + chunk = "";
221 + chunkBytes = 0;
222 + }
223 + chunk += encoded;
224 + chunkBytes += bytes;
225 + }
226 + lines.push(`${prefix}'${chunk}'`, `${evaluate('"$__t3_command"')}; unset __t3_command`);
227 + // The leading space gives every line the history suppression a short command gets.
228 + return lines.join("\r ");
229 +}
230 +
231 function wrapCommandForCompletion(
232 command: string,
233 shell: CompletionShell,
@@ -204,7 +254,7 @@ function wrapCommandForCompletion(
254 ].join("; ");
255 }
256 case "posix":
207 - return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
257 + return wrapPosixCommand(command, sentinel);
258 }
259 }
260