Skip to content

Commit f6ea10b

Browse files
sahrizviclaude
andcommitted
fix: record the mirror before the memory lookup; test run stdin on a real fd
- `mirrorBlock` records the workspace it uploads for before the memory-setting lookup, which can wait on the service, so an exit while that lookup is pending still gets the unsent-memory check. A confirmed "disabled" takes the record back. - The signal exit waits for the notice's stderr write before `process.exit`. - `ALTIMATE_RUN_STDIN_WAIT_MS` is capped at the `setTimeout` maximum, so a huge value is not turned into an immediate timeout. - New subprocess test runs `readRunStdin` on a real stdin: an idle `spawn` socket times out and the process exits, a written socket and a late write with nothing else to run come through, and a slow shell pipe is read. - The release-validation test checks that `readRunStdin(` sits inside the non-TTY guard's block, whatever the whitespace. - Tests: the status stub checks the binding it is given; the `workspace list` parser test keeps another test's exit code. - Docs: drop the `ssh` example, which depends on how sshd hands over stdin. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011chv9Rmu7jQXokum1WNcs7
1 parent 533cfe8 commit f6ea10b

11 files changed

Lines changed: 103 additions & 10 deletions

File tree

‎docs/docs/usage/cli.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ altimate --print-logs --log-level DEBUG run "test query"
190190
altimate run --no-trace "quick question"
191191
```
192192

193-
`run` reads piped input to the end, however long the command before the pipe takes. One exception: when `run` already has a message or `--command` and its stdin is a socket, which is what an agent's shell tool or a Node `spawn` hands a child, it waits only 3 seconds for the first byte and then continues without stdin. That can also catch a slow pipe that reaches `run` through a socket, such as `slow-cmd | ssh host altimate-code run "summarize"`. Set `ALTIMATE_RUN_STDIN_WAIT_MS` to change that wait, or to `0` to always wait. A caller that never writes to or closes stdin, and whose stdin is not a socket (for example a pipe on Windows), should redirect it from an empty source: `< /dev/null`, or `< NUL` in `cmd.exe`.
193+
`run` reads piped input to the end, however long the command before the pipe takes. One exception: when `run` already has a message or `--command` and its stdin is a socket, which is what an agent's shell tool or a Node `spawn` hands a child, it waits only 3 seconds for the first byte and then continues without stdin. Set `ALTIMATE_RUN_STDIN_WAIT_MS` to change that wait, or to `0` to always wait. A caller that never writes to or closes stdin, and whose stdin is not a socket (for example a pipe on Windows), should redirect it from an empty source: `< /dev/null`, or `< NUL` in `cmd.exe`.
194194

195195
For CI pipelines and headless automation, see [CI & Automation](ci-headless.md).
196196

‎packages/opencode/src/altimate/cli/run-stdin.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,16 @@ import { fstatSync } from "fs"
44
/** How long `run` waits for the first byte on a socket stdin. */
55
export const STDIN_WAIT_MS = 3000
66

7+
/** The longest delay `setTimeout` honours; a larger one fires at once. */
8+
const MAX_TIMER_MS = 2_147_483_647
9+
710
/** `ALTIMATE_RUN_STDIN_WAIT_MS` overrides the wait, for a caller that writes its stdin late; 0 waits for EOF. */
811
export function stdinWaitMs(env: Record<string, string | undefined> = process.env): number {
912
const raw = env["ALTIMATE_RUN_STDIN_WAIT_MS"]?.trim()
1013
if (!raw) return STDIN_WAIT_MS
1114
const ms = Number(raw)
12-
return Number.isFinite(ms) && ms >= 0 ? ms : STDIN_WAIT_MS
15+
if (!Number.isFinite(ms) || ms < 0) return STDIN_WAIT_MS
16+
return Math.min(ms, MAX_TIMER_MS)
1317
}
1418

1519
export interface StdinSource {

‎packages/opencode/src/altimate/workspace/memory-sync.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -972,10 +972,15 @@ export async function mirrorBlock(block: MemoryBlock, directory?: string): Promi
972972
// binding governs only whether we upload at all.
973973
const binding = await currentBinding(directory)
974974
if (!binding) return
975-
const memory = await memoryStatus(binding)
976-
if (memory === "disabled") return
977-
// Recorded before an unknown setting returns: that block is left unsent too.
975+
// Recorded before the memory-setting lookup, which can wait on the service: an exit while it is pending
976+
// leaves this block unsent too. Taken back only on a confirmed "disabled".
977+
const previous = mirrorRequests.last
978978
mirrorRequests.last = { directory, binding }
979+
const memory = await memoryStatus(binding)
980+
if (memory === "disabled") {
981+
mirrorRequests.last = previous
982+
return
983+
}
979984
if (memory !== "enabled") return
980985
await push(block, binding, undefined, directory)
981986
})

‎packages/opencode/src/cli/cmd/run.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1561,7 +1561,8 @@ You are speaking to a non-technical business executive. Follow these rules stric
15611561
const notice = await unsent
15621562
?.then((m) => m?.unsentMemoryNoticeAfterRun(process.cwd(), 1_000))
15631563
.catch(() => null)
1564-
if (notice) process.stderr.write(notice + EOL)
1564+
// process.exit does not wait for a pending write to a piped stderr.
1565+
if (notice) await new Promise<void>((resolve) => process.stderr.write(notice + EOL, () => resolve()))
15651566
process.exit(code)
15661567
})
15671568
}

‎packages/opencode/test/altimate/cli/unsent-memory.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ function deps(over: Partial<UnsentMemoryDeps> = {}): UnsentMemoryDeps & { calls:
1010
calls: 0,
1111
dirs: [] as string[],
1212
target: (): MirrorTarget | undefined => ({ directory: "/bound", binding }),
13-
status: async (directory: string) => {
13+
status: async (directory: string, given: MirrorTarget["binding"]) => {
14+
expect(given).toBe(binding)
1415
d.dirs.push(directory)
1516
d.calls++
1617
return { binding, memory: { local: 3, unsynced: 2 }, skillsEnabled: true, skillsSyncedAt: null } as any

‎packages/opencode/test/altimate/workspace/memory-sync.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,22 @@ describe("mirrorBlock", () => {
459459
expect(lastMirrorTarget()).toEqual({ directory: "/repo", binding: BINDING as any })
460460
})
461461

462+
test("the mirror is recorded while the memory-setting lookup is still pending, so an exit then still checks", async () => {
463+
const inner = globalThis.fetch
464+
let release!: () => void
465+
const held = new Promise<void>((resolve) => (release = resolve))
466+
globalThis.fetch = (async (input: any, init?: any) => {
467+
if (String(input).includes("/datamates/") && !String(input).includes("/memory")) await held
468+
return inner(input, init)
469+
}) as typeof fetch
470+
const mirror = mirrorBlock(block({ id: "pending-lookup" }), "/repo")
471+
await Bun.sleep(20)
472+
expect(lastMirrorTarget()).toEqual({ directory: "/repo", binding: BINDING as any })
473+
release()
474+
await mirror
475+
globalThis.fetch = inner
476+
})
477+
462478
test("a workspace with memory turned off is not recorded: the block stays local by design", async () => {
463479
workspaces = [{ id: 42, name: "acme", memory_enabled: false }]
464480
await mirrorBlock(block({ id: "kept-local" }), "/repo")
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// altimate_change - new file
2+
// Reads this process's real stdin with `readRunStdin`, as `run` does, and prints the result.
3+
import { readRunStdin, stdinWaitMs } from "../../../../src/altimate/cli/run-stdin"
4+
5+
const result = await readRunStdin(undefined, stdinWaitMs(), process.argv[2] !== "unbounded")
6+
process.stdout.write(JSON.stringify(result))
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// altimate_change - new file
2+
// `readRunStdin` on a real stdin: the other tests inject a fake source, so only these check that
3+
// `fstatSync(0)` sees a socket for a Node `spawn` and a FIFO for a shell pipeline.
4+
import { describe, expect, test } from "bun:test"
5+
import { spawn } from "node:child_process"
6+
import path from "node:path"
7+
8+
const FIXTURE = path.join(import.meta.dir, "fixtures", "read-run-stdin.ts")
9+
const env = { ...process.env, ALTIMATE_RUN_STDIN_WAIT_MS: "200" }
10+
11+
function collect(child: ReturnType<typeof spawn>): Promise<{ code: number | null; out: string; ms: number }> {
12+
const started = Date.now()
13+
let out = ""
14+
child.stdout!.on("data", (chunk) => (out += chunk))
15+
return new Promise((resolve) => child.on("exit", (code) => resolve({ code, out, ms: Date.now() - started })))
16+
}
17+
18+
describe("readRunStdin on a real stdin", () => {
19+
test("a socket stdin that is never written or closed times out, and the process exits on its own", async () => {
20+
const child = spawn(process.execPath, [FIXTURE], { env })
21+
const result = await collect(child)
22+
expect(result.code).toBe(0)
23+
expect(JSON.parse(result.out)).toEqual({ text: "", timedOut: true })
24+
expect(result.ms).toBeLessThan(10_000)
25+
})
26+
27+
test("a socket stdin that is written and closed comes through", async () => {
28+
const child = spawn(process.execPath, [FIXTURE], { env })
29+
child.stdin!.end("from the caller\n")
30+
expect(JSON.parse((await collect(child)).out)).toEqual({ text: "from the caller\n", timedOut: false })
31+
})
32+
33+
test("with nothing else to run, a socket written after the wait still comes through", async () => {
34+
const child = spawn(process.execPath, [FIXTURE, "unbounded"], { env })
35+
setTimeout(() => child.stdin!.end("the prompt\n"), 600)
36+
expect(JSON.parse((await collect(child)).out)).toEqual({ text: "the prompt\n", timedOut: false })
37+
})
38+
39+
test("a shell pipeline is read to EOF even when its first byte comes after the wait", async () => {
40+
const child = spawn("sh", ["-c", `sleep 0.6; echo piped | "${process.execPath}" "${FIXTURE}"`], { env })
41+
expect(JSON.parse((await collect(child)).out)).toEqual({ text: "piped\n", timedOut: false })
42+
})
43+
})

‎packages/opencode/test/cli/run/run-stdin.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,10 @@ describe("stdinWaitMs", () => {
9595
expect(stdinWaitMs({ ALTIMATE_RUN_STDIN_WAIT_MS: " 0 " })).toBe(0)
9696
})
9797

98+
test("a wait longer than a timer can hold is capped, not turned into an immediate timeout", () => {
99+
expect(stdinWaitMs({ ALTIMATE_RUN_STDIN_WAIT_MS: "99999999999" })).toBe(2_147_483_647)
100+
})
101+
98102
test("an unusable value keeps the default", () => {
99103
for (const raw of ["", " ", "soon", "-1", "Infinity"])
100104
expect(stdinWaitMs({ ALTIMATE_RUN_STDIN_WAIT_MS: raw })).toBe(STDIN_WAIT_MS)

‎packages/opencode/test/cli/workspace-command.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,11 +457,15 @@ describe("link --workspace / --create without prompting", () => {
457457

458458
describe("workspace list through the command parser", () => {
459459
const original = { isConfigured: AltimateApi.isConfigured, listDatamates: WorkspaceApi.listDatamates, write: process.stdout.write }
460+
let priorExitCode: typeof process.exitCode
461+
beforeEach(() => {
462+
priorExitCode = process.exitCode
463+
})
460464
afterEach(() => {
461465
;(AltimateApi as any).isConfigured = original.isConfigured
462466
;(WorkspaceApi as any).listDatamates = original.listDatamates
463467
process.stdout.write = original.write
464-
process.exitCode = 0
468+
process.exitCode = priorExitCode ?? 0
465469
})
466470

467471
test("`workspace list --json` is registered and prints the account's workspaces", async () => {

0 commit comments

Comments
 (0)