Skip to content

Commit 6551112

Browse files
sahrizviclaude
andcommitted
fix: bound the stdin wait only for sockets; time-limit the unsent-memory check
Consensus review follow-ups. - `readRunStdin` applies the 3s first-byte wait only when stdin is a socket, which is what an agent's shell tool or a Node `spawn` hands a child. A shell pipeline is a FIFO and is read to EOF as before, so `dbt build | altimate-code run …` keeps its input however long the producer takes. - The exit check for unsent memory is capped at 5s, reports an unreadable local count as unknown, and is injectable and tested (gating, unknown, timeout, unlinked). - Notice wording: "N memories on this machine are not in the workspace yet", since the count is the project's, not only this run's. - A test ties `SIGN_IN_COMMAND`'s `--method` to a label the `altimate-backend` provider actually has. - New-file markers; the empty-record comment folded into its docblock. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011chv9Rmu7jQXokum1WNcs7
1 parent 63f7334 commit 6551112

8 files changed

Lines changed: 130 additions & 29 deletions

File tree

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

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1+
// altimate_change - new file
12
import { fstatSync } from "fs"
23

3-
/** How long `run` waits for the first byte on a stdin that is not a TTY or a file. */
4+
/** How long `run` waits for the first byte on a socket stdin. */
45
export const STDIN_WAIT_MS = 3000
56

67
export interface StdinSource {
78
/** True when fd 0 is a regular file (`run < prompt.txt`), which always reaches EOF. */
89
isFile(): boolean
10+
/** True when fd 0 is a socket: what an agent's shell tool or a Node `spawn` hands a child. A shell
11+
* pipeline (`cmd | altimate-code run`) is a FIFO instead. */
12+
isSocket(): boolean
913
readAll(): Promise<string>
1014
stream(): ReadableStream<Uint8Array>
1115
}
@@ -18,6 +22,13 @@ export const bunStdin: StdinSource = {
1822
return false
1923
}
2024
},
25+
isSocket() {
26+
try {
27+
return fstatSync(0).isSocket()
28+
} catch {
29+
return false
30+
}
31+
},
2132
readAll: () => Bun.stdin.text(),
2233
stream: () => Bun.stdin.stream(),
2334
}
@@ -26,15 +37,16 @@ export const bunStdin: StdinSource = {
2637
* Read text piped into `altimate-code run`, without waiting on a stdin that never sends anything.
2738
*
2839
* Agents that shell out to `run` (Claude Code's Bash tool, a Node `spawn` with default stdio) hand
29-
* it a pipe or socket they never write to or close. Reading that to EOF blocks forever, so a
30-
* delegated task hangs before it starts. A file is read in full; any other stdin is read only if
31-
* its first chunk arrives within `waitMs`, and then to EOF.
40+
* it a socket they never write to or close. Reading that to EOF blocks forever, so a delegated task
41+
* hangs before it starts. A socket is read only if its first chunk arrives within `waitMs`, and then
42+
* to EOF. Anything else (a file, or a shell pipeline whose producer may take minutes, like
43+
* `dbt build | altimate-code run`) is read to EOF as before.
3244
*/
3345
export async function readRunStdin(
3446
source: StdinSource = bunStdin,
3547
waitMs: number = STDIN_WAIT_MS,
3648
): Promise<{ text: string; timedOut: boolean }> {
37-
if (source.isFile()) return { text: await source.readAll(), timedOut: false }
49+
if (source.isFile() || !source.isSocket()) return { text: await source.readAll(), timedOut: false }
3850
const reader = source.stream().getReader()
3951
let timer: ReturnType<typeof setTimeout> | undefined
4052
try {

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

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,52 @@
22
import * as Manage from "@/altimate/workspace/manage"
33
import { mirrorWasRequested } from "@/altimate/workspace/memory-sync"
44

5+
/** How long `run`'s exit waits for the count. Without a local link row, `Manage.status` asks the service. */
6+
export const UNSENT_CHECK_MS = 5000
7+
58
/**
6-
* What `run` prints at exit about memory saved here that the workspace has not received, or null when
7-
* there is nothing to say. `unsynced` is `workspace status`'s count: an upload that failed, was deferred
8-
* or declined, or was still in flight when the exit flush gave up is pending there; a block deleted
9-
* since is not.
9+
* What `run` prints at exit about memory on this machine that the workspace has not received, or null
10+
* when there is nothing to say. `unsynced` is `workspace status`'s count for the project, not only this
11+
* run's: an upload that failed, was deferred or declined, or was still in flight when the exit flush gave
12+
* up is pending there; a block deleted since is not.
1013
*/
1114
export function unsentMemoryNotice(unsynced: number | null): string | null {
1215
if (unsynced === null)
1316
return "Could not confirm that the memory saved here reached the workspace. Run `altimate-code workspace status` to check."
1417
if (unsynced === 0) return null
1518
return (
16-
`${unsynced === 1 ? "1 memory saved here is" : `${unsynced} memories saved here are`} not in the workspace yet. ` +
19+
`${unsynced === 1 ? "1 memory on this machine is" : `${unsynced} memories on this machine are`} not in the workspace yet. ` +
1720
`Run \`altimate-code workspace sync\` to send ${unsynced === 1 ? "it" : "them"}.`
1821
)
1922
}
2023

21-
/** Counted only when this process saved memory for a linked workspace, so other runs pay nothing. */
22-
export async function unsentMemoryNoticeAfterRun(directory: string): Promise<string | null> {
23-
if (!mirrorWasRequested()) return null
24-
const report = await Manage.status(directory)
24+
export interface UnsentMemoryDeps {
25+
requested(): boolean
26+
status(directory: string): Promise<Manage.StatusReport>
27+
timeoutMs: number
28+
}
29+
30+
const defaultDeps: UnsentMemoryDeps = {
31+
requested: mirrorWasRequested,
32+
status: (directory) => Manage.status(directory),
33+
timeoutMs: UNSENT_CHECK_MS,
34+
}
35+
36+
/** Counted only when this process saved memory for a linked workspace, so other runs pay nothing. A count
37+
* that cannot be read, or not in time, is reported as unknown. */
38+
export async function unsentMemoryNoticeAfterRun(
39+
directory: string,
40+
deps: UnsentMemoryDeps = defaultDeps,
41+
): Promise<string | null> {
42+
if (!deps.requested()) return null
43+
let timer: ReturnType<typeof setTimeout> | undefined
44+
const report = await Promise.race([
45+
deps.status(directory).catch(() => null),
46+
new Promise<null>((resolve) => {
47+
timer = setTimeout(() => resolve(null), deps.timeoutMs)
48+
}),
49+
]).finally(() => clearTimeout(timer))
50+
if (!report || report.memoryUnreadable) return unsentMemoryNotice(null)
2551
if (!report.binding || !report.memory) return null
2652
return unsentMemoryNotice(report.memory.unsynced)
2753
}

‎packages/opencode/src/altimate/workspace/empty-record-path.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// altimate_change - new file
12
import path from "path"
23
import { createHash } from "node:crypto"
34
import { Global } from "@/global"

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -654,12 +654,10 @@ export async function recentlySynced(directory: string): Promise<boolean> {
654654
/** Which account each project's snapshot was last fetched for. */
655655
const syncedFor = store.syncedFor
656656

657-
/* The record that a project's workspace had no custom skills at the last sync (account key +
658-
* workspace id) lives at `emptyRecordPath`. On disk rather than on `globalThis`, which is per
659-
* thread: an unlink in the TUI thread has to clear what the prompt worker's sync recorded, and the
660-
* other way round. */
661-
662-
/** The record as written: `<key>\n<write id>`. The write id tells one sync's record from another
657+
/** The record as written: `<key>\n<write id>`, at `emptyRecordPath` (./empty-record-path), saying the
658+
* project's workspace had no custom skills at the last sync (account key + workspace id). On disk rather
659+
* than on `globalThis`, which is per thread: an unlink in the TUI thread has to clear what the prompt
660+
* worker's sync recorded, and the other way round. The write id tells one sync's record from another
663661
* sync's record for the same key, so a sync only ever withdraws the record it wrote itself. */
664662
async function readEmptyRecordRaw(canon: string): Promise<string | null> {
665663
try {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -553,8 +553,8 @@ export const RunCommand = cmd({
553553
// into a stall: undefined stdin satisfied the guard and we then awaited
554554
// Bun.stdin.text() on a stream that would never EOF. Skip the read
555555
// entirely when there is no stdin to read from. An agent's shell tool can
556-
// also hand `run` a stdin it never writes to or closes, so the read is
557-
// bounded: see `readRunStdin`.
556+
// also hand `run` a socket stdin it never writes to or closes, so that
557+
// read is bounded: see `readRunStdin`.
558558
if (process.stdin && !process.stdin.isTTY) {
559559
const { readRunStdin, STDIN_WAIT_MS } = await import("../../altimate/cli/run-stdin")
560560
const piped = await readRunStdin()
Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,22 @@
11
// altimate_change - new file
22
import { describe, expect, test } from "bun:test"
3-
import { unsentMemoryNotice } from "../../../src/altimate/cli/unsent-memory"
3+
import { unsentMemoryNotice, unsentMemoryNoticeAfterRun, type UnsentMemoryDeps } from "../../../src/altimate/cli/unsent-memory"
4+
5+
const binding = { datamateId: 46, datamateName: "Growth" } as any
6+
7+
function deps(over: Partial<UnsentMemoryDeps> = {}): UnsentMemoryDeps & { calls: number } {
8+
const d = {
9+
calls: 0,
10+
requested: () => true,
11+
timeoutMs: 1000,
12+
status: async () => {
13+
d.calls++
14+
return { binding, memory: { local: 3, unsynced: 2 }, skillsEnabled: true, skillsSyncedAt: null } as any
15+
},
16+
...over,
17+
}
18+
return d
19+
}
420

521
describe("unsentMemoryNotice", () => {
622
test("says nothing when every memory reached the workspace", () => {
@@ -9,14 +25,44 @@ describe("unsentMemoryNotice", () => {
925

1026
test("counts what is pending and points at workspace sync", () => {
1127
expect(unsentMemoryNotice(1)).toBe(
12-
"1 memory saved here is not in the workspace yet. Run `altimate-code workspace sync` to send it.",
28+
"1 memory on this machine is not in the workspace yet. Run `altimate-code workspace sync` to send it.",
1329
)
1430
expect(unsentMemoryNotice(3)).toBe(
15-
"3 memories saved here are not in the workspace yet. Run `altimate-code workspace sync` to send them.",
31+
"3 memories on this machine are not in the workspace yet. Run `altimate-code workspace sync` to send them.",
1632
)
1733
})
1834

1935
test("an unknown count is reported as unknown, never as zero", () => {
2036
expect(unsentMemoryNotice(null)).toContain("workspace status")
2137
})
2238
})
39+
40+
describe("unsentMemoryNoticeAfterRun", () => {
41+
test("a run that saved no memory does not check at all", async () => {
42+
const d = deps({ requested: () => false })
43+
expect(await unsentMemoryNoticeAfterRun("/p", d)).toBeNull()
44+
expect(d.calls).toBe(0)
45+
})
46+
47+
test("a run that saved memory reports the project's pending count", async () => {
48+
expect(await unsentMemoryNoticeAfterRun("/p", deps())).toContain("2 memories on this machine")
49+
})
50+
51+
test("an unreadable local count, a failed check or a slow one is reported as unknown", async () => {
52+
const unreadable = deps({ status: async () => ({ binding, memory: null, memoryUnreadable: true }) as any })
53+
expect(await unsentMemoryNoticeAfterRun("/p", unreadable)).toContain("Could not confirm")
54+
const failed = deps({ status: async () => Promise.reject(new Error("down")) })
55+
expect(await unsentMemoryNoticeAfterRun("/p", failed)).toContain("Could not confirm")
56+
const slow = deps({ timeoutMs: 20, status: () => new Promise(() => {}) })
57+
const started = Date.now()
58+
expect(await unsentMemoryNoticeAfterRun("/p", slow)).toContain("Could not confirm")
59+
expect(Date.now() - started).toBeLessThan(1000)
60+
})
61+
62+
test("an unlinked project, or memory off in this build, says nothing", async () => {
63+
const unlinked = deps({ status: async () => ({ binding: null, memory: { local: 1, unsynced: 0 } }) as any })
64+
expect(await unsentMemoryNoticeAfterRun("/p", unlinked)).toBeNull()
65+
const off = deps({ status: async () => ({ binding, memory: null }) as any })
66+
expect(await unsentMemoryNoticeAfterRun("/p", off)).toBeNull()
67+
})
68+
})

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@ import { readRunStdin, type StdinSource } from "../../../src/altimate/cli/run-st
33

44
const encoder = new TextEncoder()
55

6-
/** A stdin whose stream yields `chunks` (the first at once, each later one after `delayMs`), then ends unless `open` is set. */
7-
function source(opts: { chunks?: string[]; delayMs?: number; open?: boolean; file?: string }): StdinSource & {
6+
/** A socket stdin (unless `file` or `fifo` is set) whose stream yields `chunks` (the first at once, each later one after `delayMs`), then ends unless `open` is set. */
7+
function source(opts: { chunks?: string[]; delayMs?: number; open?: boolean; file?: string; fifo?: string }): StdinSource & {
88
cancelled: () => boolean
99
} {
1010
let cancelled = false
1111
return {
1212
cancelled: () => cancelled,
1313
isFile: () => opts.file !== undefined,
14-
readAll: async () => opts.file ?? "",
14+
isSocket: () => opts.file === undefined && opts.fifo === undefined,
15+
readAll: async () => opts.file ?? opts.fifo ?? "",
1516
stream: () =>
1617
new ReadableStream<Uint8Array>({
1718
async start(controller) {
@@ -35,6 +36,11 @@ describe("readRunStdin", () => {
3536
expect(result).toEqual({ text: "from a file\n", timedOut: false })
3637
})
3738

39+
test("a shell pipeline (not a socket) is read to EOF however long its producer takes", async () => {
40+
const result = await readRunStdin(source({ fifo: "dbt build output\n" }), 10)
41+
expect(result).toEqual({ text: "dbt build output\n", timedOut: false })
42+
})
43+
3844
test("reads piped text to EOF", async () => {
3945
const result = await readRunStdin(source({ chunks: ["hello ", "world\n"] }), 1000)
4046
expect(result).toEqual({ text: "hello world\n", timedOut: false })

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ import {
1313
runUnlink,
1414
type WorkspaceDeps,
1515
} from "../../src/cli/cmd/workspace"
16-
import { linkHeadless, matchWorkspace, type LinkHeadlessDeps } from "../../src/cli/cmd/link"
16+
import { SIGN_IN_COMMAND, linkHeadless, matchWorkspace, type LinkHeadlessDeps } from "../../src/cli/cmd/link"
17+
import { AltimateAuthPlugin } from "../../src/altimate/plugin/altimate"
1718

1819
const binding = {
1920
datamateId: 35,
@@ -23,6 +24,17 @@ const binding = {
2324
linkedAt: 0,
2425
} as any
2526

27+
describe("SIGN_IN_COMMAND", () => {
28+
test("names a login method the altimate-backend provider has, so --method skips the picker", async () => {
29+
const hooks = await AltimateAuthPlugin({} as any)
30+
expect(hooks.auth?.provider).toBe("altimate-backend")
31+
const labels = hooks.auth!.methods.map((m) => m.label)
32+
const named = SIGN_IN_COMMAND.match(/--method "([^"]+)"/)?.[1]
33+
expect(named).toBeDefined()
34+
expect(labels).toContain(named!)
35+
})
36+
})
37+
2638
describe("workspace status wording", () => {
2739
test("an unlinked project says so and how to link", () => {
2840
const lines = describeStatus({ binding: null, memory: null, skillsEnabled: true, skillsSyncedAt: null })

0 commit comments

Comments
 (0)