Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions apps/server/test/sync.machines.live.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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(
Expand Down
9 changes: 8 additions & 1 deletion apps/server/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } },
],
},
});
6 changes: 3 additions & 3 deletions packages/codework/src/cli/cmd/handlers/mcp/control.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -25,11 +24,12 @@ const control = (operation: "connect" | "disconnect") =>
readonly thread: Option.Option<string>;
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,
});
Expand Down
5 changes: 3 additions & 2 deletions packages/codework/src/cli/cmd/handlers/plugin/session.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -19,7 +20,7 @@ export const linkedDirectory = Effect.fn("CLI.plugin.linkedDirectory")(function*
home: Option.Option<string>,
) {
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;
Expand Down
32 changes: 17 additions & 15 deletions packages/codework/src/cli/cmd/handlers/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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" });
}
Expand Down Expand Up @@ -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(
Expand All @@ -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,
});
Expand Down
5 changes: 3 additions & 2 deletions packages/codework/src/cli/cmd/handlers/session/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions packages/codework/src/cli/cmd/handlers/session/relink.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
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";
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 }),
Expand Down
6 changes: 3 additions & 3 deletions packages/codework/src/cli/cmd/handlers/thread/fork.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
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";
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) });

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)
Expand All @@ -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,
});
Expand Down
5 changes: 3 additions & 2 deletions packages/codework/src/cli/cmd/handlers/thread/list.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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) => [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>) {
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;
});
Loading