Skip to content

Commit 8c07e7f

Browse files
maria-rckssgaabdu4
andcommitted
fix(server): setup scripts complete with shell line editors
Co-authored-by: Abid A Gafoor <[email protected]>
1 parent 3d78e91 commit 8c07e7f

2 files changed

Lines changed: 178 additions & 8 deletions

File tree

‎apps/server/src/project/ProjectSetupScriptRunner.test.ts‎

Lines changed: 130 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
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";
34
import {
45
ProjectId,
56
TerminalNotRunningError,
67
type TerminalEvent,
78
type TerminalSessionSnapshot,
89
} from "@t3tools/contracts";
10+
import * as HostProcess from "@t3tools/shared/HostProcess";
911
import * as Deferred from "effect/Deferred";
1012
import * as Effect from "effect/Effect";
1113
import * as Fiber from "effect/Fiber";
1214
import * as Layer from "effect/Layer";
1315
import * as Queue from "effect/Queue";
16+
import * as Stream from "effect/Stream";
17+
import { ChildProcess, ChildProcessSpawner } from "effect/process";
1418
import { TestClock } from "effect/testing";
1519

1620
import * as ServerSettings from "../serverSettings.ts";
@@ -38,6 +42,7 @@ const openSnapshot = (history: string): TerminalSessionSnapshot => ({
3842
});
3943

4044
const makeHarness = Effect.fn(function* (options: {
45+
readonly command?: string;
4146
readonly history?: string;
4247
readonly opening?: Deferred.Deferred<void>;
4348
readonly shell?: string | null;
@@ -87,7 +92,7 @@ const makeHarness = Effect.fn(function* (options: {
8792
{
8893
id: "setup",
8994
name: "Setup",
90-
command: "vp i",
95+
command: options.command ?? "vp i",
9196
icon: "configure",
9297
runOnWorktreeCreate: true,
9398
},
@@ -101,6 +106,7 @@ const makeHarness = Effect.fn(function* (options: {
101106

102107
const setup = Effect.fn(function* (
103108
options: {
109+
readonly command?: string;
104110
readonly history?: string;
105111
readonly shell?: string | null;
106112
} = {},
@@ -135,15 +141,15 @@ describe("ProjectSetupScriptRunner", () => {
135141

136142
yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
137143
yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
138-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
144+
expect(yield* Queue.take(writes)).toContain("vp i");
139145
}),
140146
);
141147

142148
it.effect("types into a quiet shell that has no line editor", () =>
143149
Effect.gen(function* () {
144150
const { writes } = yield* setup();
145151
yield* TestClock.adjust("3 seconds");
146-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
152+
expect(yield* Queue.take(writes)).toContain("vp i");
147153
}),
148154
);
149155

@@ -165,7 +171,7 @@ describe("ProjectSetupScriptRunner", () => {
165171
yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
166172
// The restart lands inside a quiet window, so the next full window decides.
167173
yield* TestClock.adjust("6 seconds");
168-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
174+
expect(yield* Queue.take(writes)).toContain("vp i");
169175
}),
170176
);
171177

@@ -198,3 +204,122 @@ describe("ProjectSetupScriptRunner", () => {
198204
}),
199205
);
200206
});
207+
208+
const runObservedSetup = Effect.fnUntraced(function* (command: string, stdin = "") {
209+
const { writes, outputLines, emit, completion } = yield* setup({ command });
210+
yield* emit({ ...event, type: "output", data: "\x1b[?2004h" });
211+
const submitted = yield* Queue.take(writes);
212+
const cwd = yield* HostProcess.WorkingDirectory;
213+
const env = yield* HostProcess.Environment;
214+
215+
// Enter becomes a newline at the terminal boundary; transport assertions below
216+
// cover line-editor submissions and canonical TTY limits that bash -c bypasses.
217+
const child = yield* Effect.gen(function* () {
218+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
219+
const handle = yield* spawner.spawn(
220+
ChildProcess.make(
221+
"/bin/bash",
222+
["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")],
223+
{
224+
cwd,
225+
env: { PATH: env.PATH },
226+
stdin: Stream.make(new TextEncoder().encode(stdin)),
227+
},
228+
),
229+
);
230+
return yield* Effect.all(
231+
{
232+
stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
233+
stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
234+
exitCode: handle.exitCode,
235+
},
236+
{ concurrency: "unbounded" },
237+
);
238+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
239+
yield* emit({ ...event, type: "output", data: submitted + "\n" });
240+
yield* emit({ ...event, type: "output", data: child.stdout + child.stderr });
241+
yield* emit({ ...event, type: "closed" });
242+
return {
243+
submitted,
244+
lines: yield* Queue.clear(outputLines),
245+
exitCode: (yield* completion).exitCode,
246+
};
247+
});
248+
249+
describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => {
250+
it.live("submits one line while preserving multiline shell syntax and literal text", () =>
251+
Effect.gen(function* () {
252+
const result = yield* runObservedSetup(
253+
[
254+
"printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'",
255+
"cat <<'END'",
256+
"$literal \\path 雪",
257+
"END",
258+
"printf '%s\\n' done # trailing comment",
259+
].join("\r\n"),
260+
);
261+
assert.equal(result.submitted.at(-1), "\r");
262+
assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/);
263+
assert.deepEqual(result.lines, [
264+
"it's ready",
265+
"literal \\n $(printf wrong) `printf wrong` café",
266+
"$literal \\path 雪",
267+
"done",
268+
]);
269+
assert.equal(result.exitCode, 0);
270+
}),
271+
);
272+
273+
it.live("completes long scripts without exceeding canonical terminal line limits", () =>
274+
Effect.gen(function* () {
275+
const expected = Array.from(
276+
{ length: 120 },
277+
(_, index) => `line-${index}: café 雪 'quoted' \\path`,
278+
);
279+
const command = expected
280+
.map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`)
281+
.join("\n");
282+
const utf8 = new TextEncoder();
283+
assert.isAbove(utf8.encode(command).byteLength, 4_096);
284+
285+
const result = yield* runObservedSetup(command);
286+
assert.deepEqual(result.lines, expected);
287+
assert.equal(result.exitCode, 0);
288+
assert.equal(result.submitted.at(-1), "\r");
289+
assert.notInclude(result.submitted, "\n");
290+
// The runner can write before the shell switches the terminal out of canonical mode.
291+
for (const line of result.submitted.slice(0, -1).split("\r")) {
292+
assert.isBelow(utf8.encode(line).byteLength, 1_024);
293+
}
294+
}),
295+
);
296+
297+
it.live("leaves stdin available to the script without consuming completion commands", () =>
298+
Effect.gen(function* () {
299+
const result = yield* runObservedSetup(
300+
"read -r value\nprintf '%s\\n' \"$value\"",
301+
"from stdin \\path\n",
302+
);
303+
assert.deepEqual(result.lines, ["from stdin \\path"]);
304+
assert.equal(result.exitCode, 0);
305+
}),
306+
);
307+
308+
it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () =>
309+
Effect.gen(function* () {
310+
const result = yield* runObservedSetup("printf '%s\\n' direct\\\n");
311+
assert.deepEqual(result.lines, ["direct"]);
312+
assert.equal(result.exitCode, 0);
313+
}),
314+
);
315+
316+
it.live.each([
317+
{ name: "an explicit exit", command: "exit 7", exitCode: 7 },
318+
{ name: "a syntax error", command: "if then", exitCode: 2 },
319+
])("reports a nonzero completion for $name", ({ command, exitCode }) =>
320+
Effect.gen(function* () {
321+
const result = yield* runObservedSetup(command);
322+
assert.equal(result.exitCode, exitCode);
323+
}),
324+
);
325+
});

‎apps/server/src/project/ProjectSetupScriptRunner.ts‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,6 @@ function resolveCompletionShell(shell: string): CompletionShell | null {
176176
return "posix";
177177
}
178178

179-
// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin.
180179
function wrapCommandForCompletion(
181180
command: string,
182181
shell: CompletionShell,
@@ -188,8 +187,54 @@ function wrapCommandForCompletion(
188187
return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
189188
case "fish":
190189
return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
191-
case "posix":
192-
return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
190+
case "posix": {
191+
const normalized = command.replace(/\r\n/g, "\n");
192+
const encode = (text: string) => {
193+
let encoded = "";
194+
for (const character of text) {
195+
const code = character.charCodeAt(0);
196+
if (character === "'") {
197+
encoded += "'\\''";
198+
} else if (character === "\\" || code <= 0x1f || code === 0x7f) {
199+
encoded += `\\0${code.toString(8).padStart(3, "0")}`;
200+
} else {
201+
encoded += character;
202+
}
203+
}
204+
return encoded;
205+
};
206+
// The suffix preserves trailing newlines; the subshell contains exits and syntax errors.
207+
const evaluate = (payload: string) =>
208+
`( __t3_command=$(printf '%b_' ${payload}); eval "\${__t3_command%_}" ); printf '\\n${sentinel}%s\\n' "$?"`;
209+
const inline = evaluate(`'${encode(normalized)}'`);
210+
const utf8 = new TextEncoder();
211+
const maxLineBytes = 1_023;
212+
if (utf8.encode(` ${inline}\r`).byteLength <= maxLineBytes) return inline;
213+
214+
// Before readline starts, canonical TTY limits apply. Line editors also need each
215+
// submission to be complete, so accumulate encoded text with standalone assignments.
216+
const append = '__t3_command="$__t3_command"';
217+
const maxChunkBytes = maxLineBytes - utf8.encode(` ${append}''\r`).byteLength;
218+
const lines: string[] = [];
219+
let prefix = "__t3_command=";
220+
let chunk = "";
221+
let chunkBytes = 0;
222+
for (const character of normalized) {
223+
const encoded = encode(character);
224+
const bytes = utf8.encode(encoded).byteLength;
225+
if (chunkBytes + bytes > maxChunkBytes) {
226+
lines.push(`${prefix}'${chunk}'`);
227+
prefix = append;
228+
chunk = "";
229+
chunkBytes = 0;
230+
}
231+
chunk += encoded;
232+
chunkBytes += bytes;
233+
}
234+
lines.push(`${prefix}'${chunk}'`, `${evaluate('"$__t3_command"')}; unset __t3_command`);
235+
// Each physical line gets the same history suppression as a short command.
236+
return lines.join("\r ");
237+
}
193238
}
194239
}
195240

0 commit comments

Comments
 (0)