Skip to content

Commit 301c1a1

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

2 files changed

Lines changed: 179 additions & 9 deletions

File tree

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

Lines changed: 131 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
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 { ProjectId, type TerminalEvent, type TerminalSessionSnapshot } from "@t3tools/contracts";
45
import * as HostProcess from "@t3tools/shared/HostProcess";
56
import * as Deferred from "effect/Deferred";
67
import * as Effect from "effect/Effect";
78
import * as Fiber from "effect/Fiber";
89
import * as Layer from "effect/Layer";
910
import * as Queue from "effect/Queue";
11+
import * as Stream from "effect/Stream";
12+
import { ChildProcess, ChildProcessSpawner } from "effect/process";
1013
import { TestClock } from "effect/testing";
1114

1215
import * as ServerSettings from "../serverSettings.ts";
@@ -33,6 +36,7 @@ const openSnapshot = (history: string): TerminalSessionSnapshot => ({
3336
});
3437

3538
const makeHarness = Effect.fn(function* (options: {
39+
readonly command?: string;
3640
readonly history?: string;
3741
readonly opening?: Deferred.Deferred<void>;
3842
}) {
@@ -76,7 +80,7 @@ const makeHarness = Effect.fn(function* (options: {
7680
{
7781
id: "setup",
7882
name: "Setup",
79-
command: "vp i",
83+
command: options.command ?? "vp i",
8084
icon: "configure",
8185
runOnWorktreeCreate: true,
8286
},
@@ -88,7 +92,9 @@ const makeHarness = Effect.fn(function* (options: {
8892
return { start, listeners, writes, outputLines, emit };
8993
});
9094

91-
const setup = Effect.fn(function* (options: { readonly history?: string } = {}) {
95+
const setup = Effect.fn(function* (
96+
options: { readonly command?: string; readonly history?: string } = {},
97+
) {
9298
const harness = yield* makeHarness(options);
9399
const result = yield* harness.start;
94100
const completion = result.status === "started" ? result.completion : undefined;
@@ -110,15 +116,15 @@ describe("ProjectSetupScriptRunner", () => {
110116

111117
yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
112118
yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
113-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
119+
expect(yield* Queue.take(writes)).toContain("vp i");
114120
}),
115121
);
116122

117123
it.effect("types into a quiet shell that has no line editor", () =>
118124
Effect.gen(function* () {
119125
const { writes } = yield* setup();
120126
yield* TestClock.adjust("3 seconds");
121-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
127+
expect(yield* Queue.take(writes)).toContain("vp i");
122128
}),
123129
);
124130

@@ -140,7 +146,7 @@ describe("ProjectSetupScriptRunner", () => {
140146
yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
141147
// The restart lands inside a quiet window, so the next full window decides.
142148
yield* TestClock.adjust("6 seconds");
143-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
149+
expect(yield* Queue.take(writes)).toContain("vp i");
144150
}),
145151
);
146152

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

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

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,6 @@ function resolveCompletionShell(
161161
return "posix";
162162
}
163163

164-
// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin.
165164
function wrapCommandForCompletion(
166165
command: string,
167166
shell: CompletionShell,
@@ -173,8 +172,54 @@ function wrapCommandForCompletion(
173172
return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
174173
case "fish":
175174
return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
176-
case "posix":
177-
return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
175+
case "posix": {
176+
const normalized = command.replace(/\r\n/g, "\n");
177+
const encode = (text: string) => {
178+
let encoded = "";
179+
for (const character of text) {
180+
const code = character.charCodeAt(0);
181+
if (character === "'") {
182+
encoded += "'\\''";
183+
} else if (character === "\\" || code <= 0x1f || code === 0x7f) {
184+
encoded += `\\0${code.toString(8).padStart(3, "0")}`;
185+
} else {
186+
encoded += character;
187+
}
188+
}
189+
return encoded;
190+
};
191+
// The suffix preserves trailing newlines; the subshell contains exits and syntax errors.
192+
const evaluate = (payload: string) =>
193+
`( __t3_command=$(printf '%b_' ${payload}); eval "\${__t3_command%_}" ); printf '\\n${sentinel}%s\\n' "$?"`;
194+
const inline = evaluate(`'${encode(normalized)}'`);
195+
const utf8 = new TextEncoder();
196+
const maxLineBytes = 1_023;
197+
if (utf8.encode(` ${inline}\r`).byteLength <= maxLineBytes) return inline;
198+
199+
// Before readline starts, canonical TTY limits apply. Line editors also need each
200+
// submission to be complete, so accumulate encoded text with standalone assignments.
201+
const append = '__t3_command="$__t3_command"';
202+
const maxChunkBytes = maxLineBytes - utf8.encode(` ${append}''\r`).byteLength;
203+
const lines: string[] = [];
204+
let prefix = "__t3_command=";
205+
let chunk = "";
206+
let chunkBytes = 0;
207+
for (const character of normalized) {
208+
const encoded = encode(character);
209+
const bytes = utf8.encode(encoded).byteLength;
210+
if (chunkBytes + bytes > maxChunkBytes) {
211+
lines.push(`${prefix}'${chunk}'`);
212+
prefix = append;
213+
chunk = "";
214+
chunkBytes = 0;
215+
}
216+
chunk += encoded;
217+
chunkBytes += bytes;
218+
}
219+
lines.push(`${prefix}'${chunk}'`, `${evaluate('"$__t3_command"')}; unset __t3_command`);
220+
// Each physical line gets the same history suppression as a short command.
221+
return lines.join("\r ");
222+
}
178223
}
179224
}
180225

0 commit comments

Comments
 (0)