Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ jobs:
args: --win --x64
env:
CODEWORK_RELEASE_ID: ${{ needs.guard.outputs.id }}
# Built into the app, which signs everyone in; the web build stops without it. Public, so a variable.
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
# Windows runners default to PowerShell, which reads "$CHANNEL" as its own variable.
defaults:
run:
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ The most common defect is a change that works on the path you tested and is miss
[00_development.md](docs/operations/00_development.md) walks through setup, the dev home and each dev server. A few things matter most when an agent runs them:

- **Dev home:** Export `CODEWORK_HOME_DIR="$PWD/.scratch/home"` in every shell you start a process from. Please keep dev processes away from `~/.codework`: it's the user's real install, and it may be the CodeWork running you right now.
- **Start order:** Start the RPC server first (`vp run dev:cli serve --port 0`), then the desktop app and its server (`vp run dev:desktop`), both with the same home. The app finds the server through `<home>/service.json`. Nothing reloads the RPC server, so restart it after harness or codework changes.
- **Start order:** Start Relay first (`infra/relay`, see its README), then the RPC server (`vp run dev:cli serve --port 0`), then the desktop app and its server (`vp run dev:desktop`), the last two with the same home and `CODEWORK_RELAY_URL=http://127.0.0.1:8787`. The app signs everyone in and needs a Relay it can reach. The app finds the server through `<home>/service.json`. Nothing reloads the RPC server, so restart it after harness or codework changes.
- **Desktop app:** Leave the Install and Start buttons alone in the dev app. Install writes the released binary to `~/.codework/bin`, and Start runs the installed `codework` (the one in `~/.codework/bin`, else your login shell's) against the dev home.
- **Process lifecycle:** Start dev servers from your own shell so they stop when your session does, and don't detach them with `nohup`, `setsid` or `tmux` unless asked. When you clean up, stop only the PIDs you started, never by name or pattern.
- **Test data:** An empty home is the easy default. If the flow needs existing sessions, copy the real database in with `sqlite3 ... .backup`, and only while no run is active: the dev server resumes open runs, and they would act on the real project files.
Expand Down
158 changes: 158 additions & 0 deletions apps/server/test/__artifacts__/launch.settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
{
"before": {
"cli": null,
"home": {
"path": "<default home>",
"custom": false,
"fallback": "<default home>"
},
"args": "",
"env": [],
"server": {
"_tag": "Stopped"
}
},
"saved": {
"cli": {
"path": "<bin>/codework",
"custom": true,
"version": "<version>"
},
"home": {
"path": "<custom home>",
"custom": true,
"fallback": "<default home>"
},
"args": "--port <port 1>",
"env": [
{
"name": "PLAIN_SETTING",
"sensitive": false,
"value": "plain value"
},
{
"name": "SECRET_KEY",
"sensitive": true
}
],
"server": {
"_tag": "Stopped"
}
},
"afterStart": {
"cli": {
"path": "<bin>/codework",
"custom": true,
"version": "<version>"
},
"home": {
"path": "<custom home>",
"custom": true,
"fallback": "<default home>"
},
"args": "--port <port 1>",
"env": [
{
"name": "PLAIN_SETTING",
"sensitive": false,
"value": "plain value"
},
{
"name": "SECRET_KEY",
"sensitive": true
}
],
"server": {
"_tag": "Running",
"url": "ws://127.0.0.1:<port 1>/rpc/v1"
}
},
"callsAfterStart": [
"args: service start --port <port 1>",
" PLAIN_SETTING=plain value",
" SECRET_KEY=s3cret",
" CODEWORK_HOME_DIR=<custom home>"
],
"afterRestart": {
"cli": {
"path": "<bin>/codework",
"custom": true,
"version": "<version>"
},
"home": {
"path": "<custom home>",
"custom": true,
"fallback": "<default home>"
},
"args": "--port <port 2>",
"env": [
{
"name": "PLAIN_SETTING",
"sensitive": false,
"value": "changed"
},
{
"name": "SECRET_KEY",
"sensitive": true
}
],
"server": {
"_tag": "Running",
"url": "ws://127.0.0.1:<port 2>/rpc/v1"
}
},
"afterStop": {
"cli": {
"path": "<bin>/codework",
"custom": true,
"version": "<version>"
},
"home": {
"path": "<custom home>",
"custom": true,
"fallback": "<default home>"
},
"args": "--port <port 2>",
"env": [
{
"name": "PLAIN_SETTING",
"sensitive": false,
"value": "changed"
},
{
"name": "SECRET_KEY",
"sensitive": true
}
],
"server": {
"_tag": "Stopped"
}
},
"calls": [
"args: service start --port <port 1>",
" PLAIN_SETTING=plain value",
" SECRET_KEY=s3cret",
" CODEWORK_HOME_DIR=<custom home>",
"args: service restart --port <port 2>",
" PLAIN_SETTING=changed",
" SECRET_KEY=s3cret",
" CODEWORK_HOME_DIR=<custom home>",
"args: service stop",
" PLAIN_SETTING=changed",
" SECRET_KEY=s3cret",
" CODEWORK_HOME_DIR=<custom home>"
],
"reset": {
"cli": null,
"home": {
"path": "<default home>",
"custom": false,
"fallback": "<default home>"
},
"args": "",
"env": [],
"server": {
"_tag": "Stopped"
}
}
}
6 changes: 3 additions & 3 deletions apps/server/test/fixtures/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,10 @@ export const stable = (status: ServerStatus | undefined) => {
const appClient = RpcClient.make(Contract.Api);
export type AppRpc = Effect.Success<typeof appClient>;

/** The app server with its database in `home`; its own CLI home names no CodeWork server. */
export const app = async (home: string) => {
/** The app server with its database in `home`; its own CLI home names no CodeWork server. `env` is added to its own. */
export const app = async (home: string, env: Record<string, string> = {}) => {
const proc = spawn(process.execPath, [appEntry], {
env: { ...process.env, CODEWORK_DATABASE: join(home, "app.db"), CODEWORK_HOME_DIR: join(home, "cli") },
env: { ...process.env, CODEWORK_DATABASE: join(home, "app.db"), CODEWORK_HOME_DIR: join(home, "cli"), ...env },
stdio: ["ignore", "pipe", "inherit"],
});
processes.add(proc);
Expand Down
179 changes: 179 additions & 0 deletions apps/server/test/launch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
/* @effect-diagnostics nodeBuiltinImport:off -- the suite starts real CodeWork servers from temp homes. */
import { Effect, Option, Stream } from "effect";
import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, it } from "vite-plus/test";
import {
type CliAction,
type CliEnvVar,
Contract,
type LocalServerStatus,
type ServerUpdate,
} from "@codeworksh/contract";
import {
type AppRpc,
app,
cleanup,
freePort,
normalizer,
snapshot as match,
tempDir,
waitFor,
} from "./fixtures/apps.ts";

const cli = fileURLToPath(new URL("../../../packages/codework/src/index.ts", import.meta.url));
const models = fileURLToPath(new URL("../../../models.gen.json", import.meta.url));

// The servers a case started run detached, outliving the CLI that started them; each is stopped by its pid.
const started = new Set<string>();
afterEach(async () => {
for (const home of started) {
const file = join(home, "service.json");
if (!existsSync(file)) continue;
const { pid } = JSON.parse(readFileSync(file, "utf8")) as { pid: number };
try {
process.kill(pid, "SIGKILL");
} catch {
// Already gone.
}
}
started.clear();
await cleanup();
});

const snapshot = (name: string, artifact: unknown) => match(`launch.${name}`, artifact);

/**
* A `codework` that notes each `service` call, its arguments and the environment it was given, then
* runs the CLI from source. The app runs it as a custom executable, the way the Setup page sets one.
*/
const wrapper = (dir: string) => {
const log = join(dir, "calls.log");
const file = join(dir, "codework");
writeFileSync(
file,
[
"#!/bin/sh",
'if [ "$1" = service ]; then',
` { printf 'args:'; printf ' %s' "$@"; printf '\\n'; printf ' PLAIN_SETTING=%s\\n SECRET_KEY=%s\\n CODEWORK_HOME_DIR=%s\\n' "$PLAIN_SETTING" "$SECRET_KEY" "$CODEWORK_HOME_DIR"; } >> '${log}'`,
"fi",
`exec '${process.execPath}' --conditions=development '${cli}' "$@"`,
"",
].join("\n"),
);
chmodSync(file, 0o755);
return { file, calls: () => (existsSync(log) ? readFileSync(log, "utf8").trimEnd().split("\n") : []) };
};

const localOf = (rpc: AppRpc) =>
Effect.gen(function* () {
yield* rpc["servers.check"](undefined);
const statuses = yield* rpc["servers.watch"](undefined).pipe(Stream.runHead, Effect.map(Option.getOrThrow));
return statuses.find((status): status is LocalServerStatus => status.id === Contract.LOCAL_SERVER)!;
});

/** What the Setup page reads from a local server: its runtime settings and whether it runs where they say. */
const shown = (status: LocalServerStatus) => ({
cli: status.cli !== null && "version" in status.cli ? { ...status.cli, version: "<version>" } : status.cli,
home: status.home,
args: status.args,
env: status.env,
server: status.server._tag === "Running" ? { _tag: "Running", url: status.server.url } : status.server,
});

it(
"starts, restarts and stops a server with a custom executable, home, arguments and variables",
{ timeout: 180_000 },
async () => {
const appHome = tempDir("launch-app");
const osHome = tempDir("launch-os");
const bin = tempDir("launch-bin");
const home = tempDir("launch-home");
started.add(home);
started.add(join(appHome, "cli"));
const codework = wrapper(bin);
const [first, second] = [await freePort(), await freePort()];
const desk = await app(appHome, {
// Nothing of the developer's: no install folder, no login shell PATH, no OS home.
HOME: osHome,
SHELL: "/usr/bin/false",
CODEWORK_INSTALL_DIR: join(osHome, "bin"),
CODEWORK_MODELS_FILE: models,
});
// Each folder keeps a label of its own, so the artifact shows which home the server ran in.
const label = normalizer(
[],
[
[join(appHome, "cli"), "<default home>"],
[bin, "<bin>"],
[home, "<custom home>"],
[`:${first}`, ":<port 1>"],
[`:${second}`, ":<port 2>"],
[`--port ${first}`, "--port <port 1>"],
[`--port ${second}`, "--port <port 2>"],
],
);
const update = (patch: Omit<ServerUpdate, "id">) =>
desk.run((rpc) => rpc["servers.update"]({ id: Contract.LOCAL_SERVER, ...patch }));
const act = (action: CliAction) =>
desk.run((rpc) => rpc["servers.service"]({ id: Contract.LOCAL_SERVER, action }));
const status = () => desk.run(localOf);
const running = (port: number) =>
waitFor(
async () => {
const now = await status();
return now.server._tag === "Running" && now.server.url.includes(`:${port}`) ? now : undefined;
},
`the server on port ${port}`,
60_000,
);

const before = await status();

const env: Array<CliEnvVar> = [
{ name: "PLAIN_SETTING", value: "plain value", sensitive: false },
{ name: "SECRET_KEY", value: "s3cret", sensitive: true },
];
await update({ executable: codework.file, home, args: `--port ${first}`, env });
const saved = await status();

await act("start");
const afterStart = await running(first);
const callsAfterStart = codework.calls();

// The secret is sent back without its value, as the Setup page sends a kept one: it stays saved.
await update({
args: `--port ${second}`,
env: [
{ name: "PLAIN_SETTING", value: "changed", sensitive: false },
{ name: "SECRET_KEY", sensitive: true },
],
});
await act("restart");
const afterRestart = await running(second);

await act("stop");
const afterStop = await waitFor(async () => {
const now = await status();
return now.server._tag === "Stopped" ? now : undefined;
}, "the server to stop");

await update({ executable: null, home: null, args: "", env: [] });
const reset = await status();

await snapshot(
"settings",
label({
before: shown(before),
saved: shown(saved),
afterStart: shown(afterStart),
callsAfterStart,
afterRestart: shown(afterRestart),
afterStop: shown(afterStop),
calls: codework.calls(),
reset: shown(reset),
}),
);
},
);
Loading