From 5a6dda8d8de6a1f6202d579e59cb1c481c6b83e3 Mon Sep 17 00:00:00 2001 From: ATou <11880502+atou42@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:20:08 +0800 Subject: [PATCH 1/4] fix(cli): unify Space ref handling across commands and keep sessions tail --json clean --- packages/cli/src/commands/run.ts | 52 ++-- packages/cli/src/commands/search.ts | 24 +- packages/cli/src/commands/spaces.ts | 152 +++++++---- packages/cli/src/help-path.ts | 4 +- packages/cli/src/space.ts | 13 +- packages/cli/tests/help-path.test.ts | 3 + packages/cli/tests/run.test.ts | 74 +++++- packages/cli/tests/space-ref-cli.test.ts | 323 +++++++++++++++++++++++ packages/cli/tests/space.test.ts | 4 +- 9 files changed, 556 insertions(+), 93 deletions(-) create mode 100644 packages/cli/tests/space-ref-cli.test.ts diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts index b71543ac2..55be082bf 100644 --- a/packages/cli/src/commands/run.ts +++ b/packages/cli/src/commands/run.ts @@ -53,17 +53,19 @@ function topLevelRunIndex(argv: string[]): number { return -1; } -function parseSpaceId(tokens: string[]): string | undefined { - for (let index = 0; index < tokens.length; index += 1) { - const token = tokens[index] ?? ""; - if (token === "-s" || token === "--space") { - const value = tokens[index + 1]; - if (!value) return error("Missing space", `${token} requires a value`); - return value.trim() || undefined; - } - if (token.startsWith("--space=")) return token.slice("--space=".length).trim() || undefined; +function parseSpaceOption(tokens: string[], index: number): { value: string; nextIndex: number } | null { + const token = tokens[index] ?? ""; + if (token === "-s" || token === "--space") { + const value = tokens[index + 1]?.trim(); + if (!value) return error("Missing space", `${token} requires a value`); + return { value, nextIndex: index + 1 }; + } + if (token.startsWith("--space=")) { + const value = token.slice("--space=".length).trim(); + if (!value) return error("Missing space", "--space requires a value"); + return { value, nextIndex: index }; } - return undefined; + return null; } export async function parseRunCliOptions( @@ -76,12 +78,20 @@ export async function parseRunCliOptions( const beforeRun = argv.slice(0, runIndex); const afterRun = argv.slice(runIndex + 1); + let explicitSpaceId: string | undefined; for (let index = 0; index < beforeRun.length; index += 1) { - index = consumeBaseUrlOption(beforeRun, index) ?? index; - if (beforeRun[index] === "-s" || beforeRun[index] === "--space") index += 1; + const endpointIndex = consumeBaseUrlOption(beforeRun, index); + if (endpointIndex !== null) { + index = endpointIndex; + continue; + } + const spaceOption = parseSpaceOption(beforeRun, index); + if (spaceOption) { + explicitSpaceId = spaceOption.value; + index = spaceOption.nextIndex; + } } - const explicitSpaceId = parseSpaceId(beforeRun) ?? process.env.COHUB_SPACE_ID?.trim() ?? ""; let json = beforeRun.includes("--json"); let async = false; let commandOption: string | null = null; @@ -96,6 +106,13 @@ export async function parseRunCliOptions( continue; } + const spaceOption = parseSpaceOption(afterRun, index); + if (spaceOption) { + explicitSpaceId = spaceOption.value; + index = spaceOption.nextIndex; + continue; + } + if (token === "-h" || token === "--help") { printRunHelp(); process.exit(0); @@ -159,9 +176,11 @@ export function printRunHelp(): void { process.stdout.write(` Usage: cohub [--base-url ] [-s ] run [options] -- + cohub run [-s ] [options] -- cohub [-s ] run --command Options: + -s, --space Target Space: ID, slug, or username/slug --base-url API base URL (overrides COHUB_BASE_URL) -c, --command Shell command to execute in the space workspace --async Queue the command and return immediately @@ -169,9 +188,10 @@ Options: -h, --help Show this help Examples: - cohub -s run --command "git status" - cohub -s run --async --command "pnpm test" - cohub -s run -- git status -sb + cohub -s run --command "git status" + cohub run -s -- git status -sb + cohub -s run --async --command "pnpm test" + cohub -s run -- git status -sb Notes: - Without -s or COHUB_SPACE_ID, the command uses the current directory Runtime binding; it never falls back to Home. diff --git a/packages/cli/src/commands/search.ts b/packages/cli/src/commands/search.ts index 540ddec61..9da4500ce 100644 --- a/packages/cli/src/commands/search.ts +++ b/packages/cli/src/commands/search.ts @@ -1,7 +1,8 @@ -import { isUuid, type GlobalSearchResult, type GlobalSearchType } from "@neta-art/cohub"; +import type { GlobalSearchResult, GlobalSearchType } from "@neta-art/cohub"; import type { Command } from "commander"; import { createClient } from "../client.js"; -import { formatLocalDateTime, table, json as outJson, jsonRequested, error, handleHttp, truncateText, type Row } from "../output.js"; +import { formatLocalDateTime, table, json as outJson, jsonRequested, error, truncateText, type Row } from "../output.js"; +import { explicitSpaceFlag, failSpaceTarget, resolveSpaceRef } from "../space.js"; const DEFAULT_LIMIT = 20; const MAX_TITLE_LENGTH = 72; @@ -50,9 +51,7 @@ function parseTypes(value: string | undefined): GlobalSearchType[] | undefined { function parseSearchInput(opts: SearchCliOptions) { const types = parseTypes(opts.types); - const spaceId = opts.spaceId?.trim(); - if (spaceId && !isUuid(spaceId)) throw new Error("Invalid space id"); - return { types, spaceId: spaceId || undefined, labelRef: opts.labelRef?.trim() || undefined }; + return { types, labelRef: opts.labelRef?.trim() || undefined }; } function rowsFor(items: GlobalSearchResult[]): Row[] { @@ -73,7 +72,7 @@ export function registerSearch(program: Command): void { .argument("[query]", "Search query") .option("--limit ", "Maximum results, 1-50", String(DEFAULT_LIMIT)) .option("--types ", "Comma-separated result types: chat,space,label") - .option("--space-id ", "Limit search to a space") + .option("--space-id ", "Limit search to a space (ID, home, slug, or username/slug)") .option("--label-ref ", "Search items under an exact label ref") .option("--json", "Output as JSON") .addHelpText("after", ` @@ -81,22 +80,25 @@ export function registerSearch(program: Command): void { Examples: cohub search "release notes" cohub search "failing tests" --limit 10 - cohub search "bug" --types chat --space-id + cohub search "bug" --types chat --space-id + cohub -s search "bug" --types chat cohub search --types label --label-ref bug cohub search "login" --types label --label-ref bug cohub search "design review" --json `) - .action(async (query: string | undefined, opts: SearchCliOptions) => { + .action(async (query: string | undefined, opts: SearchCliOptions, command: Command) => { const client = createClient(); try { const input = parseSearchInput(opts); const q = query ?? ""; if (!q.trim() && !input.labelRef) return error("Search query is required unless --label-ref is provided."); + const spaceRef = opts.spaceId !== undefined ? opts.spaceId.trim() : explicitSpaceFlag(command); + const spaceId = spaceRef !== null ? await resolveSpaceRef(spaceRef) : undefined; const result = await client.search.query({ q, limit: clampLimit(opts.limit), types: input.types, - spaceId: input.spaceId, + spaceId, labelRef: input.labelRef, }); if (jsonRequested(opts)) return outJson(result); @@ -114,10 +116,10 @@ Examples: { key: "href", label: "Href" }, ]); } catch (e: unknown) { - if (e instanceof Error && (e.message === "Invalid space id" || e.message.startsWith("Invalid search type:"))) { + if (e instanceof Error && e.message.startsWith("Invalid search type:")) { return error(e.message); } - handleHttp(e); + failSpaceTarget(e); } }); } diff --git a/packages/cli/src/commands/spaces.ts b/packages/cli/src/commands/spaces.ts index d4a73c402..2651247ac 100644 --- a/packages/cli/src/commands/spaces.ts +++ b/packages/cli/src/commands/spaces.ts @@ -17,7 +17,7 @@ import { createClient, createRealtimeClient } from "../client.js"; import { collectOption, readPromptContent } from "../command-input.js"; import { table, json as outJson, jsonRequested, ok, error, handleHttp, formatEpochMs, truncateText } from "../output.js"; import { SESSION_INITIATOR_COLUMN, SESSION_STATUS_COLUMN, sessionArchiveFilter } from "../session-status.js"; -import { resolveSpace } from "../space.js"; +import { failSpaceTarget, resolveSpace, resolveSpaceRef } from "../space.js"; import { uploadLocalFiles, type LocalUploadEntry } from "../space-files/upload.js"; import { registerDecisionCommand } from "./decision.js"; import { registerSpaceCommerce } from "./space-commerce.js"; @@ -563,7 +563,7 @@ export function registerSpaceSetup(spacesCmd: Command, deps: { createClient?: ty .option("--json", "Output as JSON") .action(async (id: string | undefined, opts: { json?: boolean }) => { try { - const spaceId = id ?? await resolveSpace(spacesCmd); + const spaceId = id !== undefined ? await resolveSpaceRef(id) : await resolveSpace(spacesCmd); const { sandbox } = await (deps.createClient ?? createClient)().space(spaceId).sandbox.get(); const setup = sandbox?.meta?.setup ?? null; if (jsonRequested(opts)) return outJson({ provider: sandbox?.provider ?? null, setup }); @@ -580,7 +580,7 @@ export function registerSpaceSetup(spacesCmd: Command, deps: { createClient?: ty { key: "script", label: "Script" }, { key: "status", label: "Status" }, { key: "duration", label: "Duration" }, { key: "logs", label: "Logs" }, ]); - } catch (e: unknown) { handleHttp(e); } + } catch (e: unknown) { failSpaceTarget(e); } }); } @@ -638,13 +638,14 @@ export function registerSpaces(program: Command): void { .action(async (ids: string[], opts: { json?: boolean }) => { const client = createClient(); try { - const chunks = Array.from({ length: Math.ceil(ids.length / 200) }, (_, index) => ids.slice(index * 200, (index + 1) * 200)); + const resolvedIds = await Promise.all(ids.map((id) => resolveSpaceRef(id))); + const chunks = Array.from({ length: Math.ceil(resolvedIds.length / 200) }, (_, index) => resolvedIds.slice(index * 200, (index + 1) * 200)); for (const chunk of chunks) await client.user.labels.patchResources(chunk, archive ? { addLabelRefs: ["Archived"], removeLabelRefs: ["Pinned"] } : { removeLabelRefs: ["Archived"] }); - if (jsonRequested(opts)) return outJson({ ids, archived: archive }); - ok(`${archive ? "Archived" : "Unarchived"} ${ids.length} space(s)`); - } catch (e: unknown) { handleHttp(e); } + if (jsonRequested(opts)) return outJson({ ids: resolvedIds, archived: archive }); + ok(`${archive ? "Archived" : "Unarchived"} ${resolvedIds.length} space(s)`); + } catch (e: unknown) { failSpaceTarget(e); } }); } @@ -654,9 +655,9 @@ export function registerSpaces(program: Command): void { .description("Show space details") .option("--json", "Output as JSON") .action(async (id: string | undefined, opts: { json?: boolean }) => { - const spaceId = id?.trim() || await resolveSpace(spacesCmd); const client = createClient(); try { + const spaceId = id !== undefined ? await resolveSpaceRef(id) : await resolveSpace(spacesCmd); const [space, overview] = await Promise.all([ client.spaces.get(spaceId), client.space(spaceId).overview.get().catch(() => null), @@ -677,7 +678,7 @@ export function registerSpaces(program: Command): void { ]); if (overview) printSpaceOverview(overview); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -702,7 +703,8 @@ export function registerSpaces(program: Command): void { const client = createClient(); try { - const result = await client.space(id).update(input); + const spaceId = await resolveSpaceRef(id); + const result = await client.space(spaceId).update(input); if (jsonRequested(opts)) return outJson(result); ok("Space updated"); table([result.space], [ @@ -711,7 +713,7 @@ export function registerSpaces(program: Command): void { { key: "slug", label: "Slug" }, ]); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -722,10 +724,11 @@ export function registerSpaces(program: Command): void { .action(async (id: string, name: string) => { const client = createClient(); try { - await client.space(id).rename(name); + const spaceId = await resolveSpaceRef(id); + await client.space(spaceId).rename(name); ok(`Space renamed to "${name}"`); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -785,10 +788,11 @@ export function registerSpaces(program: Command): void { const autoDestroy = parseAutoDestroy(opts); const spec = opts.spec === "auto" ? null : parseSandboxSpec(opts.spec); const image = opts.image === "auto" ? null : opts.image ? parseChoice(opts.image, "sandbox image", ["default", "game"] as const) : undefined; - const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, id, opts.guestApp); + const spaceId = await resolveSpaceRef(id); + const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, spaceId, opts.guestApp); const sandboxChanged = Boolean(autoDestroy) || spec !== undefined || image !== undefined; if (sandboxChanged || guest !== undefined) { - const result = await client.space(id).updateConfig({ + const result = await client.space(spaceId).updateConfig({ ...(sandboxChanged ? { sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } } : {}), ...(guest !== undefined ? { guest } : {}), }); @@ -796,7 +800,7 @@ export function registerSpaces(program: Command): void { ok(`Space config updated${autoDestroy ? ` — sandbox auto destroy: ${formatAutoDestroy(autoDestroy)}` : ""}${spec ? ` — sandbox spec: ${spec}` : ""}${result.sandbox?.pendingRestart ? " — restart the sandbox to apply" : ""}`); return; } - const result = await client.space(id).getConfig(); + const result = await client.space(spaceId).getConfig(); if (jsonRequested(opts)) return outJson(result); table([ { key: "sandbox.autoDestroy", value: formatAutoDestroy(result.config.sandbox.autoDestroy) }, @@ -814,7 +818,7 @@ export function registerSpaces(program: Command): void { { key: "value", label: "Value" }, ]); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -898,10 +902,11 @@ export function registerSpaces(program: Command): void { .action(async (id: string) => { const client = createClient(); try { - await client.user.labels.patchResourceLabels("space", id.trim(), { addLabelRefs: ["Pinned"] }); + const spaceId = await resolveSpaceRef(id); + await client.user.labels.patchResourceLabels("space", spaceId, { addLabelRefs: ["Pinned"] }); ok("Space pinned"); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -911,10 +916,11 @@ export function registerSpaces(program: Command): void { .action(async (id: string) => { const client = createClient(); try { - await client.user.labels.patchResourceLabels("space", id.trim(), { removeLabelRefs: ["Pinned"] }); + const spaceId = await resolveSpaceRef(id); + await client.user.labels.patchResourceLabels("space", spaceId, { removeLabelRefs: ["Pinned"] }); ok("Space unpinned"); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -1511,6 +1517,72 @@ type SessionCreateOptions = { json?: boolean; }; +type TailSession = { + on(event: "turn.patch" | "turn.finalized" | "turn.error", handler: (event: { payload?: Record }) => void): unknown; +}; + +type TailClient = { + disconnect(): Promise; +}; + +export function attachSessionTail( + client: TailClient, + session: TailSession, + options: { + json: boolean; + stdout?: { write(chunk: string): unknown }; + stderr?: { write(chunk: string): unknown }; + exit?: (code: number) => void; + }, +): void { + const stdout = options.stdout ?? process.stdout; + const stderr = options.stderr ?? process.stderr; + const exit = options.exit ?? ((code: number) => process.exit(code)); + let exiting = false; + const finish = async (code: number) => { + if (exiting) return; + exiting = true; + await client.disconnect().catch(() => undefined); + exit(code); + }; + + if (!options.json) stdout.write(" Listening for events...\n\n"); + + let lastAppendPath: string | null = null; + session.on("turn.patch", (e: { payload?: Record }) => { + if (options.json) { + stdout.write(`${JSON.stringify(e)}\n`); + return; + } + const ops = e.payload?.ops as Array<{ o?: string; p?: string; v?: unknown }> | undefined; + for (const op of ops ?? []) { + if (op.o === "append" && typeof op.v === "string" && op.p?.endsWith("/text")) { + lastAppendPath = op.p; + stdout.write(op.v); + continue; + } + if (op.o === "append" && typeof op.p === "string") { + lastAppendPath = op.p; + continue; + } + if (!op.o && !op.p && typeof op.v === "string" && lastAppendPath?.endsWith("/text")) { + stdout.write(op.v); + } + } + }); + + session.on("turn.finalized", () => { + if (!options.json) stdout.write("\n\n ✓ Done\n"); + void finish(0); + }); + + session.on("turn.error", (e: unknown) => { + stderr.write("\n ✗ Error\n"); + if (options.json) stderr.write(`${JSON.stringify(e)}\n`); + void finish(1); + }); +} + function registerSessions(spacesCmd: Command): void { const sessionsCmd = spacesCmd .command("sessions") @@ -1710,42 +1782,8 @@ function registerSessions(spacesCmd: Command): void { const client = createRealtimeClient(); const session = client.space(spaceId).session(id); - process.stdout.write(" Listening for events...\n\n"); - process.once("SIGINT", () => void client.disconnect().finally(() => process.exit(130))); - - let lastAppendPath: string | null = null; - session.on("turn.patch", (e: { payload?: Record }) => { - if (jsonRequested(opts)) { - console.log(JSON.stringify(e)); - } else { - const ops = e.payload?.ops as Array<{ o?: string; p?: string; v?: unknown }> | undefined; - for (const op of ops ?? []) { - if (op.o === "append" && typeof op.v === "string" && op.p?.endsWith("/text")) { - lastAppendPath = op.p; - process.stdout.write(op.v); - continue; - } - if (op.o === "append" && typeof op.p === "string") { - lastAppendPath = op.p; - continue; - } - if (!op.o && !op.p && typeof op.v === "string" && lastAppendPath?.endsWith("/text")) { - process.stdout.write(op.v); - } - } - } - }); - - session.on("turn.finalized", () => { - process.stdout.write("\n\n ✓ Done\n"); - process.exit(0); - }); - - session.on("turn.error", (e: unknown) => { - process.stderr.write(`\n ✗ Error\n`); - if (jsonRequested(opts)) process.stderr.write(`${JSON.stringify(e)}\n`); - process.exit(1); - }); + process.once("SIGINT", () => void client.disconnect().catch(() => undefined).finally(() => process.exit(130))); + attachSessionTail(client, session, { json: jsonRequested(opts) }); }); // ── sessions turns ── diff --git a/packages/cli/src/help-path.ts b/packages/cli/src/help-path.ts index ef631cd98..2441407c6 100644 --- a/packages/cli/src/help-path.ts +++ b/packages/cli/src/help-path.ts @@ -83,11 +83,11 @@ function runRemainderRequestsHelp(argv: string[]): boolean { if (token === "--") return false; if (isHelpFlag(token)) return true; if (token === "--async" || token === "--json") continue; - if (token === "-c" || token === "--command" || token === "--base-url") { + if (token === "-c" || token === "--command" || token === "--base-url" || token === "-s" || token === "--space") { index += 1; continue; } - if (token.startsWith("--command=") || token.startsWith("--base-url=")) continue; + if (token.startsWith("--command=") || token.startsWith("--base-url=") || token.startsWith("--space=")) continue; return false; } return false; diff --git a/packages/cli/src/space.ts b/packages/cli/src/space.ts index e713302c4..1007c15b8 100644 --- a/packages/cli/src/space.ts +++ b/packages/cli/src/space.ts @@ -114,15 +114,20 @@ export function clearHomeSpaceCache(): void { } } -/** Explicit target from `-s/--space` (any ancestor) or `COHUB_SPACE_ID`, else null. */ -export function explicitSpace(program: Command): string | null { - let current: Command | null = program; +/** Explicit `-s/--space` flag from `command` or any ancestor, ignoring `COHUB_SPACE_ID`. */ +export function explicitSpaceFlag(command: Command): string | null { + let current: Command | null = command; while (current) { const opts = current.opts() as Record; if (typeof opts.space === "string" && opts.space.trim()) return opts.space.trim(); current = current.parent ?? null; } - return process.env.COHUB_SPACE_ID?.trim() || null; + return null; +} + +/** Explicit target from `-s/--space` (any ancestor) or `COHUB_SPACE_ID`, else null. */ +export function explicitSpace(program: Command): string | null { + return explicitSpaceFlag(program) ?? (process.env.COHUB_SPACE_ID?.trim() || null); } /** Cached per identity and memoized per process. */ diff --git a/packages/cli/tests/help-path.test.ts b/packages/cli/tests/help-path.test.ts index bdd182bd5..632e3f213 100644 --- a/packages/cli/tests/help-path.test.ts +++ b/packages/cli/tests/help-path.test.ts @@ -45,7 +45,10 @@ test("unknown prefixes error instead of dumping root help", () => { test("run help follows run's own parsing rules", () => { assert.equal(kind(["run", "--help"]), "run-help"); + assert.equal(kind(["run", "-s", "atou/project", "--help"]), "run-help"); + assert.equal(kind(["run", "--space=atou/project", "--help"]), "run-help"); assert.equal(kind(["run", "npm", "--help"]), "passthrough"); + assert.equal(kind(["run", "-s", "atou/project", "npm", "--help"]), "passthrough"); assert.equal(kind(["run", "--async", "npm", "--help"]), "passthrough"); assert.equal(kind(["run", "--command", "--help"]), "passthrough"); }); diff --git a/packages/cli/tests/run.test.ts b/packages/cli/tests/run.test.ts index 991addda2..6a313d17a 100644 --- a/packages/cli/tests/run.test.ts +++ b/packages/cli/tests/run.test.ts @@ -1,11 +1,17 @@ import assert from "node:assert/strict"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, test } from "node:test"; import { resolveCohubEnvironment } from "@neta-art/cohub"; import { parseRunCliOptions } from "../src/commands/run.js"; +const SPACE_A = "11111111-1111-4111-8111-111111111111"; +const SPACE_B = "22222222-2222-4222-8222-222222222222"; +const SPACE_PROJECT = "33333333-3333-4333-8333-333333333333"; + const roots: string[] = []; function jwt(payload: Record): string { @@ -17,7 +23,7 @@ afterEach(async () => { }); test("cohub run uses the current directory Runtime binding", async () => { - const root = await mkdtemp(join(tmpdir(), "cohub-run-binding-")); + const root = await realpath(await mkdtemp(join(tmpdir(), "cohub-run-binding-"))); roots.push(root); const path = join(root, "runtime-spaces.json"); const previousToken = process.env.COHUB_EXECUTION_TOKEN; @@ -39,3 +45,67 @@ test("cohub run uses the current directory Runtime binding", async () => { else process.env.COHUB_SPACE_ID = previousSpace; } }); + +test("cohub run accepts -s/--space/--space= both before and after run, without swallowing command flags", async () => { + const previousSpace = process.env.COHUB_SPACE_ID; + delete process.env.COHUB_SPACE_ID; + try { + assert.deepEqual( + await parseRunCliOptions(["-s", SPACE_A, "run", "--", "git", "status"]), + { spaceId: SPACE_A, json: false, async: false, command: "git status" }, + ); + assert.deepEqual( + await parseRunCliOptions(["run", "-s", SPACE_A, "--", "git", "status"]), + { spaceId: SPACE_A, json: false, async: false, command: "git status" }, + ); + assert.deepEqual( + await parseRunCliOptions(["run", "--space", SPACE_A, "--async", "--json", "--", "git", "status", "-s"]), + { spaceId: SPACE_A, json: true, async: true, command: "git status -s" }, + ); + assert.deepEqual( + await parseRunCliOptions(["run", `--space=${SPACE_A}`, "git", "status", "-s"]), + { spaceId: SPACE_A, json: false, async: false, command: "git status -s" }, + ); + assert.deepEqual( + await parseRunCliOptions(["-s", SPACE_A, "run", "-s", SPACE_B, "-c", "git status"]), + { spaceId: SPACE_B, json: false, async: false, command: "git status" }, + ); + } finally { + if (previousSpace === undefined) delete process.env.COHUB_SPACE_ID; + else process.env.COHUB_SPACE_ID = previousSpace; + } +}); + +test("cohub run resolves username/slug passed after run", async () => { + const server = createServer((req, res) => { + if (req.url === "/api/spaces/by-slug/atou/project") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: SPACE_PROJECT, slug: "project", name: "Project" })); + return; + } + res.writeHead(404); + res.end(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const { port } = server.address() as AddressInfo; + + const previousBaseUrl = process.env.COHUB_BASE_URL; + const previousToken = process.env.COHUB_EXECUTION_TOKEN; + const previousSpace = process.env.COHUB_SPACE_ID; + process.env.COHUB_BASE_URL = `http://127.0.0.1:${port}`; + process.env.COHUB_EXECUTION_TOKEN = "test-token"; + delete process.env.COHUB_SPACE_ID; + try { + const options = await parseRunCliOptions(["run", "-s", "atou/project", "--", "git", "status"]); + assert.equal(options.spaceId, SPACE_PROJECT); + assert.equal(options.command, "git status"); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + if (previousBaseUrl === undefined) delete process.env.COHUB_BASE_URL; + else process.env.COHUB_BASE_URL = previousBaseUrl; + if (previousToken === undefined) delete process.env.COHUB_EXECUTION_TOKEN; + else process.env.COHUB_EXECUTION_TOKEN = previousToken; + if (previousSpace === undefined) delete process.env.COHUB_SPACE_ID; + else process.env.COHUB_SPACE_ID = previousSpace; + } +}); diff --git a/packages/cli/tests/space-ref-cli.test.ts b/packages/cli/tests/space-ref-cli.test.ts new file mode 100644 index 000000000..6f54b414e --- /dev/null +++ b/packages/cli/tests/space-ref-cli.test.ts @@ -0,0 +1,323 @@ +import assert from "node:assert/strict"; +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; +import { test } from "node:test"; +import { Command } from "commander"; +import { registerSearch } from "../src/commands/search.js"; +import { attachSessionTail, registerSpaces } from "../src/commands/spaces.js"; + +const HOME_ID = "11111111-1111-4111-8111-111111111111"; +const OWNED_ID = "22222222-2222-4222-8222-222222222222"; +const OTHER_ID = "33333333-3333-4333-8333-333333333333"; + +type RecordedRequest = { + method: string; + path: string; + query: URLSearchParams; + body: unknown; +}; + +async function readJsonBody(req: IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk as Buffer); + const raw = Buffer.concat(chunks).toString("utf-8").trim(); + if (!raw) return undefined; + return JSON.parse(raw); +} + +async function withMockApi( + fn: (ctx: { requests: RecordedRequest[]; runCli: (argv: string[]) => Promise }) => Promise, +): Promise { + const requests: RecordedRequest[] = []; + const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { + const url = new URL(req.url ?? "/", "http://127.0.0.1"); + const body = await readJsonBody(req); + requests.push({ method: req.method ?? "GET", path: url.pathname, query: url.searchParams, body }); + + const json = (status: number, payload: unknown) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(payload)); + }; + + if (req.method === "POST" && url.pathname === "/api/me/spaces/home") { + return json(200, { id: HOME_ID, name: "Home", slug: "home" }); + } + if (req.method === "GET" && url.pathname === "/api/me/spaces/by-slug/notes") { + return json(200, { id: OWNED_ID, name: "Notes", slug: "notes" }); + } + if (req.method === "GET" && url.pathname === "/api/spaces/by-slug/atou/project") { + return json(200, { id: OTHER_ID, name: "Project", slug: "project" }); + } + if (req.method === "GET" && url.pathname === "/api/search") { + return json(200, { items: [], degraded: false }); + } + if (req.method === "GET" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { + const id = url.pathname.split("/").at(-1); + return json(200, { id, name: "Space", slug: "space", status: "active", createdAt: "2026-01-01T00:00:00.000Z" }); + } + if (req.method === "GET" && /^\/api\/spaces\/[^/]+\/overview$/.test(url.pathname)) { + return json(200, { days: 30, apps: { count: 0, views: 0, likes: 0 } }); + } + if (req.method === "GET" && /^\/api\/spaces\/[^/]+\/sandbox$/.test(url.pathname)) { + return json(200, { sandbox: { provider: "cloud", meta: { setup: null } } }); + } + if (req.method === "PATCH" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { + const id = url.pathname.split("/").at(-1); + return json(200, { space: { id, name: "Updated", slug: "updated" } }); + } + if (req.method === "GET" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { + return json(200, { config: { sandbox: { spec: "standard", allowedSpec: "standard" }, guest: null } }); + } + if (req.method === "PATCH" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { + return json(200, { config: { sandbox: { spec: "boost" }, guest: null }, sandbox: { pendingRestart: false } }); + } + if (req.method === "GET" && /^\/api\/apps\/space\/[^/]+$/.test(url.pathname)) { + return json(200, { apps: [{ id: "app-1", slug: "welcome" }] }); + } + if (req.method === "PATCH" && url.pathname === "/api/me/resources/space/labels") { + return json(200, { assignments: [] }); + } + if (req.method === "PATCH" && url.pathname === "/api/me/resources/space/labels/batch") { + return json(200, { resourceRefs: [], affectedLabelIds: [] }); + } + return json(404, { message: `Unhandled ${req.method} ${url.pathname}` }); + }); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const { port } = server.address() as AddressInfo; + + const previousBaseUrl = process.env.COHUB_BASE_URL; + const previousToken = process.env.COHUB_EXECUTION_TOKEN; + const previousSpace = process.env.COHUB_SPACE_ID; + process.env.COHUB_BASE_URL = `http://127.0.0.1:${port}`; + process.env.COHUB_EXECUTION_TOKEN = "test-token"; + + const runCli = async (argv: string[]): Promise => { + const program = new Command("cohub") + .option("-s, --space ", "Target Space"); + registerSearch(program); + registerSpaces(program); + + const logs: string[] = []; + const originalLog = console.log; + console.log = (...values: unknown[]) => { + logs.push(values.join(" ")); + }; + try { + await program.parseAsync(["node", "cohub", ...argv]); + } finally { + console.log = originalLog; + } + return logs.join("\n"); + }; + + try { + await fn({ requests, runCli }); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + if (previousBaseUrl === undefined) delete process.env.COHUB_BASE_URL; + else process.env.COHUB_BASE_URL = previousBaseUrl; + if (previousToken === undefined) delete process.env.COHUB_EXECUTION_TOKEN; + else process.env.COHUB_EXECUTION_TOKEN = previousToken; + if (previousSpace === undefined) delete process.env.COHUB_SPACE_ID; + else process.env.COHUB_SPACE_ID = previousSpace; + } +} + +test("cohub search ignores COHUB_SPACE_ID, honors -s/--space, and resolves --space-id refs with priority", async () => { + await withMockApi(async ({ requests, runCli }) => { + process.env.COHUB_SPACE_ID = HOME_ID; + + await runCli(["search", "release", "--json"]); + const globalSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(globalSearch?.query.get("q"), "release"); + assert.equal(globalSearch?.query.get("spaceId"), null); + + await runCli(["-s", "atou/project", "search", "bug", "--json"]); + const flagSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(flagSearch?.query.get("spaceId"), OTHER_ID); + + await runCli(["search", "notes", "--space-id", "home", "--json"]); + const spaceIdSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(spaceIdSearch?.query.get("spaceId"), HOME_ID); + + await runCli(["-s", "home", "search", "priority", "--space-id", "notes", "--json"]); + const overrideSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(overrideSearch?.query.get("spaceId"), OWNED_ID); + }); +}); + +test("spaces positional Space-ref commands resolve UUID, home, own slug, and username/slug", async () => { + await withMockApi(async ({ requests, runCli }) => { + delete process.env.COHUB_SPACE_ID; + + await runCli(["spaces", "setup", "atou/project", "--json"]); + assert.equal(requests.at(-1)?.path, `/api/spaces/${OTHER_ID}/sandbox`); + + await runCli(["spaces", "get", "home", "--json"]); + assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/spaces/${HOME_ID}`)); + + await runCli(["-s", "notes", "spaces", "get", "--json"]); + assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/spaces/${OWNED_ID}`)); + + await runCli(["spaces", "update", "atou/project", "--name", "Renamed", "--json"]); + const updateReq = requests.findLast((r) => r.method === "PATCH" && r.path === `/api/spaces/${OTHER_ID}`); + assert.deepEqual(updateReq?.body, { name: "Renamed" }); + + await runCli(["spaces", "rename", "notes", "New Notes"]); + const renameReq = requests.findLast((r) => r.method === "PATCH" && r.path === `/api/spaces/${OWNED_ID}`); + assert.deepEqual(renameReq?.body, { name: "New Notes" }); + + await runCli(["spaces", "config", "atou/project", "--json"]); + assert.equal(requests.at(-1)?.path, `/api/spaces/${OTHER_ID}/config`); + + await runCli(["spaces", "config", "atou/project", "--guest-app", "welcome", "--json"]); + assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/apps/space/${OTHER_ID}`)); + const configPatch = requests.findLast((r) => r.method === "PATCH" && r.path === `/api/spaces/${OTHER_ID}/config`); + assert.deepEqual(configPatch?.body, { guest: { appId: "app-1" } }); + + await runCli(["spaces", "pin", "atou/project"]); + const pinReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels"); + assert.equal(pinReq?.query.get("resourceRef"), OTHER_ID); + assert.deepEqual(pinReq?.body, { addLabelRefs: ["Pinned"] }); + + await runCli(["spaces", "unpin", "notes"]); + const unpinReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels"); + assert.equal(unpinReq?.query.get("resourceRef"), OWNED_ID); + assert.deepEqual(unpinReq?.body, { removeLabelRefs: ["Pinned"] }); + + const archiveOut = await runCli(["spaces", "archive", "home", "atou/project", "--json"]); + const archiveReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels/batch"); + assert.deepEqual(archiveReq?.body, { + resourceRefs: [HOME_ID, OTHER_ID], + addLabelRefs: ["Archived"], + removeLabelRefs: ["Pinned"], + }); + assert.deepEqual(JSON.parse(archiveOut), { ids: [HOME_ID, OTHER_ID], archived: true }); + + const unarchiveOut = await runCli(["spaces", "unarchive", "notes", "--json"]); + const unarchiveReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels/batch"); + assert.deepEqual(unarchiveReq?.body, { + resourceRefs: [OWNED_ID], + removeLabelRefs: ["Archived"], + }); + assert.deepEqual(JSON.parse(unarchiveOut), { ids: [OWNED_ID], archived: false }); + }); +}); + +test("attachSessionTail keeps stdout pure JSONL in --json mode and disconnects before exiting", async () => { + const handlers = new Map }) => void>(); + const events: string[] = []; + let stdout = ""; + let stderr = ""; + let exitCode: number | null = null; + let resolveExit!: () => void; + const exited = new Promise((resolve) => { + resolveExit = resolve; + }); + + attachSessionTail( + { + disconnect: async () => { + events.push("disconnect"); + throw new Error("socket already closed"); + }, + }, + { + on: (event, handler) => { + handlers.set(event, handler); + }, + }, + { + json: true, + stdout: { write: (chunk) => { stdout += chunk; } }, + stderr: { write: (chunk) => { stderr += chunk; } }, + exit: (code) => { + events.push(`exit:${code}`); + exitCode = code; + resolveExit(); + }, + }, + ); + + assert.equal(stdout, ""); + handlers.get("turn.patch")?.({ payload: { ops: [{ o: "append", p: "/text", v: "hello" }] } }); + handlers.get("turn.patch")?.({ payload: { ops: [{ o: "append", p: "/text", v: " world" }] } }); + handlers.get("turn.finalized")?.({}); + await exited; + + assert.equal(stderr, ""); + assert.equal(exitCode, 0); + assert.deepEqual(events, ["disconnect", "exit:0"]); + const lines = stdout.trim().split("\n"); + assert.equal(lines.length, 2); + assert.deepEqual(lines.map((line) => JSON.parse(line)), [ + { payload: { ops: [{ o: "append", p: "/text", v: "hello" }] } }, + { payload: { ops: [{ o: "append", p: "/text", v: " world" }] } }, + ]); +}); + +test("attachSessionTail disconnects cleanly before exiting on turn.error and preserves human output", async () => { + const errorHandlers = new Map }) => void>(); + const errorEvents: string[] = []; + let jsonStdout = ""; + let jsonStderr = ""; + let resolveErrExit!: () => void; + const errExited = new Promise((resolve) => { + resolveErrExit = resolve; + }); + + attachSessionTail( + { + disconnect: async () => { + errorEvents.push("disconnect"); + }, + }, + { + on: (event, handler) => { + errorHandlers.set(event, handler); + }, + }, + { + json: true, + stdout: { write: (chunk) => { jsonStdout += chunk; } }, + stderr: { write: (chunk) => { jsonStderr += chunk; } }, + exit: (code) => { + errorEvents.push(`exit:${code}`); + resolveErrExit(); + }, + }, + ); + + errorHandlers.get("turn.error")?.({ payload: { message: "boom" } }); + await errExited; + + assert.equal(jsonStdout, ""); + assert.match(jsonStderr, /✗ Error/); + assert.match(jsonStderr, /"message":"boom"/); + assert.deepEqual(errorEvents, ["disconnect", "exit:1"]); + + const humanHandlers = new Map }) => void>(); + let humanStdout = ""; + let resolveHumanExit!: () => void; + const humanExited = new Promise((resolve) => { + resolveHumanExit = resolve; + }); + + attachSessionTail( + { disconnect: async () => {} }, + { on: (event, handler) => { humanHandlers.set(event, handler); } }, + { + json: false, + stdout: { write: (chunk) => { humanStdout += chunk; } }, + stderr: { write: () => {} }, + exit: () => resolveHumanExit(), + }, + ); + + humanHandlers.get("turn.patch")?.({ payload: { ops: [{ o: "append", p: "/text", v: "hi" }] } }); + humanHandlers.get("turn.finalized")?.({}); + await humanExited; + + assert.equal(humanStdout, " Listening for events...\n\nhi\n\n ✓ Done\n"); +}); diff --git a/packages/cli/tests/space.test.ts b/packages/cli/tests/space.test.ts index 095ea9357..2f9258d5f 100644 --- a/packages/cli/tests/space.test.ts +++ b/packages/cli/tests/space.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, test } from "node:test"; import { Command } from "commander"; -import { explicitSpace, identityKeyFrom, readHomeSpaceCache } from "../src/space.js"; +import { explicitSpace, explicitSpaceFlag, identityKeyFrom, readHomeSpaceCache } from "../src/space.js"; const DAY_MS = 86_400_000; const tempDirs: string[] = []; @@ -39,6 +39,8 @@ test("explicit space prefers -s over COHUB_SPACE_ID", () => { try { assert.equal(explicitSpace(programWithSpace("from-flag")), "from-flag"); assert.equal(explicitSpace(programWithSpace()), "from-env"); + assert.equal(explicitSpaceFlag(programWithSpace("from-flag")), "from-flag"); + assert.equal(explicitSpaceFlag(programWithSpace()), null); } finally { if (previous === undefined) delete process.env.COHUB_SPACE_ID; else process.env.COHUB_SPACE_ID = previous; From 1e6ec6a23289e4b4ac5f1a29d3f96d01b52628e9 Mon Sep 17 00:00:00 2001 From: ATou <11880502+atou42@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:43:04 +0800 Subject: [PATCH 2/4] test(cli): use in-memory fetch fakes in run and space-ref tests for no-network CI --- packages/cli/tests/run.test.ts | 32 +++++----- packages/cli/tests/space-ref-cli.test.ts | 79 ++++++++++++------------ 2 files changed, 54 insertions(+), 57 deletions(-) diff --git a/packages/cli/tests/run.test.ts b/packages/cli/tests/run.test.ts index 6a313d17a..05d6800c6 100644 --- a/packages/cli/tests/run.test.ts +++ b/packages/cli/tests/run.test.ts @@ -1,6 +1,4 @@ import assert from "node:assert/strict"; -import { createServer } from "node:http"; -import type { AddressInfo } from "node:net"; import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -77,30 +75,32 @@ test("cohub run accepts -s/--space/--space= both before and after run, without s }); test("cohub run resolves username/slug passed after run", async () => { - const server = createServer((req, res) => { - if (req.url === "/api/spaces/by-slug/atou/project") { - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ id: SPACE_PROJECT, slug: "project", name: "Project" })); - return; - } - res.writeHead(404); - res.end(); - }); - await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); - const { port } = server.address() as AddressInfo; - + const previousFetch = globalThis.fetch; const previousBaseUrl = process.env.COHUB_BASE_URL; const previousToken = process.env.COHUB_EXECUTION_TOKEN; const previousSpace = process.env.COHUB_SPACE_ID; - process.env.COHUB_BASE_URL = `http://127.0.0.1:${port}`; + process.env.COHUB_BASE_URL = "https://cohub-run-test.invalid"; process.env.COHUB_EXECUTION_TOKEN = "test-token"; delete process.env.COHUB_SPACE_ID; + globalThis.fetch = async (input) => { + const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url); + if (url.pathname === "/api/spaces/by-slug/atou/project") { + return new Response(JSON.stringify({ id: SPACE_PROJECT, slug: "project", name: "Project" }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + } + return new Response(JSON.stringify({ message: `Unhandled ${url.pathname}` }), { + status: 404, + headers: { "content-type": "application/json" }, + }); + }; try { const options = await parseRunCliOptions(["run", "-s", "atou/project", "--", "git", "status"]); assert.equal(options.spaceId, SPACE_PROJECT); assert.equal(options.command, "git status"); } finally { - await new Promise((resolve) => server.close(() => resolve())); + globalThis.fetch = previousFetch; if (previousBaseUrl === undefined) delete process.env.COHUB_BASE_URL; else process.env.COHUB_BASE_URL = previousBaseUrl; if (previousToken === undefined) delete process.env.COHUB_EXECUTION_TOKEN; diff --git a/packages/cli/tests/space-ref-cli.test.ts b/packages/cli/tests/space-ref-cli.test.ts index 6f54b414e..cf08b4e2b 100644 --- a/packages/cli/tests/space-ref-cli.test.ts +++ b/packages/cli/tests/space-ref-cli.test.ts @@ -1,6 +1,4 @@ import assert from "node:assert/strict"; -import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; -import type { AddressInfo } from "node:net"; import { test } from "node:test"; import { Command } from "commander"; import { registerSearch } from "../src/commands/search.js"; @@ -10,6 +8,8 @@ const HOME_ID = "11111111-1111-4111-8111-111111111111"; const OWNED_ID = "22222222-2222-4222-8222-222222222222"; const OTHER_ID = "33333333-3333-4333-8333-333333333333"; +let mockApiSeq = 0; + type RecordedRequest = { method: string; path: string; @@ -17,11 +17,8 @@ type RecordedRequest = { body: unknown; }; -async function readJsonBody(req: IncomingMessage): Promise { - const chunks: Buffer[] = []; - for await (const chunk of req) chunks.push(chunk as Buffer); - const raw = Buffer.concat(chunks).toString("utf-8").trim(); - if (!raw) return undefined; +function parseRequestBody(raw: BodyInit | null | undefined): unknown { + if (typeof raw !== "string" || !raw.trim()) return undefined; return JSON.parse(raw); } @@ -29,68 +26,68 @@ async function withMockApi( fn: (ctx: { requests: RecordedRequest[]; runCli: (argv: string[]) => Promise }) => Promise, ): Promise { const requests: RecordedRequest[] = []; - const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { - const url = new URL(req.url ?? "/", "http://127.0.0.1"); - const body = await readJsonBody(req); - requests.push({ method: req.method ?? "GET", path: url.pathname, query: url.searchParams, body }); - - const json = (status: number, payload: unknown) => { - res.writeHead(status, { "content-type": "application/json" }); - res.end(JSON.stringify(payload)); - }; + const previousFetch = globalThis.fetch; + const previousBaseUrl = process.env.COHUB_BASE_URL; + const previousToken = process.env.COHUB_EXECUTION_TOKEN; + const previousSpace = process.env.COHUB_SPACE_ID; + process.env.COHUB_BASE_URL = `https://cohub-space-ref-test-${++mockApiSeq}.invalid`; + process.env.COHUB_EXECUTION_TOKEN = "test-token"; + + globalThis.fetch = async (input, init) => { + const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url); + const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase(); + const body = parseRequestBody(init?.body); + requests.push({ method, path: url.pathname, query: url.searchParams, body }); + + const json = (status: number, payload: unknown) => + new Response(JSON.stringify(payload), { + status, + headers: { "content-type": "application/json" }, + }); - if (req.method === "POST" && url.pathname === "/api/me/spaces/home") { + if (method === "POST" && url.pathname === "/api/me/spaces/home") { return json(200, { id: HOME_ID, name: "Home", slug: "home" }); } - if (req.method === "GET" && url.pathname === "/api/me/spaces/by-slug/notes") { + if (method === "GET" && url.pathname === "/api/me/spaces/by-slug/notes") { return json(200, { id: OWNED_ID, name: "Notes", slug: "notes" }); } - if (req.method === "GET" && url.pathname === "/api/spaces/by-slug/atou/project") { + if (method === "GET" && url.pathname === "/api/spaces/by-slug/atou/project") { return json(200, { id: OTHER_ID, name: "Project", slug: "project" }); } - if (req.method === "GET" && url.pathname === "/api/search") { + if (method === "GET" && url.pathname === "/api/search") { return json(200, { items: [], degraded: false }); } - if (req.method === "GET" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { + if (method === "GET" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { const id = url.pathname.split("/").at(-1); return json(200, { id, name: "Space", slug: "space", status: "active", createdAt: "2026-01-01T00:00:00.000Z" }); } - if (req.method === "GET" && /^\/api\/spaces\/[^/]+\/overview$/.test(url.pathname)) { + if (method === "GET" && /^\/api\/spaces\/[^/]+\/overview$/.test(url.pathname)) { return json(200, { days: 30, apps: { count: 0, views: 0, likes: 0 } }); } - if (req.method === "GET" && /^\/api\/spaces\/[^/]+\/sandbox$/.test(url.pathname)) { + if (method === "GET" && /^\/api\/spaces\/[^/]+\/sandbox$/.test(url.pathname)) { return json(200, { sandbox: { provider: "cloud", meta: { setup: null } } }); } - if (req.method === "PATCH" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { + if (method === "PATCH" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { const id = url.pathname.split("/").at(-1); return json(200, { space: { id, name: "Updated", slug: "updated" } }); } - if (req.method === "GET" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { + if (method === "GET" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { return json(200, { config: { sandbox: { spec: "standard", allowedSpec: "standard" }, guest: null } }); } - if (req.method === "PATCH" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { + if (method === "PATCH" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { return json(200, { config: { sandbox: { spec: "boost" }, guest: null }, sandbox: { pendingRestart: false } }); } - if (req.method === "GET" && /^\/api\/apps\/space\/[^/]+$/.test(url.pathname)) { + if (method === "GET" && /^\/api\/apps\/space\/[^/]+$/.test(url.pathname)) { return json(200, { apps: [{ id: "app-1", slug: "welcome" }] }); } - if (req.method === "PATCH" && url.pathname === "/api/me/resources/space/labels") { + if (method === "PATCH" && url.pathname === "/api/me/resources/space/labels") { return json(200, { assignments: [] }); } - if (req.method === "PATCH" && url.pathname === "/api/me/resources/space/labels/batch") { + if (method === "PATCH" && url.pathname === "/api/me/resources/space/labels/batch") { return json(200, { resourceRefs: [], affectedLabelIds: [] }); } - return json(404, { message: `Unhandled ${req.method} ${url.pathname}` }); - }); - - await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); - const { port } = server.address() as AddressInfo; - - const previousBaseUrl = process.env.COHUB_BASE_URL; - const previousToken = process.env.COHUB_EXECUTION_TOKEN; - const previousSpace = process.env.COHUB_SPACE_ID; - process.env.COHUB_BASE_URL = `http://127.0.0.1:${port}`; - process.env.COHUB_EXECUTION_TOKEN = "test-token"; + return json(404, { message: `Unhandled ${method} ${url.pathname}` }); + }; const runCli = async (argv: string[]): Promise => { const program = new Command("cohub") @@ -114,7 +111,7 @@ async function withMockApi( try { await fn({ requests, runCli }); } finally { - await new Promise((resolve) => server.close(() => resolve())); + globalThis.fetch = previousFetch; if (previousBaseUrl === undefined) delete process.env.COHUB_BASE_URL; else process.env.COHUB_BASE_URL = previousBaseUrl; if (previousToken === undefined) delete process.env.COHUB_EXECUTION_TOKEN; From f718424e3a3749286d39329f58c627de5a618f00 Mon Sep 17 00:00:00 2001 From: markbang Date: Mon, 23 Nov 2026 07:31:29 +0000 Subject: [PATCH 3/4] fix(cli): resolve Space refs in apps and references, flush tail output - apps authorize --space reads the flag the root -s/--space option claims, so the grant targets the requested Space - references aggregate accepts Space refs after validating options - spaces tail --json waits for stdout to drain before exiting - empty --space-id / positional Space falls back like an omitted one - archive resolves refs sequentially; help shows placeholders - add changeset Cohub Session: https://cohub.live/spaces/5089f055-9dbb-4fcd-b98c-fb232353281a/sessions/b03e6e71-e62e-4589-8f98-bffbf7825137 --- .changeset/cli-space-refs.md | 5 ++++ packages/cli/src/commands/apps.ts | 13 +++++---- packages/cli/src/commands/models.ts | 2 +- packages/cli/src/commands/references.ts | 28 +++++++++--------- packages/cli/src/commands/run.ts | 1 - packages/cli/src/commands/search.ts | 18 +++++------- packages/cli/src/commands/spaces.ts | 28 +++++++++--------- packages/cli/tests/run.test.ts | 37 ------------------------ packages/cli/tests/space-ref-cli.test.ts | 22 ++++++++++++++ 9 files changed, 72 insertions(+), 82 deletions(-) create mode 100644 .changeset/cli-space-refs.md diff --git a/.changeset/cli-space-refs.md b/.changeset/cli-space-refs.md new file mode 100644 index 000000000..2461c8d35 --- /dev/null +++ b/.changeset/cli-space-refs.md @@ -0,0 +1,5 @@ +--- +"@neta-art/cohub-cli": patch +--- + +Space arguments on `spaces get/setup/update/rename/config/pin/unpin/archive/unarchive`, `search --space-id`, `references aggregate`, `apps authorize --space`, and `run -s` (before or after `run`) accept an ID, `home`, your own slug, or `username/slug`. `cohub -s search` scopes the search. `spaces sessions tail --json` now writes only JSONL to stdout. diff --git a/packages/cli/src/commands/apps.ts b/packages/cli/src/commands/apps.ts index 95a587596..f6c0e3f1e 100644 --- a/packages/cli/src/commands/apps.ts +++ b/packages/cli/src/commands/apps.ts @@ -4,7 +4,7 @@ import { getCohubContext, HttpError, isUserAppFilter, type CohubHttpClient, type import type { Command } from "commander"; import { createClient, createClientWithAccessToken } from "../client.js"; import { error, handleHttp, json as outJson, jsonRequested, ok, table } from "../output.js"; -import { resolveSpace } from "../space.js"; +import { explicitSpaceFlag, failSpaceTarget, resolveSpace, resolveSpaceRef } from "../space.js"; import { downloadApp } from "../app-download.js"; import { getAppByRef, parseAppRef } from "../app-ref.js"; import { checkAppTarget } from "../app-target.js"; @@ -799,22 +799,25 @@ export function registerApps(program: Command): void { .command("authorize ") .description("Grant an app scopes as the current user") .requiredOption("--scope ", "Scope to grant (repeatable)", collectOption, []) - .option("--space ", "Target space; defaults to the app's own space") + .option("--space ", "Target space (ID, home, slug, or username/slug); defaults to the app's own space") .option("--extend", "Add scopes without replacing active grants") .option("--json", "Output as JSON") - .action(async (appRef: string, opts: { scope: string[]; space?: string; extend?: boolean; json?: boolean }) => { + .action(async (appRef: string, opts: { scope: string[]; space?: string; extend?: boolean; json?: boolean }, command: Command) => { const client = createClient(); try { + // The root `-s, --space` option claims `--space` after the subcommand too; COHUB_SPACE_ID must not apply here. + const spaceRef = explicitSpaceFlag(command); + const spaceId = spaceRef ? await resolveSpaceRef(spaceRef) : undefined; const detail = await getAppByRef(client, appRef); const result = await client.apps.authorize(detail.app.id, { scopes: opts.scope as Permission[], - ...(opts.space ? { spaceId: opts.space } : {}), + ...(spaceId ? { spaceId } : {}), ...(opts.extend ? { scopeMode: "extend" as const } : {}), }); if (jsonRequested(opts)) return outJson(result); ok(`Granted ${result.grant.scopes.join(", ")} on space ${result.grant.spaceId}`); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); diff --git a/packages/cli/src/commands/models.ts b/packages/cli/src/commands/models.ts index f9a7393fc..f4d9a4908 100644 --- a/packages/cli/src/commands/models.ts +++ b/packages/cli/src/commands/models.ts @@ -199,7 +199,7 @@ export function registerModels(program: Command): void { Examples: cohub models ls - cohub models ls --space + cohub models ls --space cohub models ls --model-type multimodal cohub models ls --model-type multimodal --category video cohub models ls --model-type multimodal --json diff --git a/packages/cli/src/commands/references.ts b/packages/cli/src/commands/references.ts index 01f8def2d..bdce80219 100644 --- a/packages/cli/src/commands/references.ts +++ b/packages/cli/src/commands/references.ts @@ -1,13 +1,13 @@ -import { - isUuid, - type ReferenceAggregateGroupBy, - type ReferenceDirection, - type ReferenceKind, - type ReferenceQueryableType, +import type { + ReferenceAggregateGroupBy, + ReferenceDirection, + ReferenceKind, + ReferenceQueryableType, } from "@neta-art/cohub"; import type { Command } from "commander"; import { createClient } from "../client.js"; import { formatLocalDateTime, table, json as outJson, jsonRequested, error, handleHttp, type Row } from "../output.js"; +import { failSpaceTarget, resolveSpaceRef } from "../space.js"; const RESOURCE_TYPES = new Set([ "turn", @@ -152,7 +152,7 @@ Examples: references .command("aggregate") .description("Grouped reference counts for a space") - .argument("", "Space id") + .argument("", "Space: ID, home, slug, or username/slug") .option("--group-by ", "kind | targetType | target | sourceType | day", "kind") .option("--kinds ", "Comma-separated kinds (see list below)") .option("--days ", "Only references seen within the last N days") @@ -166,21 +166,21 @@ Notes: --group-by target: file targets look like {spaceId}:{path} Examples: - cohub references aggregate --json - cohub references aggregate --group-by targetType - cohub references aggregate --group-by target --kinds agent_tool_file_read --limit 20 - cohub references aggregate --group-by day --days 30 + cohub references aggregate --json + cohub references aggregate --group-by targetType + cohub references aggregate --group-by target --kinds agent_tool_file_read --limit 20 + cohub references aggregate --group-by day --days 30 `) - .action(async (spaceId: string, opts: AggregateOpts) => { + .action(async (space: string, opts: AggregateOpts) => { const client = createClient(); try { - if (!isUuid(spaceId.trim())) return error("Invalid space id"); const groupBy = (opts.groupBy ?? "kind") as ReferenceAggregateGroupBy; if (!GROUP_BYS.has(groupBy)) return error(`Invalid group-by: ${opts.groupBy}`); const kinds = parseKinds(opts.kinds); const days = opts.days ? clampNumber(opts.days, 30, 1, 365) : undefined; const limit = clampNumber(opts.limit, 200, 1, 500); - const result = await client.references.aggregate({ spaceId: spaceId.trim(), groupBy, kinds, days, limit }); + const spaceId = await resolveSpaceRef(space).catch(failSpaceTarget); + const result = await client.references.aggregate({ spaceId, groupBy, kinds, days, limit }); if (jsonRequested(opts)) return outJson(result); const rows: Row[] = result.groups.map((g) => ({ group: g.group, diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts index 55be082bf..dd6470f5c 100644 --- a/packages/cli/src/commands/run.ts +++ b/packages/cli/src/commands/run.ts @@ -189,7 +189,6 @@ Options: Examples: cohub -s run --command "git status" - cohub run -s -- git status -sb cohub -s run --async --command "pnpm test" cohub -s run -- git status -sb diff --git a/packages/cli/src/commands/search.ts b/packages/cli/src/commands/search.ts index 9da4500ce..1f15d4a09 100644 --- a/packages/cli/src/commands/search.ts +++ b/packages/cli/src/commands/search.ts @@ -49,11 +49,6 @@ function parseTypes(value: string | undefined): GlobalSearchType[] | undefined { return [...new Set(types)] as GlobalSearchType[]; } -function parseSearchInput(opts: SearchCliOptions) { - const types = parseTypes(opts.types); - return { types, labelRef: opts.labelRef?.trim() || undefined }; -} - function rowsFor(items: GlobalSearchResult[]): Row[] { return items.map((item) => ({ type: item.type, @@ -89,17 +84,18 @@ Examples: .action(async (query: string | undefined, opts: SearchCliOptions, command: Command) => { const client = createClient(); try { - const input = parseSearchInput(opts); + const types = parseTypes(opts.types); + const labelRef = opts.labelRef?.trim() || undefined; const q = query ?? ""; - if (!q.trim() && !input.labelRef) return error("Search query is required unless --label-ref is provided."); - const spaceRef = opts.spaceId !== undefined ? opts.spaceId.trim() : explicitSpaceFlag(command); - const spaceId = spaceRef !== null ? await resolveSpaceRef(spaceRef) : undefined; + if (!q.trim() && !labelRef) return error("Search query is required unless --label-ref is provided."); + const spaceRef = opts.spaceId?.trim() || explicitSpaceFlag(command); + const spaceId = spaceRef ? await resolveSpaceRef(spaceRef) : undefined; const result = await client.search.query({ q, limit: clampLimit(opts.limit), - types: input.types, + types, spaceId, - labelRef: input.labelRef, + labelRef, }); if (jsonRequested(opts)) return outJson(result); diff --git a/packages/cli/src/commands/spaces.ts b/packages/cli/src/commands/spaces.ts index 2651247ac..433f4d35b 100644 --- a/packages/cli/src/commands/spaces.ts +++ b/packages/cli/src/commands/spaces.ts @@ -17,7 +17,7 @@ import { createClient, createRealtimeClient } from "../client.js"; import { collectOption, readPromptContent } from "../command-input.js"; import { table, json as outJson, jsonRequested, ok, error, handleHttp, formatEpochMs, truncateText } from "../output.js"; import { SESSION_INITIATOR_COLUMN, SESSION_STATUS_COLUMN, sessionArchiveFilter } from "../session-status.js"; -import { failSpaceTarget, resolveSpace, resolveSpaceRef } from "../space.js"; +import { explicitSpace, failSpaceTarget, resolveSpace, resolveSpaceRef, resolveSpaceTarget } from "../space.js"; import { uploadLocalFiles, type LocalUploadEntry } from "../space-files/upload.js"; import { registerDecisionCommand } from "./decision.js"; import { registerSpaceCommerce } from "./space-commerce.js"; @@ -558,12 +558,12 @@ function registerUserLabels(program: Command) { export function registerSpaceSetup(spacesCmd: Command, deps: { createClient?: typeof createClient } = {}): void { spacesCmd - .command("setup [id]") + .command("setup [space]") .description("Show cloud sandbox startup scripts, results, and log paths") .option("--json", "Output as JSON") .action(async (id: string | undefined, opts: { json?: boolean }) => { try { - const spaceId = id !== undefined ? await resolveSpaceRef(id) : await resolveSpace(spacesCmd); + const spaceId = await resolveSpaceTarget(id?.trim() || explicitSpace(spacesCmd)); const { sandbox } = await (deps.createClient ?? createClient)().space(spaceId).sandbox.get(); const setup = sandbox?.meta?.setup ?? null; if (jsonRequested(opts)) return outJson({ provider: sandbox?.provider ?? null, setup }); @@ -632,13 +632,14 @@ export function registerSpaces(program: Command): void { for (const archive of [true, false]) { spacesCmd - .command(archive ? "archive " : "unarchive ") + .command(archive ? "archive " : "unarchive ") .description(archive ? "Archive spaces in your personal view" : "Restore archived spaces") .option("--json", "Output as JSON") .action(async (ids: string[], opts: { json?: boolean }) => { const client = createClient(); try { - const resolvedIds = await Promise.all(ids.map((id) => resolveSpaceRef(id))); + const resolvedIds: string[] = []; + for (const id of ids) resolvedIds.push(await resolveSpaceRef(id)); const chunks = Array.from({ length: Math.ceil(resolvedIds.length / 200) }, (_, index) => resolvedIds.slice(index * 200, (index + 1) * 200)); for (const chunk of chunks) await client.user.labels.patchResources(chunk, archive ? { addLabelRefs: ["Archived"], removeLabelRefs: ["Pinned"] } @@ -651,13 +652,13 @@ export function registerSpaces(program: Command): void { // ── spaces get ── spacesCmd - .command("get [id]") + .command("get [space]") .description("Show space details") .option("--json", "Output as JSON") .action(async (id: string | undefined, opts: { json?: boolean }) => { const client = createClient(); try { - const spaceId = id !== undefined ? await resolveSpaceRef(id) : await resolveSpace(spacesCmd); + const spaceId = await resolveSpaceTarget(id?.trim() || explicitSpace(spacesCmd)); const [space, overview] = await Promise.all([ client.spaces.get(spaceId), client.space(spaceId).overview.get().catch(() => null), @@ -687,7 +688,7 @@ export function registerSpaces(program: Command): void { // ── spaces update ── spacesCmd - .command("update ") + .command("update ") .description("Update a space") .option("--name ", "Space name") .option("--slug ", "Public space slug") @@ -719,7 +720,7 @@ export function registerSpaces(program: Command): void { // ── spaces rename ── spacesCmd - .command("rename ") + .command("rename ") .description("Rename a space") .action(async (id: string, name: string) => { const client = createClient(); @@ -774,7 +775,7 @@ export function registerSpaces(program: Command): void { // ── spaces config ── spacesCmd - .command("config ") + .command("config ") .description("Show or update space configuration") .option("--auto-destroy ", "Sandbox auto destroy mode: idle or never") .option("--idle-ttl ", "Idle auto destroy TTL in seconds, max 2592000 (30d)") @@ -897,7 +898,7 @@ export function registerSpaces(program: Command): void { // ── spaces pin / unpin (user-scope label convenience) ── spacesCmd - .command("pin ") + .command("pin ") .description("Pin a space (add the Pinned user label)") .action(async (id: string) => { const client = createClient(); @@ -911,7 +912,7 @@ export function registerSpaces(program: Command): void { }); spacesCmd - .command("unpin ") + .command("unpin ") .description("Unpin a space (remove the Pinned user label)") .action(async (id: string) => { const client = createClient(); @@ -1537,7 +1538,8 @@ export function attachSessionTail( ): void { const stdout = options.stdout ?? process.stdout; const stderr = options.stderr ?? process.stderr; - const exit = options.exit ?? ((code: number) => process.exit(code)); + // process.exit drops pending pipe writes; the empty write's callback runs once earlier records are flushed. + const exit = options.exit ?? ((code: number) => process.stdout.write("", () => process.exit(code))); let exiting = false; const finish = async (code: number) => { if (exiting) return; diff --git a/packages/cli/tests/run.test.ts b/packages/cli/tests/run.test.ts index 05d6800c6..3027216ff 100644 --- a/packages/cli/tests/run.test.ts +++ b/packages/cli/tests/run.test.ts @@ -8,7 +8,6 @@ import { parseRunCliOptions } from "../src/commands/run.js"; const SPACE_A = "11111111-1111-4111-8111-111111111111"; const SPACE_B = "22222222-2222-4222-8222-222222222222"; -const SPACE_PROJECT = "33333333-3333-4333-8333-333333333333"; const roots: string[] = []; @@ -73,39 +72,3 @@ test("cohub run accepts -s/--space/--space= both before and after run, without s else process.env.COHUB_SPACE_ID = previousSpace; } }); - -test("cohub run resolves username/slug passed after run", async () => { - const previousFetch = globalThis.fetch; - const previousBaseUrl = process.env.COHUB_BASE_URL; - const previousToken = process.env.COHUB_EXECUTION_TOKEN; - const previousSpace = process.env.COHUB_SPACE_ID; - process.env.COHUB_BASE_URL = "https://cohub-run-test.invalid"; - process.env.COHUB_EXECUTION_TOKEN = "test-token"; - delete process.env.COHUB_SPACE_ID; - globalThis.fetch = async (input) => { - const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url); - if (url.pathname === "/api/spaces/by-slug/atou/project") { - return new Response(JSON.stringify({ id: SPACE_PROJECT, slug: "project", name: "Project" }), { - status: 200, - headers: { "content-type": "application/json" }, - }); - } - return new Response(JSON.stringify({ message: `Unhandled ${url.pathname}` }), { - status: 404, - headers: { "content-type": "application/json" }, - }); - }; - try { - const options = await parseRunCliOptions(["run", "-s", "atou/project", "--", "git", "status"]); - assert.equal(options.spaceId, SPACE_PROJECT); - assert.equal(options.command, "git status"); - } finally { - globalThis.fetch = previousFetch; - if (previousBaseUrl === undefined) delete process.env.COHUB_BASE_URL; - else process.env.COHUB_BASE_URL = previousBaseUrl; - if (previousToken === undefined) delete process.env.COHUB_EXECUTION_TOKEN; - else process.env.COHUB_EXECUTION_TOKEN = previousToken; - if (previousSpace === undefined) delete process.env.COHUB_SPACE_ID; - else process.env.COHUB_SPACE_ID = previousSpace; - } -}); diff --git a/packages/cli/tests/space-ref-cli.test.ts b/packages/cli/tests/space-ref-cli.test.ts index cf08b4e2b..1781862cf 100644 --- a/packages/cli/tests/space-ref-cli.test.ts +++ b/packages/cli/tests/space-ref-cli.test.ts @@ -1,12 +1,14 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { Command } from "commander"; +import { registerApps } from "../src/commands/apps.js"; import { registerSearch } from "../src/commands/search.js"; import { attachSessionTail, registerSpaces } from "../src/commands/spaces.js"; const HOME_ID = "11111111-1111-4111-8111-111111111111"; const OWNED_ID = "22222222-2222-4222-8222-222222222222"; const OTHER_ID = "33333333-3333-4333-8333-333333333333"; +const APP_ID = "44444444-4444-4444-8444-444444444444"; let mockApiSeq = 0; @@ -80,6 +82,12 @@ async function withMockApi( if (method === "GET" && /^\/api\/apps\/space\/[^/]+$/.test(url.pathname)) { return json(200, { apps: [{ id: "app-1", slug: "welcome" }] }); } + if (method === "GET" && url.pathname === `/api/apps/${APP_ID}`) { + return json(200, { app: { id: APP_ID } }); + } + if (method === "POST" && url.pathname === `/api/apps/${APP_ID}/authorize`) { + return json(200, { grant: { scopes: ["space.view"], spaceId: (body as { spaceId?: string }).spaceId ?? "app-space" } }); + } if (method === "PATCH" && url.pathname === "/api/me/resources/space/labels") { return json(200, { assignments: [] }); } @@ -94,6 +102,7 @@ async function withMockApi( .option("-s, --space ", "Target Space"); registerSearch(program); registerSpaces(program); + registerApps(program); const logs: string[] = []; const originalLog = console.log; @@ -202,6 +211,19 @@ test("spaces positional Space-ref commands resolve UUID, home, own slug, and use }); }); +test("apps authorize --space resolves the ref and otherwise keeps the app's own Space", async () => { + await withMockApi(async ({ requests, runCli }) => { + process.env.COHUB_SPACE_ID = HOME_ID; + const authorizeBody = () => requests.findLast((r) => r.path === `/api/apps/${APP_ID}/authorize`)?.body; + + await runCli(["apps", "authorize", APP_ID, "--scope", "space.view", "--space", "atou/project", "--json"]); + assert.deepEqual(authorizeBody(), { scopes: ["space.view"], spaceId: OTHER_ID }); + + await runCli(["apps", "authorize", APP_ID, "--scope", "space.view", "--json"]); + assert.deepEqual(authorizeBody(), { scopes: ["space.view"] }); + }); +}); + test("attachSessionTail keeps stdout pure JSONL in --json mode and disconnects before exiting", async () => { const handlers = new Map }) => void>(); const events: string[] = []; From ab9a278e05605ee69726cce1de8b720fd39ef6af Mon Sep 17 00:00:00 2001 From: markbang Date: Mon, 23 Nov 2026 08:16:08 +0000 Subject: [PATCH 4/4] test(cli): trim Space ref and tail tests to one case per behavior Cohub Session: https://cohub.live/spaces/5089f055-9dbb-4fcd-b98c-fb232353281a/sessions/b03e6e71-e62e-4589-8f98-bffbf7825137 --- packages/cli/tests/run.test.ts | 10 +- packages/cli/tests/space-ref-cli.test.ts | 178 ++--------------------- packages/cli/tests/space.test.ts | 4 +- 3 files changed, 18 insertions(+), 174 deletions(-) diff --git a/packages/cli/tests/run.test.ts b/packages/cli/tests/run.test.ts index 3027216ff..d644a76dc 100644 --- a/packages/cli/tests/run.test.ts +++ b/packages/cli/tests/run.test.ts @@ -43,18 +43,10 @@ test("cohub run uses the current directory Runtime binding", async () => { } }); -test("cohub run accepts -s/--space/--space= both before and after run, without swallowing command flags", async () => { +test("cohub run accepts -s/--space after run without taking the command's own flags", async () => { const previousSpace = process.env.COHUB_SPACE_ID; delete process.env.COHUB_SPACE_ID; try { - assert.deepEqual( - await parseRunCliOptions(["-s", SPACE_A, "run", "--", "git", "status"]), - { spaceId: SPACE_A, json: false, async: false, command: "git status" }, - ); - assert.deepEqual( - await parseRunCliOptions(["run", "-s", SPACE_A, "--", "git", "status"]), - { spaceId: SPACE_A, json: false, async: false, command: "git status" }, - ); assert.deepEqual( await parseRunCliOptions(["run", "--space", SPACE_A, "--async", "--json", "--", "git", "status", "-s"]), { spaceId: SPACE_A, json: true, async: true, command: "git status -s" }, diff --git a/packages/cli/tests/space-ref-cli.test.ts b/packages/cli/tests/space-ref-cli.test.ts index 1781862cf..fb4a73cf5 100644 --- a/packages/cli/tests/space-ref-cli.test.ts +++ b/packages/cli/tests/space-ref-cli.test.ts @@ -66,16 +66,10 @@ async function withMockApi( if (method === "GET" && /^\/api\/spaces\/[^/]+\/overview$/.test(url.pathname)) { return json(200, { days: 30, apps: { count: 0, views: 0, likes: 0 } }); } - if (method === "GET" && /^\/api\/spaces\/[^/]+\/sandbox$/.test(url.pathname)) { - return json(200, { sandbox: { provider: "cloud", meta: { setup: null } } }); - } if (method === "PATCH" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { const id = url.pathname.split("/").at(-1); return json(200, { space: { id, name: "Updated", slug: "updated" } }); } - if (method === "GET" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { - return json(200, { config: { sandbox: { spec: "standard", allowedSpec: "standard" }, guest: null } }); - } if (method === "PATCH" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { return json(200, { config: { sandbox: { spec: "boost" }, guest: null }, sandbox: { pendingRestart: false } }); } @@ -88,9 +82,6 @@ async function withMockApi( if (method === "POST" && url.pathname === `/api/apps/${APP_ID}/authorize`) { return json(200, { grant: { scopes: ["space.view"], spaceId: (body as { spaceId?: string }).spaceId ?? "app-space" } }); } - if (method === "PATCH" && url.pathname === "/api/me/resources/space/labels") { - return json(200, { assignments: [] }); - } if (method === "PATCH" && url.pathname === "/api/me/resources/space/labels/batch") { return json(200, { resourceRefs: [], affectedLabelIds: [] }); } @@ -153,61 +144,22 @@ test("cohub search ignores COHUB_SPACE_ID, honors -s/--space, and resolves --spa }); }); -test("spaces positional Space-ref commands resolve UUID, home, own slug, and username/slug", async () => { +test("spaces commands resolve Space refs in positional arguments", async () => { await withMockApi(async ({ requests, runCli }) => { delete process.env.COHUB_SPACE_ID; - await runCli(["spaces", "setup", "atou/project", "--json"]); - assert.equal(requests.at(-1)?.path, `/api/spaces/${OTHER_ID}/sandbox`); - await runCli(["spaces", "get", "home", "--json"]); assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/spaces/${HOME_ID}`)); - await runCli(["-s", "notes", "spaces", "get", "--json"]); - assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/spaces/${OWNED_ID}`)); - await runCli(["spaces", "update", "atou/project", "--name", "Renamed", "--json"]); - const updateReq = requests.findLast((r) => r.method === "PATCH" && r.path === `/api/spaces/${OTHER_ID}`); - assert.deepEqual(updateReq?.body, { name: "Renamed" }); - - await runCli(["spaces", "rename", "notes", "New Notes"]); - const renameReq = requests.findLast((r) => r.method === "PATCH" && r.path === `/api/spaces/${OWNED_ID}`); - assert.deepEqual(renameReq?.body, { name: "New Notes" }); + assert.ok(requests.some((r) => r.method === "PATCH" && r.path === `/api/spaces/${OTHER_ID}`)); - await runCli(["spaces", "config", "atou/project", "--json"]); - assert.equal(requests.at(-1)?.path, `/api/spaces/${OTHER_ID}/config`); - - await runCli(["spaces", "config", "atou/project", "--guest-app", "welcome", "--json"]); - assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/apps/space/${OTHER_ID}`)); - const configPatch = requests.findLast((r) => r.method === "PATCH" && r.path === `/api/spaces/${OTHER_ID}/config`); - assert.deepEqual(configPatch?.body, { guest: { appId: "app-1" } }); - - await runCli(["spaces", "pin", "atou/project"]); - const pinReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels"); - assert.equal(pinReq?.query.get("resourceRef"), OTHER_ID); - assert.deepEqual(pinReq?.body, { addLabelRefs: ["Pinned"] }); - - await runCli(["spaces", "unpin", "notes"]); - const unpinReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels"); - assert.equal(unpinReq?.query.get("resourceRef"), OWNED_ID); - assert.deepEqual(unpinReq?.body, { removeLabelRefs: ["Pinned"] }); + await runCli(["spaces", "config", "notes", "--guest-app", "welcome", "--json"]); + assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/apps/space/${OWNED_ID}`)); + assert.ok(requests.some((r) => r.method === "PATCH" && r.path === `/api/spaces/${OWNED_ID}/config`)); const archiveOut = await runCli(["spaces", "archive", "home", "atou/project", "--json"]); - const archiveReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels/batch"); - assert.deepEqual(archiveReq?.body, { - resourceRefs: [HOME_ID, OTHER_ID], - addLabelRefs: ["Archived"], - removeLabelRefs: ["Pinned"], - }); assert.deepEqual(JSON.parse(archiveOut), { ids: [HOME_ID, OTHER_ID], archived: true }); - - const unarchiveOut = await runCli(["spaces", "unarchive", "notes", "--json"]); - const unarchiveReq = requests.findLast((r) => r.path === "/api/me/resources/space/labels/batch"); - assert.deepEqual(unarchiveReq?.body, { - resourceRefs: [OWNED_ID], - removeLabelRefs: ["Archived"], - }); - assert.deepEqual(JSON.parse(unarchiveOut), { ids: [OWNED_ID], archived: false }); }); }); @@ -224,119 +176,21 @@ test("apps authorize --space resolves the ref and otherwise keeps the app's own }); }); -test("attachSessionTail keeps stdout pure JSONL in --json mode and disconnects before exiting", async () => { +test("sessions tail --json writes only JSONL to stdout", async () => { const handlers = new Map }) => void>(); - const events: string[] = []; let stdout = ""; - let stderr = ""; - let exitCode: number | null = null; - let resolveExit!: () => void; - const exited = new Promise((resolve) => { - resolveExit = resolve; + const exited = new Promise((resolve) => { + attachSessionTail( + { disconnect: async () => {} }, + { on: (event, handler) => { handlers.set(event, handler); } }, + { json: true, stdout: { write: (chunk) => { stdout += chunk; } }, stderr: { write: () => {} }, exit: resolve }, + ); }); - attachSessionTail( - { - disconnect: async () => { - events.push("disconnect"); - throw new Error("socket already closed"); - }, - }, - { - on: (event, handler) => { - handlers.set(event, handler); - }, - }, - { - json: true, - stdout: { write: (chunk) => { stdout += chunk; } }, - stderr: { write: (chunk) => { stderr += chunk; } }, - exit: (code) => { - events.push(`exit:${code}`); - exitCode = code; - resolveExit(); - }, - }, - ); - - assert.equal(stdout, ""); - handlers.get("turn.patch")?.({ payload: { ops: [{ o: "append", p: "/text", v: "hello" }] } }); - handlers.get("turn.patch")?.({ payload: { ops: [{ o: "append", p: "/text", v: " world" }] } }); + const patch = { payload: { ops: [{ o: "append", p: "/message/content/blocks/0/text", v: "hello" }] } }; + handlers.get("turn.patch")?.(patch); handlers.get("turn.finalized")?.({}); - await exited; - - assert.equal(stderr, ""); - assert.equal(exitCode, 0); - assert.deepEqual(events, ["disconnect", "exit:0"]); - const lines = stdout.trim().split("\n"); - assert.equal(lines.length, 2); - assert.deepEqual(lines.map((line) => JSON.parse(line)), [ - { payload: { ops: [{ o: "append", p: "/text", v: "hello" }] } }, - { payload: { ops: [{ o: "append", p: "/text", v: " world" }] } }, - ]); -}); - -test("attachSessionTail disconnects cleanly before exiting on turn.error and preserves human output", async () => { - const errorHandlers = new Map }) => void>(); - const errorEvents: string[] = []; - let jsonStdout = ""; - let jsonStderr = ""; - let resolveErrExit!: () => void; - const errExited = new Promise((resolve) => { - resolveErrExit = resolve; - }); - - attachSessionTail( - { - disconnect: async () => { - errorEvents.push("disconnect"); - }, - }, - { - on: (event, handler) => { - errorHandlers.set(event, handler); - }, - }, - { - json: true, - stdout: { write: (chunk) => { jsonStdout += chunk; } }, - stderr: { write: (chunk) => { jsonStderr += chunk; } }, - exit: (code) => { - errorEvents.push(`exit:${code}`); - resolveErrExit(); - }, - }, - ); - - errorHandlers.get("turn.error")?.({ payload: { message: "boom" } }); - await errExited; - - assert.equal(jsonStdout, ""); - assert.match(jsonStderr, /✗ Error/); - assert.match(jsonStderr, /"message":"boom"/); - assert.deepEqual(errorEvents, ["disconnect", "exit:1"]); - - const humanHandlers = new Map }) => void>(); - let humanStdout = ""; - let resolveHumanExit!: () => void; - const humanExited = new Promise((resolve) => { - resolveHumanExit = resolve; - }); - - attachSessionTail( - { disconnect: async () => {} }, - { on: (event, handler) => { humanHandlers.set(event, handler); } }, - { - json: false, - stdout: { write: (chunk) => { humanStdout += chunk; } }, - stderr: { write: () => {} }, - exit: () => resolveHumanExit(), - }, - ); - - humanHandlers.get("turn.patch")?.({ payload: { ops: [{ o: "append", p: "/text", v: "hi" }] } }); - humanHandlers.get("turn.finalized")?.({}); - await humanExited; - assert.equal(humanStdout, " Listening for events...\n\nhi\n\n ✓ Done\n"); + assert.equal(await exited, 0); + assert.deepEqual(stdout.trim().split("\n").map((line) => JSON.parse(line)), [patch]); }); diff --git a/packages/cli/tests/space.test.ts b/packages/cli/tests/space.test.ts index 2f9258d5f..095ea9357 100644 --- a/packages/cli/tests/space.test.ts +++ b/packages/cli/tests/space.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, test } from "node:test"; import { Command } from "commander"; -import { explicitSpace, explicitSpaceFlag, identityKeyFrom, readHomeSpaceCache } from "../src/space.js"; +import { explicitSpace, identityKeyFrom, readHomeSpaceCache } from "../src/space.js"; const DAY_MS = 86_400_000; const tempDirs: string[] = []; @@ -39,8 +39,6 @@ test("explicit space prefers -s over COHUB_SPACE_ID", () => { try { assert.equal(explicitSpace(programWithSpace("from-flag")), "from-flag"); assert.equal(explicitSpace(programWithSpace()), "from-env"); - assert.equal(explicitSpaceFlag(programWithSpace("from-flag")), "from-flag"); - assert.equal(explicitSpaceFlag(programWithSpace()), null); } finally { if (previous === undefined) delete process.env.COHUB_SPACE_ID; else process.env.COHUB_SPACE_ID = previous;