From 68fbd4760c95e60c0663ced88924453ba1bd46f9 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 20 Nov 2026 16:15:23 +0530 Subject: [PATCH 1/2] fix(cli): print plain errors for bad session ids, flag checks and refused connections - A session id that is not a session id printed a schema stack; every command that takes one now prints one error line. - A handler failure raised before its own catch reached the runtime's logger with a stack. The command wrapper now renders every handler failure as an error line. - A failed connection named no cause. The CLI now asks the home's server why and says when it refused the token or the host. - Give the CLI tests a 30 second timeout: they spawn the real CLI and server, which start slowly when many run at once. Co-Authored-By: Claude Fable 5.2 --- .../src/cli/cmd/handlers/mcp/control.ts | 6 +- .../src/cli/cmd/handlers/plugin/session.ts | 5 +- packages/codework/src/cli/cmd/handlers/run.ts | 32 ++--- .../src/cli/cmd/handlers/session/link.ts | 5 +- .../src/cli/cmd/handlers/session/relink.ts | 7 +- .../src/cli/cmd/handlers/thread/fork.ts | 6 +- .../src/cli/cmd/handlers/thread/list.ts | 5 +- .../codework/src/cli/{thread.ts => ids.ts} | 9 +- packages/codework/src/cli/service.ts | 113 +++++++++++------- packages/codework/src/framework/runtime.ts | 9 +- packages/codework/src/index.ts | 3 +- .../codework/test/__artifacts__/door.json | 22 +++- packages/codework/test/cli.test.ts | 6 +- packages/codework/test/door.test.ts | 15 +++ packages/codework/vite.config.ts | 2 + 15 files changed, 165 insertions(+), 80 deletions(-) rename packages/codework/src/cli/{thread.ts => ids.ts} (62%) diff --git a/packages/codework/src/cli/cmd/handlers/mcp/control.ts b/packages/codework/src/cli/cmd/handlers/mcp/control.ts index c2aa3308..b5f5b929 100644 --- a/packages/codework/src/cli/cmd/handlers/mcp/control.ts +++ b/packages/codework/src/cli/cmd/handlers/mcp/control.ts @@ -1,11 +1,10 @@ -import { Session } from "@codeworksh/harness/effect"; import { Effect, type Option } from "effect"; import * as Runtime from "../../../../framework/runtime.ts"; import * as Client from "../../../../server/client.ts"; import * as Service from "../../../service.ts"; import { reportFailure } from "../../../error.ts"; import { writeOut } from "../../../output.ts"; -import { threadFlag } from "../../../thread.ts"; +import { sessionId, threadFlag } from "../../../ids.ts"; import { Cmd } from "../../cmd.ts"; import { describe, MARKS } from "./shared.ts"; @@ -25,11 +24,12 @@ const control = (operation: "connect" | "disconnect") => readonly thread: Option.Option; readonly server: string; }) { + const id = yield* sessionId(session); const program = Effect.gen(function* () { const threadId = yield* threadFlag(thread); const rpc = yield* Client.make; const status = yield* rpc[`mcp.${operation}`]({ - sessionId: Session.SessionSchema.ID.make(session), + sessionId: id, ...(threadId === undefined ? {} : { threadId }), server: name, }); diff --git a/packages/codework/src/cli/cmd/handlers/plugin/session.ts b/packages/codework/src/cli/cmd/handlers/plugin/session.ts index a6cafd3b..5e579fab 100644 --- a/packages/codework/src/cli/cmd/handlers/plugin/session.ts +++ b/packages/codework/src/cli/cmd/handlers/plugin/session.ts @@ -1,5 +1,6 @@ -import { Database, Event, Global, Session, SessionStore } from "@codeworksh/harness/effect"; +import { Database, Event, Global, SessionStore } from "@codeworksh/harness/effect"; import { Effect, Layer, Option } from "effect"; +import { sessionId as parse } from "../../../ids.ts"; /** * The host directory a session is linked to. @@ -19,7 +20,7 @@ export const linkedDirectory = Effect.fn("CLI.plugin.linkedDirectory")(function* home: Option.Option, ) { const paths = yield* Global.resolve(Option.isNone(home) ? {} : { home: home.value }); - const id = Session.SessionSchema.ID.ascending(sessionId); + const id = yield* parse(sessionId); return yield* Effect.gen(function* () { const sessions = yield* SessionStore.Service; diff --git a/packages/codework/src/cli/cmd/handlers/run.ts b/packages/codework/src/cli/cmd/handlers/run.ts index 176d81ed..461d5344 100644 --- a/packages/codework/src/cli/cmd/handlers/run.ts +++ b/packages/codework/src/cli/cmd/handlers/run.ts @@ -15,7 +15,7 @@ import { writeError, writeOut, } from "../../output.ts"; -import { threadFlag } from "../../thread.ts"; +import { sessionId, threadFlag } from "../../ids.ts"; import { Cmd } from "../cmd.ts"; interface RenderState { @@ -120,6 +120,7 @@ export default Runtime.handler( return yield* new InvalidInputError({ message: "--thread continues a thread of --session" }); } const threadId = yield* threadFlag(thread); + const id = Option.isSome(session) ? yield* sessionId(session.value) : undefined; if (Option.isSome(provider) !== Option.isSome(model)) { return yield* new InvalidInputError({ message: "--provider and --model must be provided together" }); } @@ -161,18 +162,19 @@ export default Runtime.handler( }; const remote = Effect.gen(function* () { const rpc = yield* Client.make; - const info = Option.isSome(session) - ? yield* rpc["thread.configure"]({ - sessionId: Session.SessionSchema.ID.make(session.value), - ...(threadId === undefined ? {} : { threadId }), - runtime, - }) - : yield* rpc["session.create"]({ - runtime, - ...(Option.isNone(cwd) ? {} : { directory: cwd.value }), - hostDir, - sandbox: selection, - }); + const info = + id !== undefined + ? yield* rpc["thread.configure"]({ + sessionId: id, + ...(threadId === undefined ? {} : { threadId }), + runtime, + }) + : yield* rpc["session.create"]({ + runtime, + ...(Option.isNone(cwd) ? {} : { directory: cwd.value }), + hostDir, + sandbox: selection, + }); const state = yield* Ref.make(initialRenderState); const columns = terminalColumns(); yield* writeError( @@ -196,9 +198,9 @@ export default Runtime.handler( }); const program = Effect.gen(function* () { let handle: Session.ThreadHandle; - if (Option.isSome(session)) { + if (id !== undefined) { handle = yield* Session.attach({ - sessionId: Session.SessionSchema.ID.make(session.value), + sessionId: id, ...(threadId === undefined ? {} : { threadId }), ...runtime, }); diff --git a/packages/codework/src/cli/cmd/handlers/session/link.ts b/packages/codework/src/cli/cmd/handlers/session/link.ts index 9e95aef0..ee4804e1 100644 --- a/packages/codework/src/cli/cmd/handlers/session/link.ts +++ b/packages/codework/src/cli/cmd/handlers/session/link.ts @@ -2,6 +2,7 @@ import { Session } from "@codeworksh/harness/effect"; import { Effect, Option, Path } from "effect"; import * as Runtime from "../../../../framework/runtime.ts"; import { reportFailure } from "../../../error.ts"; +import { sessionId } from "../../../ids.ts"; import { writeOut } from "../../../output.ts"; import * as Client from "../../../../server/client.ts"; import * as Service from "../../../service.ts"; @@ -29,16 +30,16 @@ import { Cmd } from "../../cmd.ts"; export default Runtime.handler( Cmd.commands.session.commands.link, Effect.fn("CLI.session.link")(function* ({ session, path, unlink, server }) { + const id = yield* sessionId(session); const program = Effect.gen(function* () { const nodePath = yield* Path.Path; const rpc = yield* Client.make; - const sessionId = Session.SessionSchema.ID.make(session); const hostDir = unlink ? undefined : Session.AbsolutePath.make(nodePath.resolve(Option.getOrElse(path, () => "."))); const info = yield* rpc["session.link"]({ - sessionId, + sessionId: id, ...(hostDir === undefined ? {} : { hostDir }), }); // Settings are re-read every exchange, so this applies at the next one: no reload, no diff --git a/packages/codework/src/cli/cmd/handlers/session/relink.ts b/packages/codework/src/cli/cmd/handlers/session/relink.ts index 1f91565b..d7483ec7 100644 --- a/packages/codework/src/cli/cmd/handlers/session/relink.ts +++ b/packages/codework/src/cli/cmd/handlers/session/relink.ts @@ -1,4 +1,4 @@ -import { Sandbox, Session } from "@codeworksh/harness/effect"; +import { Sandbox } from "@codeworksh/harness/effect"; import { Effect, Option } from "effect"; import * as Runtime from "../../../../framework/runtime.ts"; import * as Client from "../../../../server/client.ts"; @@ -6,17 +6,18 @@ import * as Service from "../../../service.ts"; import { ThreadInfo } from "../../../../server/contract.ts"; import { reportFailure } from "../../../error.ts"; import { writeJson, writeOut } from "../../../output.ts"; -import { threadFlag } from "../../../thread.ts"; +import { sessionId, threadFlag } from "../../../ids.ts"; import { Cmd } from "../../cmd.ts"; export default Runtime.handler( Cmd.commands.session.commands.relink, Effect.fn("CLI.session.relink")(function* ({ session, thread, directory, sandboxId, json, server }) { + const id = yield* sessionId(session); const program = Effect.gen(function* () { const threadId = yield* threadFlag(thread); const rpc = yield* Client.make; const info = yield* rpc["session.relink"]({ - sessionId: Session.SessionSchema.ID.make(session), + sessionId: id, ...(threadId === undefined ? {} : { threadId }), ...(Option.isNone(sandboxId) ? {} : { sandbox: { id: Sandbox.SandboxInstance.ID.make(sandboxId.value) } }), ...(Option.isNone(directory) ? {} : { directory: directory.value }), diff --git a/packages/codework/src/cli/cmd/handlers/thread/fork.ts b/packages/codework/src/cli/cmd/handlers/thread/fork.ts index 9de9e4c4..b2f68d6a 100644 --- a/packages/codework/src/cli/cmd/handlers/thread/fork.ts +++ b/packages/codework/src/cli/cmd/handlers/thread/fork.ts @@ -1,4 +1,3 @@ -import { Session } from "@codeworksh/harness/effect"; import { Effect, Option, Schema } from "effect"; import * as Runtime from "../../../../framework/runtime.ts"; import * as Client from "../../../../server/client.ts"; @@ -6,7 +5,7 @@ import * as Service from "../../../service.ts"; import { ThreadInfo } from "../../../../server/contract.ts"; import { InvalidInputError, reportFailure } from "../../../error.ts"; import { writeJson, writeOut } from "../../../output.ts"; -import { threadFlag } from "../../../thread.ts"; +import { sessionId, threadFlag } from "../../../ids.ts"; import { Cmd } from "../../cmd.ts"; const Forked = Schema.Struct({ thread: ThreadInfo, text: Schema.optional(Schema.String) }); @@ -14,6 +13,7 @@ const Forked = Schema.Struct({ thread: ThreadInfo, text: Schema.optional(Schema. export default Runtime.handler( Cmd.commands.thread.commands.fork, Effect.fn("CLI.thread.fork")(function* ({ session, thread, at, before, json, server }) { + const id = yield* sessionId(session); const program = Effect.gen(function* () { const point = Option.isSome(at) ? Option.isNone(before) @@ -26,7 +26,7 @@ export default Runtime.handler( const threadId = yield* threadFlag(thread); const rpc = yield* Client.make; const forked = yield* rpc["thread.fork"]({ - sessionId: Session.SessionSchema.ID.make(session), + sessionId: id, ...(threadId === undefined ? {} : { threadId }), ...point, }); diff --git a/packages/codework/src/cli/cmd/handlers/thread/list.ts b/packages/codework/src/cli/cmd/handlers/thread/list.ts index c58e1ebd..8999f3cf 100644 --- a/packages/codework/src/cli/cmd/handlers/thread/list.ts +++ b/packages/codework/src/cli/cmd/handlers/thread/list.ts @@ -1,10 +1,10 @@ -import { Session } from "@codeworksh/harness/effect"; import { Effect, Schema } from "effect"; import * as Runtime from "../../../../framework/runtime.ts"; import * as Client from "../../../../server/client.ts"; import * as Service from "../../../service.ts"; import { type ThreadInfo, ThreadInfo as ThreadInfoSchema } from "../../../../server/contract.ts"; import { reportFailure } from "../../../error.ts"; +import { sessionId } from "../../../ids.ts"; import { writeJson, writeOut } from "../../../output.ts"; import { Cmd } from "../../cmd.ts"; @@ -24,9 +24,10 @@ const cost = (info: ThreadInfo) => `$${info.usage.cost.toFixed(4)}`; export default Runtime.handler( Cmd.commands.thread.commands.list, Effect.fn("CLI.thread.list")(function* ({ session, json, server }) { + const id = yield* sessionId(session); const program = Effect.gen(function* () { const rpc = yield* Client.make; - const threads = yield* rpc["thread.list"]({ sessionId: Session.SessionSchema.ID.make(session) }); + const threads = yield* rpc["thread.list"]({ sessionId: id }); if (json) return yield* writeJson(Schema.Array(ThreadInfoSchema), threads); if (threads.length === 0) return yield* writeOut(`No threads in ${session}.\n`); const rows = threads.map((info) => [ diff --git a/packages/codework/src/cli/thread.ts b/packages/codework/src/cli/ids.ts similarity index 62% rename from packages/codework/src/cli/thread.ts rename to packages/codework/src/cli/ids.ts index 733cb36b..26b04c85 100644 --- a/packages/codework/src/cli/thread.ts +++ b/packages/codework/src/cli/ids.ts @@ -2,13 +2,20 @@ import { Session } from "@codeworksh/harness/effect"; import { Effect, Option, Schema } from "effect"; import { InvalidInputError } from "./error.ts"; +const isSessionId = Schema.is(Session.SessionSchema.ID); const isThreadId = Schema.is(Session.ThreadSchema.ID); +/** A session ID as a person typed it; checked here because the schema's `make` throws. */ +export const sessionId = Effect.fn("CLI.sessionId")(function* (value: string) { + if (!isSessionId(value)) return yield* new InvalidInputError({ message: `${value} is not a session ID (ses_…)` }); + return value; +}); + /** A `--thread` value; `main`, like no flag at all, is the session's main thread and reads as absent. */ export const threadFlag = Effect.fn("CLI.threadFlag")(function* (flag: Option.Option) { if (Option.isNone(flag) || flag.value === Session.ThreadSchema.MAIN) return undefined; if (!isThreadId(flag.value)) { return yield* new InvalidInputError({ message: "--thread takes a thread ID (thr_…) or main" }); } - return Session.ThreadSchema.ID.make(flag.value); + return flag.value; }); diff --git a/packages/codework/src/cli/service.ts b/packages/codework/src/cli/service.ts index e372904f..136b2e8a 100644 --- a/packages/codework/src/cli/service.ts +++ b/packages/codework/src/cli/service.ts @@ -1,5 +1,7 @@ import { Global } from "@codeworksh/harness/effect"; -import { Effect, Layer, Option, Schema } from "effect"; +import { Door } from "@codeworksh/schema"; +import { Effect, Option, Schema } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; import { RpcClientError } from "effect/rpc"; import * as Client from "../server/client.ts"; import type * as Discovery from "../server/discovery.ts"; @@ -57,52 +59,77 @@ const same = (a: string, b: string) => { }; /** - * A client of the server at `url`, which must be the one the home's `service.json` names: the token - * goes nowhere else, as any other server, however local it looks, may belong to someone else. A - * loopback alias of that URL connects to it as filed. + * The server at `url`, which must be the one the home's `service.json` names: the token goes nowhere + * else, as any other server, however local it looks, may belong to someone else. A loopback alias + * of that URL is the server as filed. */ -const client = (url: string) => - Layer.unwrap( - Effect.gen(function* () { - const paths = yield* home(yield* Cmd.spec); - const registered = yield* Registration.read(Registration.file(paths.home)); - if (registered === undefined) - return yield* new ConnectError({ - message: [ - "no CodeWork server is running for this home", - "hint: start one with `codework service start`", - ].join("\n"), - }); - if (!same(registered.url, url)) - return yield* new ConnectError({ - message: [ - `${url} is not this home's server`, - `hint: this home's server is ${registered.url}; pass --home for another home's server`, - ].join("\n"), - }); - return Client.layer({ url: registered.url, token: registered.token }); - }), - ); +const target = Effect.fn("CLI.target")(function* (url: string) { + const paths = yield* home(yield* Cmd.spec); + const registered = yield* Registration.read(Registration.file(paths.home)); + if (registered === undefined) + return yield* new ConnectError({ + message: ["no CodeWork server is running for this home", "hint: start one with `codework service start`"].join( + "\n", + ), + }); + if (!same(registered.url, url)) + return yield* new ConnectError({ + message: [ + `${url} is not this home's server`, + `hint: this home's server is ${registered.url}; pass --home for another home's server`, + ].join("\n"), + }); + return { url: registered.url, token: registered.token }; +}); /** - * Runs `program` against the server at `url`. A socket that does not open names no reason: the - * WebSocket hides the HTTP status, so a refused token, a stopped server and a wrong port look alike. + * Why a socket to `server` did not open. The WebSocket hides the HTTP status, so the same request + * is made again as a plain GET, with the token offered the same way, and the door's status read. */ +const refused = Effect.fn("CLI.refused")(function* (url: string, server: Client.Target) { + const status = yield* HttpClient.get(server.url.replace(/^ws/, "http"), { + headers: { "sec-websocket-protocol": Door.protocols(server.token).join(", ") }, + }).pipe( + Effect.map((response) => response.status), + Effect.timeout("2 seconds"), + Effect.provide(FetchHttpClient.layer), + Effect.orElseSucceed(() => undefined), + ); + switch (status) { + case 401: + return yield* new ConnectError({ + message: [ + `the CodeWork server at ${url} refused this home's token`, + "hint: restart it with `codework service restart`, or check --home names its home", + ].join("\n"), + }); + case 403: + return yield* new ConnectError({ + message: `the CodeWork server at ${url} refused the request's host or origin`, + }); + default: + return yield* new ConnectError({ + message: [ + `could not connect to the CodeWork server at ${url}`, + "hint: check it is running with `codework service status`", + ].join("\n"), + }); + } +}); + +/** Runs `program` against the server at `url`, naming why when its socket does not open. */ export const connect = (url: string) => (program: Effect.Effect) => - program.pipe( - // Scoped inside the client, so the program's own finalizers still reach the server. - Effect.scoped, - Effect.provide(client(url)), - Effect.mapError((error) => - isClientError(error) && error.reason._tag === "SocketOpenError" - ? new ConnectError({ - message: [ - `could not connect to the CodeWork server at ${url}`, - "hint: check it is running with `codework service status`", - ].join("\n"), - }) - : error, - ), - ); + Effect.gen(function* () { + const server = yield* target(url); + return yield* program.pipe( + // Scoped inside the client, so the program's own finalizers still reach the server. + Effect.scoped, + Effect.provide(Client.layer(server)), + Effect.catchIf( + (error) => isClientError(error) && error.reason._tag === "SocketOpenError", + () => refused(url, server), + ), + ); + }); diff --git a/packages/codework/src/framework/runtime.ts b/packages/codework/src/framework/runtime.ts index 7c1018a2..f6e0a834 100644 --- a/packages/codework/src/framework/runtime.ts +++ b/packages/codework/src/framework/runtime.ts @@ -43,7 +43,7 @@ interface LazyHandler { type LazyHandlers = LazyHandler["load"] | { readonly [key: string]: LazyHandlers | undefined }; -type ProvidedCommand = Command.Command; +type ProvidedCommand = Command.Command; /** Type-checks a handler against the spec node it implements. */ export function handler(_node: Node, run: Run>) { @@ -88,6 +88,13 @@ function provide( Command.withHandler((input) => Effect.promise(found.load).pipe( Effect.flatMap((module) => module.default(input)), + // Rendered here, so a handler's own failure prints as `error:` instead of reaching the + // runtime's logger with a stack. Imported on failure: the renderer pulls in the harness. + Effect.catch((error) => + Effect.promise(() => import("../cli/error.ts")).pipe( + Effect.flatMap((module) => module.reportFailure(error)), + ), + ), Effect.provide(Otel.layer({ version: context.version, command })), ), ), diff --git a/packages/codework/src/index.ts b/packages/codework/src/index.ts index 4d677e87..4ccdeadf 100644 --- a/packages/codework/src/index.ts +++ b/packages/codework/src/index.ts @@ -6,7 +6,6 @@ import { Effect } from "effect"; import type { CliError } from "effect/cli"; import pkg from "../package.json" with { type: "json" }; import { Cmd } from "./cli/cmd/cmd.ts"; -import type { CommandError } from "./cli/error.ts"; import * as Runtime from "./framework/runtime.ts"; const Handlers = Runtime.handlers(Cmd, { @@ -60,7 +59,7 @@ const Handlers = Runtime.handlers(Cmd, { }, }); -export const main: Effect.Effect = Runtime.run(Cmd, Handlers, { +export const main: Effect.Effect = Runtime.run(Cmd, Handlers, { version: pkg.version, }).pipe(Effect.provide(NodeServices.layer)); diff --git a/packages/codework/test/__artifacts__/door.json b/packages/codework/test/__artifacts__/door.json index f4d01607..763e3de8 100644 --- a/packages/codework/test/__artifacts__/door.json +++ b/packages/codework/test/__artifacts__/door.json @@ -63,13 +63,33 @@ "a filed server that refuses the token": { "status": 1, "stdout": "", - "stderr": "error: could not connect to the CodeWork server at \nhint: check it is running with `codework service status`\n" + "stderr": "error: the CodeWork server at refused this home's token\nhint: restart it with `codework service restart`, or check --home names its home\n" }, "a filed server that is gone": { "status": 1, "stdout": "", "stderr": "error: could not connect to the CodeWork server at \nhint: check it is running with `codework service status`\n" }, + "a filed server that refuses the host": { + "status": 1, + "stdout": "", + "stderr": "error: the CodeWork server at refused the request's host or origin\n" + }, + "not a session id": { + "status": 1, + "stdout": "", + "stderr": "error: foo is not a session ID (ses_…)\n" + }, + "run with not a session id": { + "status": 1, + "stdout": "", + "stderr": "error: foo is not a session ID (ses_…)\n" + }, + "run with --user-config-dir and --server": { + "status": 1, + "stdout": "", + "stderr": "error: --database and --user-config-dir belong on codework serve when using --server\n" + }, "stop": { "status": 0, "stdout": "", diff --git a/packages/codework/test/cli.test.ts b/packages/codework/test/cli.test.ts index 7d7f5ddd..35d6e8b9 100644 --- a/packages/codework/test/cli.test.ts +++ b/packages/codework/test/cli.test.ts @@ -136,7 +136,7 @@ describe("codework CLI", () => { const result = run("run", "--sandbox-provider-id", "existing-id", "test"); expect(result.status).toBe(1); - expect(result.stdout).toContain("--sandbox-provider-id requires a remote --sandbox-driver"); + expect(result.stderr).toBe("error: --sandbox-provider-id requires a remote --sandbox-driver\n"); }); it("reports an invalid model catalog without an Effect stack", () => { @@ -192,7 +192,9 @@ describe("codework CLI", () => { expect(run("run", "--help").stdout).toContain("--server"); const result = run("run", "--server", "ws://127.0.0.1:1/rpc/v1", "--database", ":memory:", "hello"); expect(result.status).toBe(1); - expect(result.stdout).toContain("belong on codework serve"); + expect(result.stderr).toBe( + "error: --database and --user-config-dir belong on codework serve when using --server\n", + ); }); it("rejects out-of-range listening ports", () => { diff --git a/packages/codework/test/door.test.ts b/packages/codework/test/door.test.ts index 21a566c4..7f442c81 100644 --- a/packages/codework/test/door.test.ts +++ b/packages/codework/test/door.test.ts @@ -100,8 +100,11 @@ it("the loopback server opens its socket only to a caller with its home's token" const session = yield* otherRpc["session.create"]({}); const alias = otherServer.url.replace("127.0.0.1", "localhost"); const gone = `ws://127.0.0.1:${yield* Effect.promise(closedPort)}/rpc/v1`; + // A name of this machine the loopback listener does not answer to. + const foreign = url.replace("127.0.0.1", "localhost."); const scrub = (text: string) => text + .replaceAll(foreign, "") .replaceAll(otherServer.url, "") .replaceAll(alias, "") .replaceAll(gone, "") @@ -138,6 +141,14 @@ it("the loopback server opens its socket only to a caller with its home's token" const auth = yield* run("auth", "status", "--openai-codex", "--server", otherServer.url); const wrongToken = yield* stale(url, "thread", "list", session.session.id, "--server", url); const unreachable = yield* stale(gone, "thread", "list", session.session.id, "--server", gone); + const hostRefused = yield* stale(foreign, "thread", "list", session.session.id, "--server", foreign); + + // A session id the schema refuses, and a flag check of run: each one `error:` line. + const notSession = yield* run("thread", "list", "foo", "--server", otherServer.url); + const runNotSession = yield* run("run", "--session", "foo", "hi", "--server", otherServer.url); + // cli() passes --user-config-dir, which run refuses next to --server. + const runFlags = yield* run("run", "hi", "--server", otherServer.url); + const stopped = yield* run("service", "stop"); const afterStop = yield* run("service", "status"); const noServer = yield* run("thread", "list", session.session.id, "--server", otherServer.url); @@ -160,6 +171,10 @@ it("the loopback server opens its socket only to a caller with its home's token" "auth status with --home and --server": auth, "a filed server that refuses the token": wrongToken, "a filed server that is gone": unreachable, + "a filed server that refuses the host": hostRefused, + "not a session id": notSession, + "run with not a session id": runNotSession, + "run with --user-config-dir and --server": runFlags, stop: stopped, "status after stop": afterStop, "no server for the home": noServer, diff --git a/packages/codework/vite.config.ts b/packages/codework/vite.config.ts index 79f50ee3..a3ca6ac4 100644 --- a/packages/codework/vite.config.ts +++ b/packages/codework/vite.config.ts @@ -66,6 +66,8 @@ export default defineConfig({ }, test: { include: ["test/**/*.test.ts"], + // These tests spawn the real CLI and server, which start slowly when many run at once. + testTimeout: 30_000, }, lint: { ...recommended, From 4335510e1b3dbb9dfd552159fe0a822795fc7fe4 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 20 Nov 2026 16:15:23 +0530 Subject: [PATCH 2/2] test(server): fix a wrong revision assertion and run live suites serially The live sync suite assumed the main thread never commits last among four concurrent writes. When it does, its revision is the store head, which is legal. The stale-write check now targets whichever thread is older. The live suites share the OrbStack machines, so they are now a test project of their own that runs one file at a time. Co-Authored-By: Claude Fable 5.2 --- apps/server/test/sync.machines.live.test.ts | 16 ++++++++++------ apps/server/vite.config.ts | 9 ++++++++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/apps/server/test/sync.machines.live.test.ts b/apps/server/test/sync.machines.live.test.ts index 678b4625..2d0cc55f 100644 --- a/apps/server/test/sync.machines.live.test.ts +++ b/apps/server/test/sync.machines.live.test.ts @@ -946,22 +946,26 @@ describeMachines("sync across OrbStack machines", () => { ); await caughtUp(machineId, ubuntu); const appThread = query(appHome, "SELECT thinking_level FROM thread WHERE id = ?", fork.id)[0]; - // The main thread's row is older than the head: rewriting it with its own rev is a write without the current revision. - const [stale] = await ubuntu.sql(`SELECT rev FROM thread WHERE id = '${created.id}'`); + // Whichever thread's write committed last may hold the head; none of the writes above touches both, so + // the other one is older, and rewriting that row with its own rev is a write without the current revision. + const [stale] = await ubuntu.sql( + `SELECT id, title, rev FROM thread WHERE id IN ('${created.id}', '${fork.id}') ORDER BY rev LIMIT 1`, + ); expect(stale!.rev as number).toBeLessThan(store!.rev as number); + const staleId = String(stale!.id); const refused = await ubuntu.refused( - `UPDATE thread SET title = 'Not at the current revision' WHERE id = '${created.id}';`, + `UPDATE thread SET title = 'Not at the current revision' WHERE id = '${staleId}';`, ); // A write that stamps the head without taking a new revision is not caught: the trigger compares with // store.rev only, so it cannot tell a forgotten increment from a second write in the same transaction. const atHead = await ubuntu.refused( - `UPDATE thread SET title = 'At the head, untaken', rev = (SELECT rev FROM store) WHERE id = '${created.id}';`, + `UPDATE thread SET title = 'At the head, untaken', rev = (SELECT rev FROM store) WHERE id = '${staleId}';`, ); const [headAfter] = await ubuntu.sql("SELECT rev FROM store"); const refusedInsert = await ubuntu.refused( `INSERT INTO project (id, name, status, created_at, updated_at, rev) VALUES ('stray', 'Stray', 'active', 1, 1, 0);`, ); - const untouched = await ubuntu.sql(`SELECT title FROM thread WHERE id = '${created.id}'`); + const untouched = await ubuntu.sql(`SELECT title FROM thread WHERE id = '${staleId}'`); measure("case 10", { head, items: rows.length, revs: new Set(revs).size, store: store!.rev }); expect(increasing).toBe(true); expect(revs.every((rev) => rev > head)).toBe(true); @@ -973,7 +977,7 @@ describeMachines("sync across OrbStack machines", () => { expect(appThread).toEqual({ thinking_level: "high" }); expect(refused).toContain("rev is not the current revision"); expect(refusedInsert).toContain("rev is not the current revision"); - expect(untouched[0]!.title).toBe(atHead === undefined ? "At the head, untaken" : "Revisions"); + expect(untouched[0]!.title).toBe(atHead === undefined ? "At the head, untaken" : stale!.title); expect(headAfter!.rev).toBe(store!.rev); await snapshot( diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 2691239d..3f54d5da 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -19,6 +19,13 @@ export default defineConfig({ }, ], test: { - include: ["test/**/*.test.ts"], + projects: [ + { + extends: true, + test: { name: "server", include: ["test/**/*.test.ts"], exclude: ["test/**/*.live.test.ts"] }, + }, + // The live suites share the OrbStack machines, and each start stops the server another one runs. + { extends: true, test: { name: "live", include: ["test/**/*.live.test.ts"], fileParallelism: false } }, + ], }, });