From 42b8fdfe6a8c74fddea738459a4ef0b68ec85289 Mon Sep 17 00:00:00 2001 From: Ashot Petrosian Date: Fri, 4 Dec 2026 16:47:46 -0500 Subject: [PATCH 001/108] feat(web): codecast cross-platform builds --- .codecast/ci.toml | 35 + .../__fixtures__/install-golden/stub/check.md | 2 +- packages/cli/src/browser/cloudHost.test.ts | 20 +- packages/cli/src/browser/sharedHost.test.ts | 2 +- packages/cli/src/ciPoolHost.test.ts | 248 ++++++++ packages/cli/src/ciRun/command.ts | 365 +++++++++++ packages/cli/src/ciRun/executor.ts | 511 +++++++++++++++ packages/cli/src/hostWorkTicks.ts | 29 + packages/cli/src/momentsHost.test.ts | 34 +- packages/cli/src/momentsHost.ts | 19 +- packages/cli/src/test-helpers/loopHold.ts | 8 + packages/convex/convex/_generated/api.d.ts | 100 +++ packages/convex/convex/accountPool.test.ts | 15 + .../convex/changeApprovals.landing.test.ts | 212 +++++++ .../convex/convex/changeApprovals.test.ts | 18 +- packages/convex/convex/changeApprovals.ts | 399 +++++------- packages/convex/convex/ciPool.test.ts | 244 +++++++ packages/convex/convex/http.ts | 9 +- packages/convex/convex/judgeReview.test.ts | 3 +- .../convex/convex/lib/changeApprovalReads.ts | 219 +++++++ .../lib/changeApprovalRecordValidator.ts | 31 + packages/convex/convex/lib/ciRoutes.ts | 14 + packages/convex/convex/lib/secretAskFirst.ts | 89 +++ packages/convex/convex/secrets.ts | 124 ++-- packages/electron/installedApps/e2e/run.mjs | 34 +- packages/electron/package.json | 2 +- packages/mobile/app/decisions/[id].tsx | 6 + packages/shared/blame/index.ts | 12 + packages/shared/blame/sessionTrailer.test.ts | 11 +- packages/shared/contracts/ciWorkflow.test.ts | 139 ++++ packages/shared/contracts/ciWorkflow.ts | 600 ++++++++++++++++++ packages/shared/contracts/codeProtocol.ts | 5 + packages/shared/contracts/shortcutCatalog.ts | 5 + packages/shared/contracts/snippets.ts | 35 +- .../blog/agents-in-your-own-chrome/page.tsx | 234 ------- .../blog/claude-code-cursor-codex/page.tsx | 237 ------- .../blog/claude-code-from-your-phone/page.tsx | 289 --------- .../claude-code-history-on-day-one/page.tsx | 189 ------ .../blog/claude-code-sessions/page.tsx | 217 ------- .../blog/codecast-in-the-cloud/page.tsx | 476 -------------- .../blog/fewer-bigger-jumps/page.tsx | 210 ------ .../one-repository-twenty-checkouts/page.tsx | 204 ------ .../blog/the-chart-in-the-reply/page.tsx | 229 ------- .../page.tsx | 232 ------- .../the-task-your-agent-reports-to/page.tsx | 193 ------ .../page.tsx | 271 -------- .../blog/undo-with-a-history/page.tsx | 226 ------- .../documentation/guides/content/decisions.md | 12 +- .../app/commit/[owner]/[repo]/[sha]/page.tsx | 11 +- packages/web/app/tasks/[id]/page.tsx | 7 +- packages/web/components/InlineDiff.tsx | 8 +- .../web/components/OpenInEditorButton.tsx | 5 +- packages/web/components/PaletteRows.tsx | 3 +- packages/web/components/PlanDetailPanel.tsx | 11 +- .../__tests__/collabComposerPresence.test.tsx | 19 +- .../__tests__/phoneCallStrip.mount.test.tsx | 5 +- packages/web/components/code/CodeEditor.tsx | 14 +- packages/web/components/code/CodeFileBar.tsx | 130 +++- packages/web/components/code/CodeFileView.tsx | 201 ++++-- .../vaultFileViewRead.mount.test.tsx | 72 ++- .../web/components/code/agent/AgentLayer.tsx | 76 ++- .../components/code/agent/SessionPicker.tsx | 99 +-- .../__tests__/SessionPicker.mount.test.tsx | 31 +- .../components/code/blame/BlameHoverCard.tsx | 17 +- .../code/workspace/CodeWorkspace.tsx | 438 +++++++++---- .../components/code/workspace/EditorGroup.tsx | 93 ++- .../web/components/code/workspace/TabBar.tsx | 173 ++++- .../components/code/workspace/TabSwitcher.tsx | 33 +- .../conversation/blocks/toolBlocks.tsx | 25 +- packages/web/components/pr/PRThread.tsx | 4 + packages/web/components/repo/BlobContent.tsx | 23 +- .../components/repo/RepoCompareContent.tsx | 6 +- .../web/components/sidebar/navPrimitives.tsx | 5 +- .../web/components/stage/StageSplitView.tsx | 7 +- .../web/components/tasks/TaskInlineThread.tsx | 7 +- .../terminal/ConversationTerminal.tsx | 1 + .../web/components/vault/VaultFileView.tsx | 99 ++- .../web/components/vault/VaultScopeLine.tsx | 2 +- .../web/components/vault/useVaultSidePanel.ts | 9 +- packages/web/hooks/useJumpToDecisionAsk.ts | 3 + packages/web/hooks/useSessionLineMessage.ts | 92 +++ .../lib/__tests__/decisionQueueKeys.test.ts | 8 +- .../__tests__/editorPaletteCommands.test.ts | 9 +- packages/web/lib/__tests__/filesPane.test.ts | 28 + .../web/lib/__tests__/inboxRouting.test.ts | 23 +- packages/web/lib/__tests__/stage.test.ts | 23 +- .../standaloneBootGraph.guard.test.ts | 57 +- packages/web/lib/calls/callManager.ts | 75 +-- packages/web/lib/calls/remoteAudio.ts | 225 +++++++ packages/web/lib/castDiff.ts | 14 + .../web/lib/code/__tests__/buffers.test.ts | 25 + .../web/lib/code/__tests__/fileSync.test.ts | 152 ++++- packages/web/lib/code/__tests__/merge.test.ts | 12 +- .../web/lib/code/__tests__/statusBar.test.ts | 22 +- .../__tests__/statusBarVault.mount.test.ts | 44 ++ packages/web/lib/code/__tests__/theme.test.ts | 24 +- .../agent/__tests__/editorMarks.mount.test.ts | 65 +- .../agent/__tests__/feature.mount.test.ts | 71 ++- .../lib/code/agent/__tests__/sessions.test.ts | 48 +- packages/web/lib/code/agent/agentStore.ts | 31 + packages/web/lib/code/agent/editorMarks.ts | 161 ++++- packages/web/lib/code/agent/feature.ts | 144 ++++- packages/web/lib/code/agent/live.ts | 4 +- packages/web/lib/code/agent/sessions.ts | 67 +- .../lib/code/blame/__tests__/actions.test.ts | 33 +- .../blame/__tests__/feature.mount.test.ts | 53 +- .../lib/code/blame/__tests__/model.test.ts | 13 +- packages/web/lib/code/blame/actions.ts | 17 +- packages/web/lib/code/blame/gutter.ts | 58 +- packages/web/lib/code/blame/index.ts | 13 +- packages/web/lib/code/blame/model.ts | 25 +- packages/web/lib/code/buffers.ts | 33 +- packages/web/lib/code/commands.ts | 39 +- packages/web/lib/code/editorHost.ts | 24 +- packages/web/lib/code/features.ts | 8 + packages/web/lib/code/fileSync.ts | 189 ++++-- .../code/git/__tests__/feature.mount.test.ts | 42 +- .../code/git/__tests__/gutter.mount.test.ts | 47 ++ packages/web/lib/code/git/gitTheme.ts | 16 +- packages/web/lib/code/git/gutter.ts | 95 ++- packages/web/lib/code/git/index.ts | 78 ++- packages/web/lib/code/git/split.ts | 25 +- packages/web/lib/code/git/status.ts | 18 +- packages/web/lib/code/gutterSlots.ts | 19 +- packages/web/lib/code/idle.ts | 18 + packages/web/lib/code/languages.ts | 13 +- .../web/lib/code/lsp/__tests__/lsp.test.ts | 2 +- packages/web/lib/code/lsp/feature.ts | 32 +- packages/web/lib/code/lsp/host.ts | 12 +- packages/web/lib/code/lsp/navigation.ts | 141 ++-- packages/web/lib/code/lsp/register.ts | 22 +- packages/web/lib/code/lsp/symbols.ts | 73 ++- packages/web/lib/code/lsp/ui/list.ts | 10 + packages/web/lib/code/lsp/ui/peek.ts | 10 +- packages/web/lib/code/lsp/ui/quickPick.ts | 28 +- packages/web/lib/code/lsp/ui/status.ts | 20 +- packages/web/lib/code/lsp/ui/theme.ts | 12 +- packages/web/lib/code/merge.ts | 120 +++- .../code/search/__tests__/controller.test.ts | 14 + packages/web/lib/code/search/controller.ts | 13 +- packages/web/lib/code/search/multibuffer.ts | 9 +- packages/web/lib/code/setup.ts | 21 +- packages/web/lib/code/statusBar.ts | 152 ++++- packages/web/lib/code/theme.ts | 317 ++++++--- .../web/lib/code/vim/__tests__/engine.test.ts | 162 +++++ packages/web/lib/code/vim/apply.ts | 4 + packages/web/lib/code/vim/exAdapters.ts | 138 ++-- packages/web/lib/code/vim/index.ts | 35 +- packages/web/lib/code/vim/keyLayer.ts | 17 +- packages/web/lib/code/vim/mode.ts | 14 +- packages/web/lib/code/vim/options.ts | 4 +- packages/web/lib/code/vim/plugins.ts | 43 +- packages/web/lib/code/vim/theme.ts | 24 +- packages/web/lib/code/vim/translate.ts | 58 +- packages/web/lib/code/vim/types.ts | 2 +- packages/web/lib/code/vimFeature.ts | 38 +- packages/web/lib/code/workspace/controller.ts | 10 +- .../web/lib/code/workspace/editorWorkspace.ts | 37 +- .../lib/code/workspace/followFiles.test.ts | 80 ++- .../web/lib/code/workspace/followFiles.ts | 136 +++- .../web/lib/code/workspace/groupRegistry.ts | 9 + packages/web/lib/code/workspace/model.test.ts | 116 +++- packages/web/lib/code/workspace/model.ts | 380 ++++++++++- .../web/lib/code/workspace/navHistory.test.ts | 22 +- packages/web/lib/code/workspace/navHistory.ts | 24 +- packages/web/lib/code/workspace/persist.ts | 2 +- .../web/lib/code/workspace/quickOpen.test.ts | 70 +- packages/web/lib/code/workspace/quickOpen.ts | 197 +++++- packages/web/lib/code/workspace/symbolPath.ts | 92 +-- packages/web/lib/decisionOpenRegistry.ts | 28 + packages/web/lib/editorPaletteCommands.ts | 107 +++- packages/web/lib/filePathLinks.ts | 21 +- packages/web/lib/filesPane.ts | 109 ++-- packages/web/lib/stage.ts | 36 +- packages/web/lib/terminal/endpoint.ts | 34 +- packages/web/lib/terminal/termRegistry.ts | 3 + packages/web/lib/terminal/termSessions.ts | 42 ++ packages/web/lib/vault/client.ts | 41 +- .../web/lib/vault/hosts/VaultMachineBar.tsx | 27 +- packages/web/lib/vault/vaultHref.ts | 9 + packages/web/perf/README.md | 52 ++ packages/web/plugins/contentOnlyHmr.test.ts | 112 +++- packages/web/plugins/contentOnlyHmr.ts | 109 ++-- packages/web/plugins/tailwindWorker.test.ts | 23 +- packages/web/plugins/tailwindWorker.ts | 49 +- packages/web/scripts/perf-budgets.sh | 3 + packages/web/shortcuts/keyOwnership.ts | 1 + .../web/store/__tests__/inboxStore.test.ts | 10 +- .../web/store/__tests__/restState.test.ts | 3 +- .../web/store/__tests__/sim/windowSlots.ts | 5 + packages/web/store/clientSyncRegistry.ts | 38 +- packages/web/store/codeStore.ts | 14 +- packages/web/store/criticalUiPrefs.ts | 44 ++ packages/web/store/vaultStore.ts | 262 ++++---- packages/web/store/vaultTypes.ts | 24 +- scripts/ci/local.ts | 45 +- 196 files changed, 9533 insertions(+), 5195 deletions(-) create mode 100644 .codecast/ci.toml create mode 100644 packages/cli/src/ciPoolHost.test.ts create mode 100644 packages/cli/src/ciRun/command.ts create mode 100644 packages/cli/src/ciRun/executor.ts create mode 100644 packages/cli/src/hostWorkTicks.ts create mode 100644 packages/convex/convex/changeApprovals.landing.test.ts create mode 100644 packages/convex/convex/ciPool.test.ts create mode 100644 packages/convex/convex/lib/changeApprovalReads.ts create mode 100644 packages/convex/convex/lib/changeApprovalRecordValidator.ts create mode 100644 packages/convex/convex/lib/ciRoutes.ts create mode 100644 packages/convex/convex/lib/secretAskFirst.ts create mode 100644 packages/shared/contracts/ciWorkflow.test.ts create mode 100644 packages/shared/contracts/ciWorkflow.ts delete mode 100644 packages/web/app/(marketing)/blog/agents-in-your-own-chrome/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-cursor-codex/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-from-your-phone/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-history-on-day-one/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-sessions/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/codecast-in-the-cloud/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/fewer-bigger-jumps/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/one-repository-twenty-checkouts/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-chart-in-the-reply/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-questions-your-agents-save-for-you/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-task-your-agent-reports-to/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-tree-at-the-end-of-every-turn/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/undo-with-a-history/page.tsx create mode 100644 packages/web/hooks/useSessionLineMessage.ts create mode 100644 packages/web/lib/calls/remoteAudio.ts create mode 100644 packages/web/store/criticalUiPrefs.ts diff --git a/.codecast/ci.toml b/.codecast/ci.toml new file mode 100644 index 0000000000..ea32cbf754 --- /dev/null +++ b/.codecast/ci.toml @@ -0,0 +1,35 @@ +# codecast's own CI runner (`cast ci run `): what .github/workflows/ci.yml cannot say. The jobs, their steps, +# matrices and `if:` gates come from ci.yml itself, read for the push or pull_request event the run stands in for; +# this file adds only the host-side facts. Schema: packages/shared/contracts/ciConfig.ts. + +repository = "codecast-sh/codecast" +name = "codecast-ci" +# A CI pool host (c8id.16xlarge, 64 vCPU / 128 GB) takes one run at a time; within it, job runners go sixteen at +# once, four cores each, each in a checkout of its own, as GitHub gives each job a runner of its own. +runs_per_host = 1 +parallel_jobs = 16 + +# The pool has no job cap, so ci.yml's matrices run their wide set on a push too (ci.yml, typecheck's note). +[vars] +CI_WIDE = "true" + +# Runner setup that needs root on GitHub's image: the pool's host image carries these tools already, and a slot user +# has no sudo. +[skip_steps] +"Install tmux" = "the CI host image has tmux" +"Install tmux (e2e tests need a real tmux server)" = "the CI host image has tmux" +"Allow the Electron sandbox, and a display for it" = "the CI host image has xvfb and allows unprivileged user namespaces" + +# ci.yml needs no secrets and no services. Every job counts as ci.yml says: computer-macos is continue-on-error +# (advisory), and verify is the one check GitHub requires; it runs after every gated job and fails when any of them +# did not end as its gate said. + +# Each test shard's JUnit report, beside its log: `scripts/ci/test-shards.ts --record` balances the shards from them. +[jobs.test-cli] +keep = ["$RUNNER_TEMP/junit.xml"] + +[jobs.test-web] +keep = ["$RUNNER_TEMP/junit.xml"] + +[jobs.test-convex] +keep = ["$RUNNER_TEMP/junit.xml"] diff --git a/packages/cli/src/__fixtures__/install-golden/stub/check.md b/packages/cli/src/__fixtures__/install-golden/stub/check.md index e8e9b066f0..8de02304ee 100644 --- a/packages/cli/src/__fixtures__/install-golden/stub/check.md +++ b/packages/cli/src/__fixtures__/install-golden/stub/check.md @@ -9,6 +9,6 @@ cast check web # one project by name, or any directory or tsconfig path cast check --fresh # restart a watcher that lost track, then ask ``` -If a pass is running or queued, wait on it rather than run your own `tsc`. A worktree holds a program of its own (gigabytes per project), so give worktrees only to the agents whose edits would collide. When a check is red with errors nobody wrote, suspect the `.codecast/check.toml` entry before the code. `cast guide check` covers that file. +If a pass is running or queued, wait on it rather than run your own `tsc`. A worktree holds a program of its own (gigabytes per project), so give worktrees only to the agents whose edits would collide, and make each with `cast ws acquire `, which puts it under `.codecast/worktrees/` with its env files, ports and install and removes it with `cast ws destroy `; never a raw `git worktree add` at a path of your own. When a check is red with errors nobody wrote, suspect the `.codecast/check.toml` entry before the code. `cast guide check` covers that file. diff --git a/packages/cli/src/browser/cloudHost.test.ts b/packages/cli/src/browser/cloudHost.test.ts index b170098994..a790ccc87a 100644 --- a/packages/cli/src/browser/cloudHost.test.ts +++ b/packages/cli/src/browser/cloudHost.test.ts @@ -4,7 +4,7 @@ import { promisify } from "node:util"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -import { instanceNameTag, NEW_HOST_LOGINS, patchHost, readHosts, registryLockPath, resolveCloudHost, toRemoteHost, upsertHost, writeHosts, type CloudHost } from "./cloudHost"; +import { credentialPushHosts, instanceNameTag, NEW_HOST_LOGINS, reachableRemoteHosts, patchHost, readHosts, registryLockPath, resolveCloudHost, toRemoteHost, upsertHost, writeHosts, type CloudHost } from "./cloudHost"; let dir: string, prev: string | undefined; const base: CloudHost = { id: "i-1", provider: "aws", region: "us-west-2", user: "ubuntu", keyPath: "/k", address: "1.1.1.1", forwardAgent: true, idleStopMinutes: 20 }; @@ -147,3 +147,21 @@ describe("resolveCloudHost — the default skips a host reserved for one job", ( expect(() => resolveCloudHost()).toThrow("every registered cloud host is reserved for one job (i-1: Acme line, i-2: evals)"); }); }); + +describe("credential pushes skip CI machines", () => { + const h = (id: string, address: string, reservedFor?: string): CloudHost => + ({ id, provider: "aws", region: "us-west-2", user: "ubuntu", keyPath: "/k", address, platform: "linux", ...(reservedFor ? { reservedFor } : {}) }); + const hosts = [h("i-dev", "10.0.0.1"), h("i-ci", "10.0.0.2", "ci: codecast-sh/codecast pool"), h("i-evals", "10.0.0.3", "evals")]; + + test("only a ci: reservation is left out", () => { + expect(credentialPushHosts(hosts).map((x) => x.id)).toEqual(["i-dev", "i-evals"]); + }); + + test("the reachable set a push walks never reaches a CI host", async () => { + const probed: string[] = []; + const reach = async (r: { address: string }) => { probed.push(r.address); return true; }; + const out = await reachableRemoteHosts([], reach, credentialPushHosts(hosts)); + expect(out.map((r) => r.address).sort()).toEqual(["10.0.0.1", "10.0.0.3"]); + expect(probed).not.toContain("10.0.0.2"); + }); +}); diff --git a/packages/cli/src/browser/sharedHost.test.ts b/packages/cli/src/browser/sharedHost.test.ts index 3016af85fb..e413d0befd 100644 --- a/packages/cli/src/browser/sharedHost.test.ts +++ b/packages/cli/src/browser/sharedHost.test.ts @@ -148,7 +148,7 @@ describe("binaries outside private homes", () => { test("a member runs the box's own cast bundle when it has one, on their own bun", () => { const s = addUserSelfScript({}); expect(s).toContain("if [ -f /usr/local/lib/codecast/index.js ]"); - expect(s).toContain('exec "$HOME/.bun/bin/bun" /usr/local/lib/codecast/index.js "$@"'); + expect(s).toContain('exec "$HOME/.bun/bin/bun" --no-env-file /usr/local/lib/codecast/index.js "$@"'); }); test("a new user's installs run with their own PATH, so a tool linked for the owner is never taken as theirs", () => { diff --git a/packages/cli/src/ciPoolHost.test.ts b/packages/cli/src/ciPoolHost.test.ts new file mode 100644 index 0000000000..a41470d10f --- /dev/null +++ b/packages/cli/src/ciPoolHost.test.ts @@ -0,0 +1,248 @@ +// The CI pool's daemon tick against a real bare mirror whose origin moves: it queues each first-parent commit main +// gained, claims queued shas only into free slots, starts `cast ci run --lease`, and frees a slot when its run's +// process is gone. The lease rules themselves (one winner, takeover after 2 minutes) are ciLeases.test.ts's. +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { castArgv, readPoolMarker, tickCiPool, type PoolMarker } from "./ciPoolHost.js"; +import { sh } from "./ciRun/executor.js"; +import { markAvoid, type HostReadings } from "./ciRun/host.js"; + +const tmp = mkdtempSync(path.join(os.tmpdir(), "castci-pool-")); +const HOME = process.env.HOME; +beforeAll(() => { process.env.HOME = path.join(tmp, "home"); mkdirSync(process.env.HOME, { recursive: true }); }); +afterAll(() => { process.env.HOME = HOME; rmSync(tmp, { recursive: true, force: true }); }); + +const g = (dir: string, ...a: string[]) => { + const r = sh("git", ["-C", dir, "-c", "user.name=t", "-c", "user.email=t@t", ...a]); + if (r.code !== 0) throw new Error(r.err); + return r.out; +}; + +function world() { + const origin = path.join(tmp, "origin"); + mkdirSync(origin, { recursive: true }); + g(origin, "init", "-q", "-b", "main"); + const commit = (m: string) => { writeFileSync(path.join(origin, `${m}.txt`), m); g(origin, "add", "."); g(origin, "commit", "-qm", m); return g(origin, "rev-parse", "HEAD"); }; + const c1 = commit("one"); + const mirror = path.join(tmp, "mirror.git"); + sh("git", ["clone", "-q", "--bare", origin, mirror]); + return { origin, mirror, commit, c1 }; +} + +/** A lease server's routes as the tick calls them, holding what a test needs to see. */ +function fakeServer() { + const queue: Array<{ sha: string; before?: string }> = []; + const claimed: string[] = []; + const calls: string[] = []; + const post = async (route: string, body: any) => { + calls.push(route); + if (route.endsWith("/enqueue")) { for (const c of body.commits) if (!queue.some((q) => q.sha === c.sha)) queue.push(c); return { added: body.commits.length }; } + if (route.endsWith("/pending")) return { leases: queue.filter((q) => !claimed.includes(q.sha)).map((q) => ({ ...q, event: "push", before: q.before ?? null })) }; + if (route.endsWith("/claim")) { claimed.push(body.sha); return { claimed: true }; } + if (route.endsWith("/register-pool")) { calls.push(`register ${body.repository} ${body.lanes.join(",")}`); return { registered: true }; } + throw new Error(`unexpected ${route}`); + }; + return { queue, claimed, calls, post }; +} + +describe("the CI pool's daemon tick", () => { + test("queues what main gained, oldest first, and claims into free slots only", async () => { + const w = world(); + const marker: PoolMarker = { role: "ci", pool: "p", repo: "o/r", host: "codecast-ci-1", slots: 1, mirror: w.mirror, lanes: ["linux"] }; + const server = fakeServer(); + const started: string[][] = []; + // A run's process that is still alive: this test's own pid. + const spawnRun = (argv: string[]) => { started.push(argv); return process.pid; }; + await tickCiPool({ marker, post: server.post, log: () => {}, spawnRun }); + expect(server.queue.map((q) => q.sha)).toEqual([w.c1]); + expect(server.calls).toContain("register o/r linux"); + expect(started).toHaveLength(1); + const argv = started[0]!; + expect(argv.slice(argv.indexOf("ci"), argv.indexOf("--lease"))).toEqual(["ci", "run", w.c1]); + expect(argv.slice(argv.indexOf("--os"))).toEqual(["--os", "linux", "--repository", "o/r"]); + expect(started[0]).toContain("--repository"); + expect(started[0]![started[0]!.indexOf("--lease") + 1]).toMatch(new RegExp(`^${w.c1.slice(0, 12)}-[0-9a-z]+$`)); + + // Two pushes land; the one slot is busy, so they are queued and none is claimed. + const c2 = w.commit("two"); + const c3 = w.commit("three"); + await tickCiPool({ marker, post: server.post, log: () => {}, spawnRun }); + expect(server.queue.map((q) => q.sha)).toEqual([w.c1, c2, c3]); + expect(server.queue[2]).toEqual({ sha: c3, before: c2 }); + expect(started).toHaveLength(1); + + // The run's process is gone (a pid that cannot be alive): its slot frees, and the oldest waiting sha goes next. + const dead = { ...marker }; + const state = path.join(process.env.HOME!, ".codecast", "ci-pool", "state.json"); + const s = JSON.parse(await Bun.file(state).text()); + s.runs[0].pid = 2 ** 22 + 12345; + writeFileSync(state, JSON.stringify(s)); + await tickCiPool({ marker: dead, post: server.post, log: () => {}, spawnRun }); + expect(started).toHaveLength(2); + expect(started[1]).toContain(c2); + expect(started[1]!.slice(started[1]!.indexOf("--before"), started[1]!.indexOf("--before") + 2)).toEqual(["--before", w.c1]); + }); + + test("a queued push that is not on the pool's branch is refused, and a run that never started gives its lease back", async () => { + const dir = mkdtempSync(path.join(tmp, "refuse-")); + const origin = path.join(dir, "origin"); + mkdirSync(origin); + g(origin, "init", "-q", "-b", "main"); + writeFileSync(path.join(origin, "a.txt"), "a"); + g(origin, "add", "."); + g(origin, "commit", "-qm", "a"); + const onMain = g(origin, "rev-parse", "HEAD"); + const mirror = path.join(dir, "mirror.git"); + sh("git", ["clone", "-q", "--bare", origin, mirror]); + // A sha that never landed on main (a fork's pull request head, say) sitting in the queue as a push. + const elsewhere = "ab".repeat(20); + const finished: Array<{ sha: string; conclusion: string }> = []; + const released: string[] = []; + const post = async (route: string, body: any) => { + if (route.endsWith("/enqueue") || route.endsWith("/register-pool")) return {}; + if (route.endsWith("/pending")) return { leases: [{ sha: elsewhere, event: "push" }, { sha: onMain, event: "push" }] }; + if (route.endsWith("/claim")) return { claimed: true }; + if (route.endsWith("/finish")) { finished.push({ sha: body.sha, conclusion: body.conclusion }); return { finished: true }; } + if (route.endsWith("/release")) { released.push(body.sha); return { released: true }; } + throw new Error(`unexpected ${route}`); + }; + const marker: PoolMarker = { role: "ci", pool: "p", repo: "o/r", host: "codecast-ci-1", slots: 50, mirror, lanes: ["linux"] }; + const started: string[][] = []; + await tickCiPool({ marker, post, log: () => {}, spawnRun: (argv) => { started.push(argv); return null; } }); + expect(finished).toEqual([{ sha: elsewhere, conclusion: "refused" }]); + expect(started.map((a) => a[a.indexOf("run") + 1])).toEqual([onMain]); + expect(released).toEqual([onMain]); + }); + + test("a post that throws after a run started still records that run, so the next tick counts its slot", async () => { + const dir = mkdtempSync(path.join(tmp, "throw-")); + const origin = path.join(dir, "origin"); + mkdirSync(origin); + g(origin, "init", "-q", "-b", "main"); + const shas: string[] = []; + for (const m of ["a", "b"]) { writeFileSync(path.join(origin, `${m}.txt`), m); g(origin, "add", "."); g(origin, "commit", "-qm", m); shas.push(g(origin, "rev-parse", "HEAD")); } + const mirror = path.join(dir, "mirror.git"); + sh("git", ["clone", "-q", "--bare", origin, mirror]); + let claims = 0; + const post = async (route: string) => { + if (route.endsWith("/enqueue") || route.endsWith("/register-pool")) return {}; + if (route.endsWith("/pending")) return { leases: shas.map((sha) => ({ sha, event: "push" })) }; + if (route.endsWith("/claim")) { if (++claims > 1) throw new Error("network down"); return { claimed: true }; } + throw new Error(`unexpected ${route}`); + }; + const marker: PoolMarker = { role: "ci", pool: "p", repo: "o/r", host: "codecast-ci-1", slots: 50, mirror, lanes: ["linux"] }; + const prevHome = process.env.HOME; + process.env.HOME = path.join(dir, "home"); + try { + await expect(tickCiPool({ marker, post, log: () => {}, spawnRun: () => process.pid })).rejects.toThrow("network down"); + const state = JSON.parse(await Bun.file(path.join(process.env.HOME, ".codecast", "ci-pool", "state.json")).text()); + expect(state.runs.map((r: { sha: string }) => r.sha)).toEqual([shas[0]]); + } finally { + process.env.HOME = prevHome; + } + }); + + /** A repository whose main carries `ci.toml`, mirrored, with one commit queued; HOME is the test's own. */ + function hostWorld(name: string, ciToml: string) { + const dir = mkdtempSync(path.join(tmp, `${name}-`)); + const origin = path.join(dir, "origin"); + mkdirSync(path.join(origin, ".codecast"), { recursive: true }); + g(origin, "init", "-q", "-b", "main"); + writeFileSync(path.join(origin, ".codecast", "ci.toml"), ciToml); + g(origin, "add", "."); + g(origin, "commit", "-qm", "ci.toml"); + const sha = g(origin, "rev-parse", "HEAD"); + const mirror = path.join(dir, "mirror.git"); + sh("git", ["clone", "-q", "--bare", origin, mirror]); + const calls: string[] = []; + const post = async (route: string, body: any) => { + calls.push(route.split("/").pop()!); + if (route.endsWith("/enqueue") || route.endsWith("/register-pool")) return {}; + if (route.endsWith("/pending")) return { leases: [{ sha, event: "push" }] }; + if (route.endsWith("/claim")) return { claimed: true, lease: { sha: body.sha, attempts: 2 } }; + throw new Error(`unexpected ${route}`); + }; + const marker: PoolMarker = { role: "ci", pool: "p", repo: "o/r", host: "line-2", slots: 1, mirror, lanes: ["linux"] }; + return { dir, sha, post, calls, marker, home: path.join(dir, "home") }; + } + + async function withHome(home: string, fn: () => Promise): Promise { + const prev = process.env.HOME; + process.env.HOME = home; + try { return await fn(); } finally { process.env.HOME = prev; } + } + + const busy: HostReadings = { memAvailableGiB: 12.4, cpuSomeAvg60: 31, memoryFullAvg60: 0.2, ioFullAvg60: 0, load1: 48 }; + const idle: HostReadings = { memAvailableGiB: 70, cpuSomeAvg60: 2, memoryFullAvg60: 0, ioFullAvg60: 0, load1: 4 }; + const ADMIT = "[host]\nmin_mem_available_gib = 26\nmax_memory_full_avg60 = 5\nmax_cpu_some_avg60 = 20\n"; + + test("a host below ci.toml's admission claims nothing and leaves the lease queued, saying why once", async () => { + const w = hostWorld("admit", ADMIT); + const logs: string[] = []; + const started: string[][] = []; + await withHome(w.home, async () => { + for (let i = 0; i < 2; i++) await tickCiPool({ marker: w.marker, post: w.post, log: (l) => logs.push(l), spawnRun: (a) => { started.push(a); return process.pid; }, readings: () => busy }); + expect(w.calls).not.toContain("claim"); + expect(w.calls).not.toContain("pending"); + expect(started).toEqual([]); + expect(logs.filter((l) => l.includes("takes no run"))).toEqual(["ci pool: line-2 takes no run now: 12.4 GiB free < 26 (12.4 GiB free, cpu 31%, mem 0.2%, io 0%, load 48); queued shas wait for another host"]); + + // The host frees up: it claims, and tells the run which claim of the lease it is. + await tickCiPool({ marker: w.marker, post: w.post, log: (l) => logs.push(l), spawnRun: (a) => { started.push(a); return process.pid; }, readings: () => idle }); + expect(logs).toContain("ci pool: line-2 admits runs again"); + expect(started).toHaveLength(1); + expect(started[0]!.slice(started[0]!.indexOf("--attempt"), started[0]!.indexOf("--attempt") + 2)).toEqual(["--attempt", "2"]); + }); + }); + + test("with shared_ci_slot, a CI slot held by another runner (Union's own-ci) keeps the host from claiming", async () => { + const state = mkdtempSync(path.join(tmp, "state-")); + const w = hostWorld("slot", `[host]\nshared_ci_slot = true\nstate = "${state}"\n`); + mkdirSync(path.join(state, "ci-slot")); + const holder = Bun.spawn(["sleep", "60"]); + writeFileSync(path.join(state, "ci-slot", "slot-0"), String(holder.pid)); + const started: string[][] = []; + const logs: string[] = []; + try { + await withHome(w.home, () => tickCiPool({ marker: w.marker, post: w.post, log: (l) => logs.push(l), spawnRun: (a) => { started.push(a); return process.pid; } })); + expect(w.calls).not.toContain("claim"); + expect(logs.some((l) => l.includes(`its CI slot (${path.join(state, "ci-slot")}) is held by another CI run`))).toBe(true); + } finally { + holder.kill(); + await holder.exited; + } + await withHome(w.home, () => tickCiPool({ marker: w.marker, post: w.post, log: () => {}, spawnRun: (a) => { started.push(a); return process.pid; } })); + expect(started).toHaveLength(1); + }); + + test("a sha this host gave back after an infra run is left for another host", async () => { + const w = hostWorld("avoid", ""); + const started: string[][] = []; + await withHome(w.home, async () => { + markAvoid(w.sha, "linux"); + await tickCiPool({ marker: w.marker, post: w.post, log: () => {}, spawnRun: (a) => { started.push(a); return process.pid; } }); + expect(w.calls).toContain("pending"); + expect(w.calls).not.toContain("claim"); + expect(started).toEqual([]); + }); + }); + + test("a wrong ci.toml on main stops the host taking runs, and says so", async () => { + const w = hostWorld("wrong", "[host]\nmin_mem_available_gib = \"lots\"\n"); + const logs: string[] = []; + await withHome(w.home, () => tickCiPool({ marker: w.marker, post: w.post, log: (l) => logs.push(l), spawnRun: () => process.pid })); + expect(w.calls).not.toContain("claim"); + expect(logs.some((l) => l.includes("host.min_mem_available_gib must be a number"))).toBe(true); + }); + + test("a machine without the role marker is not in a pool; a daemon run from source starts the CLI's entry", () => { + expect(readPoolMarker(path.join(tmp, "nope.json"))).toBeNull(); + const f = path.join(tmp, "pool.json"); + writeFileSync(f, JSON.stringify({ role: "ci", pool: "codecast-ci", repo: "codecast-sh/codecast", host: "codecast-ci-1", slots: 1 })); + expect(readPoolMarker(f)).toMatchObject({ repo: "codecast-sh/codecast", host: "codecast-ci-1", slots: 1 }); + expect(castArgv("/usr/local/bin/cast", "/whatever")).toEqual(["/usr/local/bin/cast"]); + expect(castArgv("/x/bun", path.join(import.meta.dir, "daemon.ts"))).toEqual(["/x/bun", path.join(import.meta.dir, "index.ts")]); + }); +}); diff --git a/packages/cli/src/ciRun/command.ts b/packages/cli/src/ciRun/command.ts new file mode 100644 index 0000000000..0881507f6d --- /dev/null +++ b/packages/cli/src/ciRun/command.ts @@ -0,0 +1,365 @@ +// `cast ci run `: codecast's own CI for one commit of any repository, on this machine. +// +// On a CI pool host (Linux) it runs in two halves. This process, as the host's own user (the daemon's), fetches the +// sha into the host's bare mirror under its lock, reads the repository's .codecast/ci.toml from a trusted tree (the +// commit itself for a push to main, main's tip for a pull request: a branch cannot grant its own jobs secrets), reads +// the vault secrets ci.toml names, and starts `cast ci run-inner` as root in the transient unit `ownci-.service` +// inside the per-run slice `ownci-.slice` (a child of ownci.slice, whose MemoryMax caps all CI on the host; +// cancel: `systemctl stop ownci-.slice`). The inner half takes one of the host's run slots (ci.toml +// runs_per_host, default 1), checks the slot's walls, wipes the slot user's home and runs the commit (run.ts). This +// half records the verdict with `cast ci record` as it goes: the in-progress verdict at least every 4 minutes (the +// pool controller counts a host busy by it), and the finished one with its job logs. +// +// `--unsandboxed` runs it all in this process, as this user, in a temp HOME: for trying a ci.toml on a laptop and +// for the macOS lane until the pool's macOS slot exists. + +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { parseCiConfig, type CiConfig } from "@codecast/shared/contracts/ciConfig"; +import type { JobOs } from "@codecast/shared/contracts/ciWorkflow"; +import type { RunnerVerdict } from "@codecast/shared/contracts/ciVerdict"; +import { LocalExecutor, setSetupTimeout, sh, SlotExecutor } from "./executor.js"; +import { admissionRefusal, ciSlotCount, ciSlotDir, describeReadings, holdCiSlot, hostNote, hostReadings, markAvoid, requeueInfra, sampleResources, setAside, thresholdsOf, withHostNote, type RunResources } from "./host.js"; +import { Masker } from "./mask.js"; +import { runCommit, type RunInput } from "./run.js"; + +export type RunOptions = { + repo?: string; + event?: "push" | "pull_request" | "workflow_dispatch"; + /** A workflow_dispatch run: the workflow file and its inputs (never recorded as the commit's CI). */ + workflow?: string; + inputs?: Record; + before?: string; + base?: string; + landing?: string; + only?: string; + os?: JobOs; + unsandboxed?: boolean; + out?: string; + record?: boolean; + /** The repository (owner/name) when ci.toml does not name it and --repo is not a checkout of it. */ + repository?: string; + /** A ci.toml file to use instead of the repository's (a repo that has not committed one yet). */ + config?: string; + /** A lease this run holds (ciLeases.ts, its run id): heartbeat it, and finish it with the conclusion. */ + lease?: string; + /** Which claim of the lease this run is (the lease's attempts after the claim): an infra first attempt is requeued. */ + attempt?: number; +}; + +/** The exit codes: 0 green (or nothing to run), 1 red, 2 infra (the runner's failure, not the commit's), 3 the host refused the run (admission). */ +export const RUN_EXIT = { success: 0, failure: 1, infra: 2, refused: 3 } as const; + +/** How to start this same cast: the compiled binary, or bun with the entry script when run from source. */ +export function selfArgv(): string[] { + const script = process.argv[1]; + return script && /\.(ts|js|mjs)$/.test(script) && existsSync(script) ? [process.execPath, path.resolve(script)] : [process.execPath]; +} + +const git = (dir: string, args: string[], timeoutMs?: number) => sh("git", ["-C", dir, ...args], { timeoutMs }); + +/** ci.toml at a ref of the source, parsed; absent is the default config. */ +export function configAt(source: string, ref: string): CiConfig { + const r = git(source, ["show", `${ref}:.codecast/ci.toml`]); + const raw = r.code === 0 ? Bun.TOML.parse(r.out) : {}; + const parsed = parseCiConfig(raw); + if ("problems" in parsed) throw new Error(`.codecast/ci.toml at ${ref.slice(0, 12)} is wrong:\n ${parsed.problems.join("\n ")}`); + return parsed.config; +} + +/** A ci.toml given on the command line, parsed. */ +export function configFile(file: string): CiConfig { + const parsed = parseCiConfig(Bun.TOML.parse(readFileSync(file, "utf-8"))); + if ("problems" in parsed) throw new Error(`${file} is wrong:\n ${parsed.problems.join("\n ")}`); + return parsed.config; +} + +/** The name this host goes by in verdicts: the pool's role marker (the EC2 Name tag), else its hostname. */ +export function hostName(config: CiConfig): string { + try { + const pool = JSON.parse(readFileSync(config.host.pool_file, "utf-8")) as { host?: string }; + if (pool.host) return pool.host; + } catch {} + return os.hostname().split(".")[0]!; +} + +/** + * The cache store actions/cache uses here: pool.json's `cache` (a pool's shared store, `s3://bucket`), else a directory + * on this host's own disk (root's, beside the runner's state), or on a laptop the person's cache directory. + */ +export function cacheSpec(config: CiConfig, unsandboxed: boolean): string { + if (unsandboxed) return `dir:${path.join(os.homedir(), ".cache", "castci", "cache")}`; + try { + const pool = JSON.parse(readFileSync(config.host.pool_file, "utf-8")) as { cache?: string }; + if (typeof pool.cache === "string" && pool.cache) return pool.cache; + } catch {} + return "dir:/var/lib/ownci/cache"; +} + +/** Fetch what a run needs into the host's bare mirror, under its lock: main, and the sha when it is not there. */ +function fetchMirror(mirror: string, branch: string, sha: string): void { + const lock = `${mirror}.lock`; + const r = sh("flock", [lock, "sh", "-c", `git -C "$1" fetch -q origin "+refs/heads/$2:refs/heads/$2" && { git -C "$1" cat-file -e "$3^{commit}" 2>/dev/null || git -C "$1" fetch -q origin "$3"; } && git -C "$1" update-ref "refs/ownci/keep/$3" "$3"`, "_", mirror, branch, sha], { timeoutMs: 10 * 60_000 }); + if (r.code !== 0) throw new Error(`fetching ${sha.slice(0, 12)} into ${mirror}: ${r.err}`); +} + +type Deps = { + /** A codecast CLI route (the lease's heartbeat and finish). */ + post?: (route: string, body: Record) => Promise; + readVault: (names: string[]) => Promise>; + record: (file: string, o: { logs: boolean }) => Promise<{ written: boolean }>; + repositoryOf: (dir: string) => string | null; + log: (line: string) => void; +}; + +export async function runCi(shaArg: string, opts: RunOptions, deps: Deps): Promise { + if (!opts.lease) return runCiOnce(shaArg, opts, deps); + const lease: Lease = { lost: false, released: false, key: null }; + let code: number = RUN_EXIT.infra; + let conclusion = "infra"; + try { + code = await runCiOnce(shaArg, opts, deps, lease, (c) => { conclusion = c; }); + } finally { + // A run that lost its lease leaves the sha to the host that took it over; one that gave it back left it queued. + if (lease.key && !lease.lost && !lease.released) await deps.post?.("/cli/ci/lease/finish", { ...lease.key, conclusion }).catch((err) => deps.log(`lease finish failed: ${err instanceof Error ? err.message : String(err)}`)); + } + return code; +} + +type Lease = { lost: boolean; released: boolean; key: null | Record }; + +/** Give the lease back unrun or unrecorded: queued again, for the next host's tick. */ +async function releaseLease(lease: Lease | undefined, deps: Deps): Promise { + if (!lease?.key || lease.lost || lease.released) return; + lease.released = true; + await deps.post?.("/cli/ci/lease/release", lease.key).catch((err) => deps.log(`lease release failed: ${err instanceof Error ? err.message : String(err)}`)); +} + +async function runCiOnce(shaArg: string, opts: RunOptions, deps: Deps, lease?: Lease, concluded: (c: string) => void = () => {}): Promise { + const repoDir = path.resolve(opts.repo ?? process.env.CODECAST_CWD ?? process.cwd()); + const lane: JobOs = opts.os ?? (process.platform === "darwin" ? "darwin" : "linux"); + const event = opts.event ?? (opts.landing ? "pull_request" : "push"); + if (!opts.unsandboxed && process.platform !== "linux") throw new Error("A sandboxed run needs a Linux CI host; on this machine pass --unsandboxed (steps then run as you, in a temp HOME)."); + + // The source checkouts clone from, and the trusted tree ci.toml is read from. + const local = git(repoDir, ["rev-parse", "--path-format=absolute", "--git-common-dir"]); + if (local.code !== 0 && opts.unsandboxed) throw new Error(`${repoDir} is not a git checkout`); + // The mirror and branch come from the given ci.toml, else this checkout's, else the default layout. + const bootstrap = opts.config ? configFile(opts.config) : local.code === 0 ? configAt(local.out, "HEAD") : parseConfigOrDefault(); + const source = opts.unsandboxed ? local.out : bootstrap.host.mirror; + const branch = bootstrap.branch; + let sha = git(source, ["rev-parse", "--verify", "-q", `${shaArg}^{commit}`]).out; + if (!opts.unsandboxed) { + fetchMirror(source, branch, /^[0-9a-f]{40}$/.test(shaArg) ? shaArg : sha || shaArg); + sha = git(source, ["rev-parse", "--verify", "-q", `${shaArg}^{commit}`]).out; + } + if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error(`${shaArg} is not a commit in ${source}`); + const mainRef = opts.unsandboxed ? (git(source, ["rev-parse", "--verify", "-q", `refs/remotes/origin/${branch}`]).out ? `refs/remotes/origin/${branch}` : `refs/heads/${branch}`) : `refs/heads/${branch}`; + const base = event === "pull_request" ? (opts.base ?? git(source, ["rev-parse", mainRef]).out) : undefined; + const config = opts.config ? configFile(opts.config) : configAt(source, event === "pull_request" ? base! : sha); + const repository = opts.repository ?? config.repository ?? deps.repositoryOf(repoDir); + if (!repository) throw new Error("No repository: set repository in .codecast/ci.toml or run from a checkout with an origin remote."); + setSetupTimeout(config); + const host = hostName(config); + if (opts.lease && !(new RegExp(`^${sha.slice(0, 12)}-[0-9a-z]+$`).test(opts.lease))) throw new Error(`--lease ${opts.lease} is not a run id of ${sha.slice(0, 12)}`); + const id = opts.lease ?? `${sha.slice(0, 12)}-${Date.now().toString(36)}`; + let leaseTimer: ReturnType | null = null; + let stopRun = () => {}; + if (lease && deps.post) { + lease.key = { repository, sha, lane, event, host, run_id: id }; + // Every 30 seconds, against the lease's 2-minute expiry: a run whose lease another host took over stops. + leaseTimer = setInterval(() => { + void deps.post!("/cli/ci/lease/heartbeat", lease.key!).then((r) => { + if (r?.held === false && !lease.lost) { + lease.lost = true; + deps.log(`lease lost: ${r.holder ?? "another host"} holds ${sha.slice(0, 12)} now; stopping this run`); + stopRun(); + } + }).catch((err) => deps.log(`lease heartbeat failed: ${err instanceof Error ? err.message : String(err)}`)); + }, 30_000); + } + try { + const out = path.resolve(opts.out ?? (opts.unsandboxed ? path.join(os.tmpdir(), "castci", id) : path.join(os.homedir(), "ci", "runs", `${sha}-${lane}${opts.workflow ? `-${path.basename(opts.workflow).replace(/\.ya?ml$/, "")}` : ""}`))); + // A sha run again here (a retry, a lease taken back) starts from an empty verdict directory: job logs append, and + // the last run's lines would read as this run's failures. + for (const stale of ["jobs", "runner.log", "verdict.json", "not-triggered.txt", "admission.json", "resources.json"]) rmSync(path.join(out, stale), { recursive: true, force: true }); + mkdirSync(path.join(out, "jobs"), { recursive: true }); + // Admission (ci.toml [host]): a sandboxed run starts only on a host with the memory and headroom it needs. The pool + // tick checks the same before it claims; this catches a host that filled up in between, and a run started by hand. + if (!opts.unsandboxed) { + const readings = hostReadings(); + const refused = admissionRefusal(readings, config.host); + writeFileSync(path.join(out, "admission.json"), `${JSON.stringify({ at: new Date().toISOString(), host, readings, thresholds: thresholdsOf(config.host), ...(opts.attempt ? { attempt: opts.attempt } : {}), ...(refused ? { refused } : {}) }, null, 2)}\n`); + if (refused) { + deps.log(`${host} refuses the run: ${refused}${readings ? ` (${describeReadings(readings)})` : ""}${lease?.key ? "; the lease goes back for another host" : ""}`); + await releaseLease(lease, deps); + concluded("refused"); + return RUN_EXIT.refused; + } + } + const only = opts.only?.split(",").map((s) => s.trim()).filter(Boolean); + const vaultNames = Object.entries(config.secrets).filter(([, s]) => s.vault).map(([n]) => n); + const vault = vaultNames.length ? await deps.readVault(vaultNames.map((n) => config.secrets[n]!.vault!)) : {}; + // A vault secret is read by its vault name; the job sees it by its ci.toml name. + const secrets = Object.fromEntries(vaultNames.filter((n) => vault[config.secrets[n]!.vault!] !== undefined).map((n) => [n, vault[config.secrets[n]!.vault!]!])); + deps.log(`${repository} ${sha.slice(0, 12)} (${event}, ${lane} lane) on ${host} as castci-${id}; verdict in ${out}`); + + const base_: Omit = { + repository, sha, event, ...(opts.workflow ? { workflow: opts.workflow } : {}), ...(opts.inputs ? { inputs: opts.inputs } : {}), ...(opts.before ? { before: opts.before } : {}), ...(base ? { base } : {}), ...(opts.landing ? { headRef: opts.landing } : {}), + source, out, id, host, lane, config, cache: cacheSpec(config, !!opts.unsandboxed), ...(only ? { only } : {}), + }; + + let lastBeat = 0; + const beat = async (force = false) => { + if (opts.record === false || only) return; + if (!force && Date.now() - lastBeat < 4 * 60_000) return; + lastBeat = Date.now(); + try { await deps.record(path.join(out, "verdict.json"), { logs: false }); } catch (err) { deps.log(`heartbeat record failed: ${err instanceof Error ? err.message : String(err)}`); } + }; + + let verdict: RunnerVerdict | null = null; + if (opts.unsandboxed) { + const masker = new Masker((n) => !!config.secrets[n]?.public); + const merged = { ...envSecrets(config), ...secrets }; + masker.addAll(merged); + const r = await runCommit({ ...base_, secrets: merged, executor: new LocalExecutor(config), masker, say: deps.log, onVerdict: () => void beat() }); + if (!r.triggered) { deps.log(`not run: ${r.why} (GitHub runs no CI for it either)`); rmSync(out, { recursive: true, force: true }); concluded("not_triggered"); return 0; } + verdict = r.verdict; + } else { + // The inner half's job, root-only: its vault values never touch argv, a log or a file anyone else reads. + const state = config.host.state; + const jobFile = path.join(state, `${id}.job.json`); + const payload = JSON.stringify({ input: base_, secrets, uid: process.getuid?.(), gid: process.getgid?.() }); + const put = sh("sudo", ["-n", "sh", "-c", 'mkdir -p -m 755 "$1" && install -m 600 -o root -g root /dev/stdin "$2"', "_", state, jobFile], { input: payload }); + if (put.code !== 0) throw new Error(`could not hand the run to root (sudo): ${put.err}`); + const unit = `ownci-${id}`; + const start = sh("sudo", ["-n", "systemd-run", "--quiet", "--collect", `--unit=${unit}`, `--slice=ownci-${id.replace("-", "_")}.slice`, + "-p", "RuntimeMaxSec=21600", "-p", "WorkingDirectory=/", "-p", `StandardOutput=append:${out}/runner.log`, "-p", `StandardError=append:${out}/runner.log`, + "--setenv=HOME=/root", "--setenv=PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", + ...selfArgv(), "ci", "run-inner", jobFile]); + if (start.code !== 0) throw new Error(`could not start ${unit}: ${start.err}`); + stopRun = () => { sh("sudo", ["-n", "systemctl", "stop", `ownci-${id.replace("-", "_")}.slice`]); }; + const active = () => ["active", "activating", "deactivating"].includes(sh("systemctl", ["is-active", `${unit}.service`]).out); + while (active()) { + await Bun.sleep(1_000); + if (existsSync(path.join(out, "verdict.json"))) await beat(); + } + sh("sudo", ["-n", "systemctl", "stop", `ownci-${id.replace("-", "_")}.slice`]); + if (existsSync(path.join(out, "not-triggered.txt"))) { deps.log(`not run: ${readFileSync(path.join(out, "not-triggered.txt"), "utf-8").trim()}`); concluded("not_triggered"); return 0; } + if (lease?.lost) { deps.log("stopped: the lease went to another host, which records this sha"); return RUN_EXIT.infra; } + try { + verdict = JSON.parse(readFileSync(path.join(out, "verdict.json"), "utf-8")) as RunnerVerdict; + } catch { + verdict = null; + } + if (!verdict || verdict.status !== "completed") { + // The unit ended without finishing its verdict (killed, OOM, the host restarted): the runner broke. + verdict = { ...(verdict ?? { version: 1, repository, sha, name: config.name, kind: event === "pull_request" ? "landing" : "main", host, run_id: `castci-${id}`, started_at: Date.now(), jobs: [] }), status: "completed", conclusion: "infra", finished_at: Date.now() } as RunnerVerdict; + writeFileSync(path.join(out, "verdict.json"), `${JSON.stringify(verdict, null, 2)}\n`); + } + } + // An infra first attempt goes again on another host before anything is recorded (Union's dispatcher does the same): + // its directory is set aside, this host leaves the sha alone for a while, and the lease goes back on the queue. + if (lease?.key && !lease.lost && requeueInfra({ conclusion: verdict.conclusion, attempt: opts.attempt, enabled: config.host.requeue_infra, partial: !!only })) { + const aside = setAside(out); + markAvoid(sha, lane); + await releaseLease(lease, deps); + deps.log(`${sha.slice(0, 12)}: infra on ${host}; queued again for another host, not recorded (kept in ${aside})`); + concluded("infra"); + return RUN_EXIT.infra; + } + for (const j of verdict.jobs) deps.log(` ${j.name.padEnd(28)} ${j.conclusion.padEnd(8)} ${String(j.seconds).padStart(5)}s${j.counts ? "" : " (does not count)"}${j.note ? ` ${j.note}` : ""}`); + deps.log(`${sha.slice(0, 12)}: ${verdict.conclusion}`); + if (opts.record !== false && !only) { + const r = await deps.record(path.join(out, "verdict.json"), { logs: true }); + deps.log(r.written ? "recorded" : "not recorded: a newer run of this sha is stored"); + } else if (only) deps.log("partial run (--only): not recorded"); + concluded(verdict.conclusion ?? "infra"); + return RUN_EXIT[verdict.conclusion ?? "infra"]; + } finally { + if (leaseTimer) clearInterval(leaseTimer); + } +} + +function parseConfigOrDefault(): CiConfig { + const p = parseCiConfig({}); + if ("problems" in p) throw new Error(p.problems.join("; ")); + return p.config; +} + +/** The host's secrets file (root 0600, `NAME=value` lines), when this process may read it. */ +function readEnvFile(file: string): Record { + const out: Record = {}; + let text = ""; + try { text = readFileSync(file, "utf-8"); } catch { return out; } + for (const line of text.split("\n")) { + const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim()); + if (m) out[m[1]!] = m[2]!.replace(/^(['"])(.*)\1$/, "$2"); + } + return out; +} + +/** An unsandboxed run's non-vault secrets: from this process's environment, as `cast vault run` would set them. */ +function envSecrets(config: CiConfig): Record { + const out: Record = {}; + for (const name of Object.keys(config.secrets)) if (process.env[name]) out[name] = process.env[name]!; + for (const s of Object.values(config.secrets)) if (s.github_app && process.env[s.github_app.key_secret]) out[s.github_app.key_secret] = process.env[s.github_app.key_secret]!; + return out; +} + +/** `cast ci run-inner `: the root half on a CI host. */ +export async function runInner(jobFile: string): Promise { + if (process.getuid?.() !== 0) { console.error("run-inner runs as root (cast ci run starts it)"); return 2; } + const st = statSync(jobFile); + if (st.uid !== 0 || (st.mode & 0o077) !== 0) { console.error(`${jobFile} must be root's and 0600`); return 2; } + const job = JSON.parse(readFileSync(jobFile, "utf-8")) as { input: Omit; secrets: Record; uid?: number; gid?: number }; + rmSync(jobFile, { force: true }); + const { input } = job; + const config = input.config; + const masker = new Masker((n) => !!config.secrets[n]?.public); + const secrets = { ...readEnvFile(config.host.env_file), ...job.secrets }; + masker.addAll(secrets); + const say = (l: string) => console.log(masker.apply(`${new Date().toISOString()} castci: ${l}`)); + setSetupTimeout(config); + // The host's CI slot before anything else: with shared_ci_slot it is the one Union's own-ci holds, so the two never + // run side by side. Its index is the sandbox slot the run gets. + const { slot, release } = await holdCiSlot({ dir: ciSlotDir(config), slots: ciSlotCount(config), say }); + const chownOut = () => job.uid !== undefined && sh("chown", ["-R", `${job.uid}:${job.gid ?? job.uid}`, input.out]); + const runSlice = `ownci-${input.id.replace("-", "_")}.slice`; + const sampler = sampleResources(config.host.slice, runSlice); + if (sampler.atStart) say(`host at start: ${describeReadings(sampler.atStart)}`); + try { + const ex = new SlotExecutor(config, slot, input.id, runSlice, (n, v) => masker.add(n, v)); + const walls = ex.wallsMissing(); + if (walls) throw new Error(`slot ${slot}'s isolation is not in place (${walls}): the CI pool's host setup provisions it`); + ex.freshHome(); + const r = await runCommit({ ...input, secrets, executor: ex, masker, say }); + if (!r.triggered) writeFileSync(path.join(input.out, "not-triggered.txt"), `${r.why}\n`); + } catch (err) { + say(`the runner broke before the run: ${err instanceof Error ? err.message : String(err)}`); + const v: RunnerVerdict = { version: 1, repository: input.repository, sha: input.sha, name: config.name, kind: input.event === "pull_request" ? "landing" : "main", host: input.host, run_id: `castci-${input.id}`, started_at: Date.now(), finished_at: Date.now(), status: "completed", conclusion: "infra", jobs: [] }; + writeFileSync(path.join(input.out, "verdict.json"), `${masker.apply(JSON.stringify(v, null, 2))}\n`); + } finally { + noteResources(input.out, sampler.stop(), masker.apply.bind(masker), say); + release(); + chownOut(); + } + return 0; +} + +/** resources.json beside the verdict, and the host's readings on the verdict's notes of the jobs that did not pass. */ +function noteResources(out: string, resources: RunResources, mask: (t: string) => string, say: (l: string) => void): void { + try { + writeFileSync(path.join(out, "resources.json"), `${JSON.stringify(resources, null, 2)}\n`); + say(`resources: peak ${resources.peakAnonGiB} GiB anonymous, ${resources.peakChargedGiB} GiB charged${resources.atEnd ? `; host at end ${describeReadings(resources.atEnd)}` : ""}`); + const file = path.join(out, "verdict.json"); + if (!existsSync(file)) return; + const noted = withHostNote(JSON.parse(readFileSync(file, "utf-8")) as RunnerVerdict, hostNote(resources)); + const tmp = path.join(out, `.verdict.json.${process.pid}`); + writeFileSync(tmp, `${mask(JSON.stringify(noted, null, 2))}\n`); + renameSync(tmp, file); + } catch (err) { + say(`resources: ${err instanceof Error ? err.message : String(err)}`); + } +} diff --git a/packages/cli/src/ciRun/executor.ts b/packages/cli/src/ciRun/executor.ts new file mode 100644 index 0000000000..648ebf541e --- /dev/null +++ b/packages/cli/src/ciRun/executor.ts @@ -0,0 +1,511 @@ +// Where a CI run's steps execute. The rule both executors hold (from Union's runner, ct-102083): a commit's code +// may see its own run's secrets, never the host, another run, or anything left for the next run. +// +// SlotExecutor (Linux CI hosts, run as root): each step is a transient systemd unit inside the run's slice, run as +// the slot's user `` (no sudo, home wiped at every run start), in the slot's network namespace (its +// own loopback, the internet through NAT, of the host only the CI Postgres; IPv6 off), with its own /tmp, IPC and +// /dev/shm, the file system read-only outside its home, other users' processes hidden, and an environment file +// only root reads. Every read of a file a run wrote happens as the slot user: a regular file only, size-capped, +// with a timeout. The host layout (users, namespaces, cluster, mirror, pinned git) is provisioned by the pool +// (ct-103162) to the names in ciConfig.ts's DEFAULT_HOST_LAYOUT. +// +// LocalExecutor (`--unsandboxed`): steps run as the person running cast, in a fresh temp HOME with a runner's +// environment and nothing of theirs. No walls: for trying a repo's ci.toml on a laptop and for the macOS lane until +// the pool's macOS slot exists. + +import { spawn, spawnSync } from "../proc.js"; +import { closeSync, createWriteStream, existsSync, openSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { randomBytes } from "node:crypto"; +import type { CiConfig } from "@codecast/shared/contracts/ciConfig"; +import type { JobOs } from "@codecast/shared/contracts/ciWorkflow"; + +export type Sh = { code: number; out: string; err: string }; + +/** + * How long a setup command may take (a checkout, reading a job's files, the CI Postgres): ci.toml [host] + * setup_timeout_minutes, 10 by default. Hosts that also run agent sessions get slow under load, and a 2-minute git + * checkout timed out there and made two of Union's runs infra (Dec 1). A slow host makes a slow run, not a broken one. + */ +let setupTimeoutMs = 10 * 60_000; +export const setupTimeout = () => setupTimeoutMs; +export function setSetupTimeout(config: Pick): void { + setupTimeoutMs = Math.round(config.host.setup_timeout_minutes * 60_000); +} + +export function sh(cmd: string, args: string[], opts: { input?: string; timeoutMs?: number; env?: NodeJS.ProcessEnv; cwd?: string } = {}): Sh { + const r = spawnSync(cmd, args, { encoding: "utf-8", input: opts.input, cwd: opts.cwd, timeout: opts.timeoutMs ?? setupTimeoutMs, maxBuffer: 64 * 1024 * 1024, env: opts.env ?? process.env }); + return { code: r.status ?? 1, out: (r.stdout ?? "").trim(), err: ((r.stderr ?? "") + (r.error ? r.error.message : "")).trim() }; +} + +/** sh without blocking: a run's concurrent runners check out side by side, not one after another. */ +export function shAsync(cmd: string, args: string[], opts: { timeoutMs?: number; env?: NodeJS.ProcessEnv; cwd?: string } = {}): Promise { + return new Promise((resolve) => { + const child = spawn(cmd, args, { cwd: opts.cwd, env: opts.env ?? process.env, stdio: ["ignore", "pipe", "pipe"] }); + let out = ""; + let err = ""; + child.stdout!.on("data", (d: Buffer) => { out += d.toString("utf-8"); }); + child.stderr!.on("data", (d: Buffer) => { err += d.toString("utf-8"); }); + const ms = opts.timeoutMs ?? setupTimeoutMs; + const timer = setTimeout(() => { err += `\ntimed out after ${ms}ms`; child.kill("SIGKILL"); }, ms); + child.on("error", (e) => { err += e.message; }); + child.on("close", (code) => { clearTimeout(timer); resolve({ code: code ?? 1, out: out.trim(), err: err.trim() }); }); + }); +} + +/** A command whose stdin reads a file and/or whose stdout writes one (opened by this process, not the command). */ +export function shFiles(cmd: string, args: string[], o: { stdin?: string; stdout?: string; timeoutMs?: number; env?: NodeJS.ProcessEnv; cwd?: string }): Sh { + const inFd = o.stdin ? openSync(o.stdin, "r") : "ignore"; + const outFd = o.stdout ? openSync(o.stdout, "w", 0o600) : "pipe"; + try { + const r = spawnSync(cmd, args, { encoding: "utf-8", stdio: [inFd, outFd, "pipe"], cwd: o.cwd, timeout: o.timeoutMs ?? 10 * 60_000, maxBuffer: 64 * 1024 * 1024, env: o.env ?? process.env }); + return { code: r.status ?? 1, out: (typeof r.stdout === "string" ? r.stdout : "").trim(), err: ((r.stderr ?? "") + (r.error ? r.error.message : "")).trim() }; + } finally { + if (typeof inFd === "number") closeSync(inFd); + if (typeof outFd === "number") closeSync(outFd); + } +} + +export type StepSpec = { + /** Unique within the run: names the step's unit and its env file. */ + key: string; + script: string; + shell: "bash" | "sh"; + cwd: string; + env: Record; + deadline: number; + onLine: (line: string) => void; + /** The cores the step may use (AllowedCPUs syntax), when its runner shares the host with others. */ + cpus?: string; +}; +export type StepOutcome = { code: number; timedOut: boolean }; + +export interface Executor { + readonly os: JobOs; + readonly sandboxed: boolean; + readonly slot: number; + /** The run user's home; checkouts and scratch live under it. */ + readonly home: string; + readonly user: string; + /** Root-owned tool directory (/git, /bun/, /node/), or null when the host's own tools serve. */ + readonly opt: string | null; + /** The PATH every step starts from. */ + basePath(): string; + /** git as the run user, reading no config of its own. */ + git(args: string[], cwd: string, timeoutMs?: number): Sh; + /** The same, without blocking the runner (checkouts). */ + gitAsync(args: string[], cwd: string, timeoutMs?: number): Promise; + mkdirs(dirs: string[]): void; + /** A command as the run user outside any step (a cache's tar): stdin from a file, stdout to one, each opened by the runner. */ + asUser(argv: string[], io?: { stdin?: string; stdout?: string; timeoutMs?: number }): Sh; + /** A file a step wrote: a regular file only, at most maxBytes, null when absent or anything else. */ + readRunFile(file: string, maxBytes?: number): string | null; + /** The regular files directly in a directory a step wrote, matching a glob. */ + listRunFiles(dir: string, pattern: string): string[]; + runStep(s: StepSpec): Promise; + /** The bin directory of a pinned bun (installed once per version), or null to use the host's. */ + bunBin(version: string): string; + nodeBin(major: string): string; + /** + * A tool directory as the job's own: a copy owned by the run user under dest, as GitHub's setup actions install + * into the runner user's home (code that treats a root-owned runtime as an MDM install sees what it would there). + */ + ownCopy(bin: string, dest: string): string; + /** A Postgres database of its own for one job runner, as a URL only the run's environment holds. */ + postgres?(port: number, db: string): string; + /** End every process the run left, drop its Postgres role, remove its work tree. */ + cleanup(workDir: string): void; +} + +/** git as root or as a run user reads only this, and no system config: a run cannot plant hooks or aliases for the next. */ +const gitEnv = (config: CiConfig) => ({ GIT_CONFIG_GLOBAL: config.host.gitconfig, GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0" }); + +// A step's git: its global config is the job's own ~/.gitconfig (empty, as on GitHub), and code that reads +// GIT_CONFIG_GLOBAL as the person's config finds nothing; the root-owned mirror stays trusted through the env. +const stepGitEnv = (config: CiConfig) => ({ GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "safe.directory", GIT_CONFIG_VALUE_0: config.host.mirror }); + +/** + * Checkout-local git config keys that make git run a command. A step can write the checkout's .git/config, and the + * runner's own git (a later `actions/checkout` ref move) runs outside the step's walls, so a planted fsmonitor, filter + * driver, alias or include would run there. The runner sets none of these, so finding one refuses the git call. + */ +const COMMAND_CONFIG = /^(core\.(fsmonitor|sshcommand|pager|editor|askpass|hookspath|gitproxy|alternaterefscommand)|filter\..+|diff\..+\.(command|textconv)|merge\..+\.driver|alias\..+|include\.path|includeif\..+|credential\..*|uploadpack\..+|sequence\.editor|gpg\..*program|.+\.helper)$/i; + +export function plantedGitConfig(localKeys: string[]): string[] { + return localKeys.map((k) => k.trim()).filter((k) => k && COMMAND_CONFIG.test(k)); +} + +/** The runner's git: no hooks and no fsmonitor, whatever the checkout's config says. */ +const RUNNER_GIT = ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"]; + +/** Runs `git` through `run` after checking the checkout's own config for anything that would execute. */ +function guardedGit(run: (argv: string[]) => Sh, args: string[]): Sh { + // Reading config runs nothing; an absent or unreadable local config lists nothing. + const listed = run(["git", ...RUNNER_GIT, "config", "--local", "--name-only", "--list"]); + const planted = listed.code === 0 ? plantedGitConfig(listed.out.split("\n")) : []; + if (planted.length) return { code: 1, out: "", err: `refused: the checkout's git config sets ${planted.join(", ")}, which a step must have written` }; + return run(["git", ...RUNNER_GIT, ...args]); +} + +async function guardedGitAsync(run: (argv: string[]) => Promise, args: string[]): Promise { + const listed = await run(["git", ...RUNNER_GIT, "config", "--local", "--name-only", "--list"]); + const planted = listed.code === 0 ? plantedGitConfig(listed.out.split("\n")) : []; + if (planted.length) return { code: 1, out: "", err: `refused: the checkout's git config sets ${planted.join(", ")}, which a step must have written` }; + return run(["git", ...RUNNER_GIT, ...args]); +} + +/** A value for a systemd EnvironmentFile line: double-quoted, with `\` and `"` escaped (systemd expands nothing). */ +const envLine = (k: string, v: string) => `${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`; + +function pump(stream: NodeJS.ReadableStream, onLine: (l: string) => void) { + let buf = ""; + stream.on("data", (d: Buffer) => { + buf += d.toString("utf-8"); + const parts = buf.split("\n"); + buf = parts.pop() ?? ""; + for (const p of parts) onLine(p); + }); + stream.on("end", () => buf && onLine(buf)); +} + +const RUN_ROLE = /^[a-z_]+\d+_[0-9a-f]{12}_[0-9a-z]+$/; + +export class SlotExecutor implements Executor { + readonly os = "linux" as const; + readonly sandboxed = true; + readonly user: string; + readonly home: string; + readonly opt: string; + private stepSeq = 0; + private pgRole: { role: string; password: string } | null = null; + constructor(readonly config: CiConfig, readonly slot: number, readonly runId: string, readonly slice: string, private onSecret: (name: string, value: string) => void) { + this.user = `${config.host.slot_user}${slot}`; + this.home = `/home/${this.user}`; + this.opt = config.host.opt; + } + private get netns() { return this.user; } + private get state() { return path.join(this.config.host.state, this.runId); } + + basePath() { + return `${this.opt}/git/bin:${this.opt}/node/default/bin:/usr/local/bin:/usr/bin:/bin`; + } + + /** A command as the slot's user, outside any step (the checkout, reading what a step wrote). */ + private slotArgv(args: string[], cwd?: string): string[] { + const env = ["env", "-i", `HOME=${this.home}`, `PATH=${this.basePath()}`, ...Object.entries(gitEnv(this.config)).map(([k, v]) => `${k}=${v}`)]; + return ["-u", this.user, "--", ...env, ...(cwd ? ["sh", "-c", 'cd "$0" && exec "$@"', cwd] : []), ...args]; + } + + private asSlot(args: string[], opts: { cwd?: string; timeoutMs?: number } = {}): Sh { + return sh("runuser", this.slotArgv(args, opts.cwd), { timeoutMs: opts.timeoutMs }); + } + + git(args: string[], cwd: string, timeoutMs?: number) { + return guardedGit((argv) => this.asSlot(argv, { cwd, timeoutMs }), args); + } + + gitAsync(args: string[], cwd: string, timeoutMs?: number) { + return guardedGitAsync((argv) => shAsync("runuser", this.slotArgv(argv, cwd), { timeoutMs }), args); + } + + mkdirs(dirs: string[]) { + this.asSlot(["mkdir", "-p", ...dirs]); + } + + asUser(argv: string[], io: { stdin?: string; stdout?: string; timeoutMs?: number } = {}): Sh { + return shFiles("runuser", ["-u", this.user, "--", "env", "-i", `HOME=${this.home}`, `PATH=${this.basePath()}`, ...argv], io); + } + + readRunFile(file: string, maxBytes = 8 * 1024 * 1024): string | null { + const r = spawnSync("runuser", ["-u", this.user, "--", "sh", "-c", '[ -f "$1" ] && [ ! -L "$1" ] && exec head -c "$2" -- "$1"', "_", file, String(maxBytes)], { encoding: "utf-8", timeout: 30_000, maxBuffer: maxBytes + 1024 }); + return r.status === 0 ? (r.stdout ?? "") : null; + } + + listRunFiles(dir: string, pattern: string): string[] { + const r = this.asSlot(["find", dir, "-maxdepth", "1", "-type", "f", "-name", pattern, "-printf", "%f\\n"], { timeoutMs: 30_000 }); + return r.code === 0 ? r.out.split("\n").filter((f) => f && !f.includes("/")) : []; + } + + /** Every process of the slot's user, ended by pid (the slot's user runs nothing between runs). */ + private endProcesses() { + for (const p of sh("pgrep", ["-u", this.user]).out.split("\n").filter((x) => /^\d+$/.test(x))) { + try { process.kill(Number(p), "SIGKILL"); } catch {} + } + } + + /** + * The slot's walls, checked before a run: its namespace, the host rules that let it reach only Postgres, the rule + * that keeps its user off the host's own network, and IPv6 off on both ends. A missing one makes the run infra. + */ + wallsMissing(): string | null { + const s = this.slot; + const iface = `ownci-h${s}`; + const peer = `ownci-p${s}`; + if (sh("ip", ["netns", "exec", this.netns, "true"]).code !== 0) return `no network namespace ${this.netns}`; + const rules: Array<[string, string[]]> = [ + ["iptables", ["-C", "INPUT", "-i", iface, "-j", `OWNCI-IN-${s}`]], + ["iptables", ["-C", "FORWARD", "-i", iface, "-j", `OWNCI-FWD-${s}`]], + ["ip6tables", ["-C", "INPUT", "-i", iface, "-j", "REJECT"]], + ["ip6tables", ["-C", "FORWARD", "-i", iface, "-j", "REJECT"]], + ["iptables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.user, "-j", "REJECT"]], + ["ip6tables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.user, "-j", "REJECT"]], + ]; + if (Object.keys(this.config.services).length) { + rules.push(["iptables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.config.host.pg_admin, "-j", "OWNCI-PG-OUT"]]); + rules.push(["ip6tables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.config.host.pg_admin, "-j", "OWNCI-PG-OUT"]]); + } + for (const [tool, rule] of rules) if (sh(tool, rule).code !== 0) return `${tool} rule missing: ${rule.join(" ")}`; + if (sh("cat", [`/proc/sys/net/ipv6/conf/${iface}/disable_ipv6`]).out !== "1") return `IPv6 is on for ${iface}`; + if (sh("ip", ["netns", "exec", this.netns, "cat", `/proc/sys/net/ipv6/conf/${peer}/disable_ipv6`]).out !== "1") return `IPv6 is on for ${peer}`; + if (!existsSync(path.join(this.opt, "git", "bin", "git"))) return `no pinned git at ${this.opt}/git`; + return null; + } + + /** The slot user's home, emptied and made anew (700, owned by the user). */ + freshHome() { + this.endProcesses(); + rmSync(this.home, { recursive: true, force: true }); + mkdirSync(this.home, { mode: 0o700 }); + sh("chown", [`${this.user}:${this.user}`, this.home]); + } + + private psqlAdmin(sql: string, db = "postgres", port = 5440) { + return sh("runuser", ["-u", this.config.host.pg_admin, "--", "psql", "-h", this.config.host.pg_socket, "-p", String(port), "-d", db, "-v", "ON_ERROR_STOP=1", "-Atq", "-f", "-"], { input: sql, timeoutMs: 90_000 }); + } + + /** A run's role and everything it holds: its sessions, its databases, what it owns elsewhere, then the role. */ + dropRole(role: string, port: number) { + if (!RUN_ROLE.test(role)) throw new Error(`not a run role: ${role}`); + this.psqlAdmin(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = '${role}'`, "postgres", port); + const owned = this.psqlAdmin(`SELECT d.datname FROM pg_database d JOIN pg_roles r ON r.oid = d.datdba WHERE r.rolname = '${role}'`, "postgres", port); + for (const db of owned.code === 0 ? owned.out.split("\n").filter(Boolean) : []) this.psqlAdmin(`DROP DATABASE IF EXISTS "${db.replace(/"/g, '""')}" WITH (FORCE)`, "postgres", port); + for (const db of ["postgres", "template1"]) this.psqlAdmin(`DO $$ BEGIN IF EXISTS (SELECT FROM pg_roles WHERE rolname = '${role}') THEN EXECUTE 'DROP OWNED BY ${role}'; END IF; END $$`, db, port); + const dropped = this.psqlAdmin(`DROP ROLE IF EXISTS ${role}`, "postgres", port); + if (dropped.code !== 0) throw new Error(`could not drop the run role ${role}: ${dropped.err}`); + } + + /** + * A fresh login role for this run in its slot's group (which pg_hba admits only from the slot's namespace): + * CREATEDB, no superuser, GitHub's 97 connections, a password made now that exists only in this run. The group is + * reset first, and a group that keeps a setting makes the run infra. + */ + private runRole(port: number): { role: string; password: string } { + if (this.pgRole) return this.pgRole; + const group = `${this.config.host.pg_group}${this.slot}`; + this.psqlAdmin(`ALTER ROLE ${group} RESET ALL`, "postgres", port); + const kept = this.psqlAdmin(`SELECT count(*) FROM pg_db_role_setting s JOIN pg_roles r ON r.oid = s.setrole WHERE r.rolname = '${group}'`, "postgres", port); + if (kept.code !== 0 || kept.out.trim() !== "0") throw new Error(`the slot group ${group} keeps settings after RESET ALL (${kept.out || kept.err})`); + const role = `${group}_${this.runId.replace("-", "_")}`; + this.dropRole(role, port); + const password = randomBytes(24).toString("hex"); + this.onSecret("CASTCI_PG_PASSWORD", password); + const made = this.psqlAdmin(`CREATE ROLE ${role} LOGIN CREATEDB NOSUPERUSER NOCREATEROLE NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 97 IN ROLE ${group} PASSWORD '${password}'`, "postgres", port); + if (made.code !== 0) throw new Error(`could not make the run role ${role}: ${made.err.split(password).join("***")}`); + this.pgRole = { role, password }; + return this.pgRole; + } + + postgres(port: number, db: string): string { + if (!/^[a-z0-9_]+$/.test(db)) throw new Error(`not a database name: ${db}`); + const { role, password } = this.runRole(port); + const made = this.psqlAdmin(`CREATE DATABASE "${db}" OWNER ${role}`, "postgres", port); + if (made.code !== 0 && !/already exists/.test(made.err)) throw new Error(`could not make database ${db}: ${made.err}`); + // 127.0.0.1: inside the slot's namespace is forwarded to the CI cluster. + return `postgresql://${role}:${password}@127.0.0.1:${port}/${db}?sslmode=disable`; + } + + bunBin(version: string): string { + return installedTool(path.join(this.opt, "bun"), version, /^[0-9]+\.[0-9]+\.[0-9]+$/, "bun", (tmp) => + sh("bash", ["-c", 'curl -fsSL https://bun.sh/install | BUN_INSTALL="$1" bash -s "bun-v$2" >/dev/null 2>&1', "_", tmp, version], { timeoutMs: 5 * 60_000 })); + } + + nodeBin(major: string): string { + const bin = path.join(this.opt, "node", major, "bin"); + if (!existsSync(path.join(bin, "node"))) throw new Error(`the host has no node ${major} at ${bin}: the CI pool's image provisions it`); + return bin; + } + + ownCopy(bin: string, dest: string): string { + const r = this.asSlot(["sh", "-c", 'mkdir -p "$1" && cp -a "$2"/. "$1"/', "_", dest, bin]); + if (r.code !== 0) throw new Error(`could not copy ${bin} for the job: ${r.err}`); + return dest; + } + + runStep(s: StepSpec): Promise { + const n = ++this.stepSeq; + const unit = `ownci-step-${this.runId}-${n}`; + const envFile = path.join(this.state, `${s.key}-${n}.env`); + mkdirSync(path.dirname(envFile), { recursive: true, mode: 0o700 }); + writeFileSync(envFile, `${Object.entries({ ...s.env, ...stepGitEnv(this.config) }).map(([k, v]) => envLine(k, v)).join("\n")}\n`, { mode: 0o600 }); + const left = Math.max(5, Math.ceil((s.deadline - Date.now()) / 1000)); + const h = this.config.host; + // A step's result is its shell's, as on GitHub: what it leaves running is KILLed when the shell exits (KillMode=mixed), + // where systemd's default TERMs it and, when it ignores TERM (a test's leaked daemon), waits 90s and fails the unit. + // systemd ignores SIGPIPE in a unit by default; a GitHub step does not, and a pipeline's writer must die with it. + // A step's /tmp is a tmpfs of its own (GitHub's runners each have a disk; here every runner shares one EBS volume, + // and the tests' scratch repos in /tmp held its IOPS at the cap, stalling workers on the ext4 journal). + const args = [ + "--wait", "--pipe", "--collect", "--quiet", `--unit=${unit}`, `--slice=${this.slice}`, + `--uid=${this.user}`, `--gid=${this.user}`, + "-p", `NetworkNamespacePath=/run/netns/${this.netns}`, + "-p", `BindReadOnlyPaths=${h.resolv}:/run/systemd/resolve/stub-resolv.conf`, + "-p", "TemporaryFileSystem=/tmp:mode=1777,size=12G", "-p", "TemporaryFileSystem=/var/tmp:mode=1777,size=4G", "-p", "PrivateIPC=yes", "-p", "TemporaryFileSystem=/dev/shm:mode=1777", "-p", "TemporaryFileSystem=/run/lock:mode=1777", + "-p", "ProtectHome=tmpfs", "-p", `BindPaths=${this.home}`, + "-p", "ProtectSystem=strict", "-p", `ReadWritePaths=${this.home}`, + "-p", "ProtectProc=invisible", "-p", "NoNewPrivileges=yes", "-p", "IgnoreSIGPIPE=no", "-p", "KillMode=mixed", + "-p", "InaccessiblePaths=-/run/postgresql", "-p", `InaccessiblePaths=-${h.pg_socket}`, "-p", `InaccessiblePaths=-${path.dirname(h.env_file)}`, "-p", `InaccessiblePaths=-${h.state}`, + "-p", "InaccessiblePaths=-/run/dbus", "-p", "InaccessiblePaths=-/run/snapd.socket", "-p", "InaccessiblePaths=-/run/snapd-snap.socket", + "-p", "InaccessiblePaths=-/run/systemd/journal", + "-p", `EnvironmentFile=${envFile}`, "-p", `WorkingDirectory=${s.cwd}`, + "-p", `RuntimeMaxSec=${left + 60}`, + ...(s.cpus ? ["-p", `AllowedCPUs=${s.cpus}`] : []), + ...(s.shell === "bash" ? ["/bin/bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", s.script] : ["/bin/sh", "-e", "-c", s.script]), + ]; + return new Promise((resolve) => { + const child = spawn("systemd-run", args, { stdio: ["ignore", "pipe", "pipe"] }); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + sh("systemctl", ["stop", `${unit}.service`]); + }, left * 1000); + pump(child.stdout!, s.onLine); + pump(child.stderr!, s.onLine); + const done = (code: number) => { + clearTimeout(timer); + rmSync(envFile, { force: true }); + resolve({ code: timedOut ? 124 : code, timedOut }); + }; + child.on("close", (code) => done(code ?? 1)); + child.on("error", (err) => { s.onLine(`##[error]${err.message}`); done(127); }); + }); + } + + cleanup(workDir: string) { + this.endProcesses(); + // A checkout per runner, each with its own node_modules: removed side by side, as one rm took 19s for 23 of them. + sh("sh", ["-c", 'for d in "$0"/* "$0"/.[!.]*; do [ -e "$d" ] && rm -rf -- "$d" & done; wait', workDir], { timeoutMs: 10 * 60_000 }); + rmSync(workDir, { recursive: true, force: true }); + const pg = Object.values(this.config.services)[0]; + if (this.pgRole && pg) this.dropRole(this.pgRole.role, pg.port); + rmSync(this.state, { recursive: true, force: true }); + } +} + +/** A tool pinned by version under `root//bin`, installed once (root-owned, readable) and shared by runs. */ +function installedTool(root: string, version: string, valid: RegExp, binName: string, install: (tmp: string) => Sh): string { + if (!valid.test(version)) throw new Error(`not a ${binName} version: ${version.slice(0, 40)}`); + const dir = path.join(root, version); + const bin = path.join(dir, "bin"); + const linkBunx = (b: string) => binName === "bun" && sh("ln", ["-sfn", "bun", path.join(b, "bunx")]); + if (existsSync(path.join(bin, binName))) { + if (binName === "bun" && !existsSync(path.join(bin, "bunx"))) linkBunx(bin); + return bin; + } + const tmp = `${dir}.tmp-${process.pid}`; + rmSync(tmp, { recursive: true, force: true }); + mkdirSync(root, { recursive: true }); + const r = install(tmp); + if (r.code !== 0 || !existsSync(path.join(tmp, "bin", binName))) throw new Error(`could not install ${binName} ${version}: ${r.err.slice(-300)}`); + linkBunx(path.join(tmp, "bin")); + sh("chmod", ["-R", "a+rX", tmp]); + try { renameSync(tmp, dir); } catch { rmSync(tmp, { recursive: true, force: true }); } + return bin; +} + +/** A runner's environment on the person's own machine: a temp HOME, no walls. */ +export class LocalExecutor implements Executor { + readonly sandboxed = false; + readonly slot = 0; + readonly user = os.userInfo().username; + readonly home: string; + readonly opt = null; + readonly os: JobOs; + constructor(readonly config: CiConfig, root?: string) { + this.home = root ?? mkdtempSync(path.join(os.tmpdir(), "castci-home-")); + this.os = process.platform === "darwin" ? "darwin" : "linux"; + } + basePath() { + return ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(":"); + } + private gitEnv() { return { HOME: this.home, PATH: this.basePath(), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0" }; } + git(args: string[], cwd: string, timeoutMs?: number) { + return guardedGit(([cmd, ...rest]) => sh(cmd!, rest, { cwd, timeoutMs, env: this.gitEnv() }), args); + } + gitAsync(args: string[], cwd: string, timeoutMs?: number) { + return guardedGitAsync(([cmd, ...rest]) => shAsync(cmd!, rest, { cwd, timeoutMs, env: this.gitEnv() }), args); + } + mkdirs(dirs: string[]) { + for (const d of dirs) mkdirSync(d, { recursive: true }); + } + asUser(argv: string[], io: { stdin?: string; stdout?: string; timeoutMs?: number } = {}): Sh { + return shFiles(argv[0]!, argv.slice(1), { ...io, env: { HOME: this.home, PATH: this.basePath() } }); + } + readRunFile(file: string, maxBytes = 8 * 1024 * 1024): string | null { + try { + const st = statSync(file, { throwIfNoEntry: false } as any); + if (!st || !st.isFile()) return null; + return readFileSync(file).subarray(0, maxBytes).toString("utf-8"); + } catch { + return null; + } + } + listRunFiles(dir: string, pattern: string): string[] { + const re = new RegExp(`^${pattern.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`); + try { + return readdirSync(dir).filter((f) => re.test(f) && statSync(path.join(dir, f)).isFile()); + } catch { + return []; + } + } + bunBin(version: string): string { + if (version === Bun.version) return path.dirname(process.execPath.endsWith("/bun") ? process.execPath : sh("which", ["bun"]).out || "/usr/local/bin/bun"); + return installedTool(path.join(os.homedir(), ".cache", "castci", "bun"), version, /^[0-9]+\.[0-9]+\.[0-9]+$/, "bun", (tmp) => + sh("bash", ["-c", 'curl -fsSL https://bun.sh/install | BUN_INSTALL="$1" bash -s "bun-v$2" >/dev/null 2>&1', "_", tmp, version], { timeoutMs: 5 * 60_000 })); + } + nodeBin(major: string): string { + const node = sh("node", ["--version"]).out.replace(/^v/, ""); + if (node.split(".")[0] !== major) throw new Error(`this machine has node ${node || "(none)"}, the job pins ${major}`); + return path.dirname(sh("which", ["node"]).out); + } + ownCopy(bin: string): string { + return bin; + } + runStep(s: StepSpec): Promise { + const left = Math.max(5, Math.ceil((s.deadline - Date.now()) / 1000)); + return new Promise((resolve) => { + const argv = s.shell === "bash" ? ["--noprofile", "--norc", "-e", "-o", "pipefail", "-c", s.script] : ["-e", "-c", s.script]; + const child = spawn(s.shell === "bash" ? "/bin/bash" : "/bin/sh", argv, { cwd: s.cwd, env: s.env, stdio: ["ignore", "pipe", "pipe"], detached: true }); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + try { process.kill(-child.pid!, "SIGKILL"); } catch {} + }, left * 1000); + pump(child.stdout!, s.onLine); + pump(child.stderr!, s.onLine); + child.on("close", (code) => { clearTimeout(timer); resolve({ code: timedOut ? 124 : (code ?? 1), timedOut }); }); + child.on("error", (err) => { clearTimeout(timer); s.onLine(`##[error]${err.message}`); resolve({ code: 127, timedOut: false }); }); + }); + } + cleanup(workDir: string) { + rmSync(workDir, { recursive: true, force: true }); + } +} + +/** A step's log, each line stamped and workflow commands shown the way a GitHub job log shows them. */ +export class JobLog { + private out: ReturnType; + constructor(readonly file: string, private masker: (t: string) => string) { + mkdirSync(path.dirname(file), { recursive: true }); + this.out = createWriteStream(file, { flags: "a" }); + } + line(text: string) { + for (const l of this.masker(text).split(/\r?\n/)) { + const m = /^::(group|endgroup|error|warning|notice|debug)(?: [^:]*)?::(.*)$/.exec(l); + this.out.write(`${new Date().toISOString()} ${m ? `##[${m[1]}]${m[2]}` : l}\n`); + } + } + close(): Promise { + return new Promise((resolve) => this.out.end(resolve)); + } +} diff --git a/packages/cli/src/hostWorkTicks.ts b/packages/cli/src/hostWorkTicks.ts new file mode 100644 index 0000000000..01f0493391 --- /dev/null +++ b/packages/cli/src/hostWorkTicks.ts @@ -0,0 +1,29 @@ +// The daemon's host work ticks: jobs a machine runs for codecast because a person +// or a role marker put it to that work. Each module loads on its first tick, and +// on a machine not set up for the job the tick reads one config and returns. + +export type HostWorkTickDeps = { + siteUrl: () => string | null; + token: () => string | null; + deviceId: () => string; + log: (line: string) => void; + logError: (what: string, err: Error) => void; +}; + +export function startHostWorkTicks(deps: HostWorkTickDeps): void { + const every = (ms: number, what: string, run: (opts: { siteUrl: string | null; token: string | null; deviceId: string; log: (line: string) => void }) => Promise) => { + setInterval(() => { + void run({ siteUrl: deps.siteUrl(), token: deps.token(), deviceId: deps.deviceId(), log: deps.log }) + .catch((err) => deps.logError(`${what} tick failed`, err as Error)); + }, ms); + }; + // Moments (learning-loop.md LL7): a machine that published a product's + // extractors claims what is due and runs them in the product's checkout. + every(60_000, "moments", async (opts) => (await import("./momentsHost.js")).daemonMomentsTick(opts)); + // The CI pool (ciPoolHost.ts): a host whose role marker puts it in a repository's CI pool watches main and claims + // each new sha through a lease in codecast; anywhere else the tick reads one missing file and returns. + every(30_000, "ci pool", async (opts) => (await import("./ciPoolHost.js")).daemonCiPoolTick(opts)); + // Agent reviews (agentReviewsHost.ts): a machine a person set to run reviews + // claims queued ones into its free slots and runs each in the dry-run harness. + every(30_000, "reviews", async (opts) => (await import("./agentReviewsHost.js")).daemonReviewsTick(opts)); +} diff --git a/packages/cli/src/momentsHost.test.ts b/packages/cli/src/momentsHost.test.ts index ac372a93ee..efd5364200 100644 --- a/packages/cli/src/momentsHost.test.ts +++ b/packages/cli/src/momentsHost.test.ts @@ -6,7 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { spawnSync } from "./proc.js"; -import { pruneHostMoments, runExtractor, shadowDir, tickMoments, type MomentClaim } from "./momentsHost.js"; +import { extractorLastWords, pruneHostMoments, runExtractor, shadowDir, tickMoments, type MomentClaim } from "./momentsHost.js"; import { readPublishSet } from "./momentsCommand.js"; let root: string; @@ -18,6 +18,7 @@ const EXTRACTOR = `// Conversations for the comms judge. // timeout: 20s const input = JSON.parse(await Bun.stdin.text()); if (input.subject === "boom") { console.error("no such thread"); process.exit(3); } +if (input.subject === "throws") { const e = new Error("connect ECONNREFUSED 127.0.0.1:5432"); (e as any).code = "ECONNREFUSED"; throw e; } console.log(JSON.stringify({ refs: [{ label: "thread", id: input.subject }], blocks: [{ type: "message", direction: "in", channel: "sms", at: input.at, sender: "Dana", body: "Tuesday?" }], @@ -108,6 +109,37 @@ describe("running an extractor", () => { const r = await runExtractor(claim("boom")); expect(r.error).toBe("the extractor exited 3: no such thread"); }, 60_000); + + test("an uncaught throw names its error, not bun's version footer", async () => { + const r = await runExtractor(claim("throws")); + expect(r.error).toBe('the extractor exited 1: error: connect ECONNREFUSED 127.0.0.1:5432 code: "ECONNREFUSED"'); + }, 60_000); +}); + +describe("an extractor's last words", () => { + test("keeps the error and its fields, drops the source excerpt, frames, blanks and footer", () => { + const stderr = [ + '1 | const e = new Error("db unreachable");', + " ^", + "error: db unreachable", + ' code: "ECONNRESET"', + "", + " at /tmp/a.ts:1:15", + "", + "Bun v1.4.4 (macOS arm64)", + "", + ].join("\n"); + expect(extractorLastWords(stderr)).toBe('error: db unreachable code: "ECONNRESET"'); + }); + + test("drops the workflow annotation bun adds under GitHub Actions", () => { + const stderr = 'error: db unreachable\n code: "ECONNRESET"\n::error file=a.ts,line=1,col=15,title=error: db unreachable::%0A at /tmp/a.ts:1:15\n'; + expect(extractorLastWords(stderr)).toBe('error: db unreachable code: "ECONNRESET"'); + }); + + test("plain stderr keeps its last lines", () => { + expect(extractorLastWords("[config] warming up\nno such thread\n")).toBe("[config] warming up no such thread"); + }); }); describe("one daemon pass", () => { diff --git a/packages/cli/src/momentsHost.ts b/packages/cli/src/momentsHost.ts index 5228493262..c35c94270e 100644 --- a/packages/cli/src/momentsHost.ts +++ b/packages/cli/src/momentsHost.ts @@ -72,6 +72,22 @@ export function bunPath(): string { return findOnPath("bun", [TOOL_PATH, path.join(os.homedir(), ".bun", "bin")].join(path.delimiter)) ?? "bun"; } +/** + * What a failed extractor said, in its own words. An uncaught throw in bun + * prints the source line and a caret, `error: `, the error's fields, + * its frames, blank lines and a `Bun vX (os)` footer, and under GitHub Actions a + * `::error file=…` workflow annotation; only the message and its fields say + * what went wrong, so the rest goes. Other stderr keeps its last lines. + */ +export function extractorLastWords(stderr: string): string { + const lines = stderr.split("\n").filter((l) => + l.trim() !== "" && !/^\s+at /.test(l) && !/^Bun v\d/.test(l) && !/^\s*\d+ \| /.test(l) && !/^\s*\^\s*$/.test(l) && !/^::[a-z-]+( |::)/.test(l)); + let thrown = -1; + lines.forEach((l, i) => { if (/^(error|[A-Za-z]*Error)(: |$)/.test(l)) thrown = i; }); + const words = thrown >= 0 ? lines.slice(thrown) : lines.slice(-3); + return words.map((l) => l.trim()).join(" ").slice(0, 400); +} + /** * Runs one extractor on one claim: `bun ` in the checkout with the * event on stdin. Its stdout is the moment; a non-zero exit, a timeout or @@ -102,8 +118,7 @@ export async function runExtractor(claim: MomentClaim, opts: { bun?: string } = child.on("close", (code: number | null) => { clearTimeout(timer); if (over) return resolve({ error: `the moment is over ${MOMENT_LIMITS.json_bytes} bytes`, version }); - // Its own words, not the stack under them: an error's frames (" at …") say where, its message says what. - if (code !== 0) return resolve({ error: `the extractor exited ${code}: ${err.trim().split("\n").filter((l) => !/^\s+at /.test(l)).slice(-3).join(" ").slice(0, 400)}`, version }); + if (code !== 0) return resolve({ error: `the extractor exited ${code}: ${extractorLastWords(err)}`, version }); resolve({ output: out, version }); }); child.stdin!.end(JSON.stringify(claim.input)); diff --git a/packages/cli/src/test-helpers/loopHold.ts b/packages/cli/src/test-helpers/loopHold.ts index 79179a25d4..19cbae802a 100644 --- a/packages/cli/src/test-helpers/loopHold.ts +++ b/packages/cli/src/test-helpers/loopHold.ts @@ -4,6 +4,11 @@ import { machineLoadFactor } from "./machineLoad.js"; // while an async job ran. A timer that fires late by more than its interval // means nothing else could run in between; the largest such gap is the // longest single hold. Shared by the priming and ingest timing tests. +// +// The probe stops only after one more tick fires once the job resolves. +// A job whose awaits finish within the first interval and whose synchronous +// work comes after the last one (a fast read, then the parse) would otherwise +// end before any tick, and its one long hold would go unmeasured. export async function measureLoopHold( fn: () => Promise, tickMs = 5, @@ -11,14 +16,17 @@ export async function measureLoopHold( let last = performance.now(); let maxGapMs = 0; let ticks = 0; + let onTick: (() => void) | undefined; const timer = setInterval(() => { const now = performance.now(); maxGapMs = Math.max(maxGapMs, now - last - tickMs); last = now; ticks++; + onTick?.(); }, tickMs); try { const result = await fn(); + await new Promise((resolve) => { onTick = resolve; }); return { result, maxGapMs, ticks }; } finally { clearInterval(timer); diff --git a/packages/convex/convex/_generated/api.d.ts b/packages/convex/convex/_generated/api.d.ts index 9bfc611ce4..c1c1be15c0 100644 --- a/packages/convex/convex/_generated/api.d.ts +++ b/packages/convex/convex/_generated/api.d.ts @@ -31,6 +31,7 @@ import type * as apnsProviderToken from "../apnsProviderToken.js"; import type * as apnsVoip from "../apnsVoip.js"; import type * as appConnections from "../appConnections.js"; import type * as artifactMarkdown from "../artifactMarkdown.js"; +import type * as artifactPageShell from "../artifactPageShell.js"; import type * as artifactPages from "../artifactPages.js"; import type * as artifacts from "../artifacts.js"; import type * as artifactsHttp from "../artifactsHttp.js"; @@ -62,6 +63,7 @@ import type * as buckets from "../buckets.js"; import type * as callChat from "../callChat.js"; import type * as callFace from "../callFace.js"; import type * as callGuests from "../callGuests.js"; +import type * as callReads from "../callReads.js"; import type * as callRecordings from "../callRecordings.js"; import type * as callRoomOwnership from "../callRoomOwnership.js"; import type * as callRoomSchema from "../callRoomSchema.js"; @@ -97,6 +99,7 @@ import type * as chatAgents from "../chatAgents.js"; import type * as chatDm from "../chatDm.js"; import type * as chatExcerpt from "../chatExcerpt.js"; import type * as chatHandoff from "../chatHandoff.js"; +import type * as chatMessageIds from "../chatMessageIds.js"; import type * as chatRounds from "../chatRounds.js"; import type * as chatSessionReplies from "../chatSessionReplies.js"; import type * as chatText from "../chatText.js"; @@ -105,6 +108,8 @@ import type * as chatWakePrompts from "../chatWakePrompts.js"; import type * as checkoutAsk from "../checkoutAsk.js"; import type * as checkouts from "../checkouts.js"; import type * as ciBackfill from "../ciBackfill.js"; +import type * as ciLeases from "../ciLeases.js"; +import type * as ciPool from "../ciPool.js"; import type * as ciRuns from "../ciRuns.js"; import type * as ciVerdicts from "../ciVerdicts.js"; import type * as cleanup from "../cleanup.js"; @@ -133,6 +138,7 @@ import type * as conversationSessionLookup from "../conversationSessionLookup.js import type * as conversations from "../conversations.js"; import type * as counters from "../counters.js"; import type * as crons from "../crons.js"; +import type * as daemonCommandClaimsSchema from "../daemonCommandClaimsSchema.js"; import type * as daemonCommandUtils from "../daemonCommandUtils.js"; import type * as daemonLogs from "../daemonLogs.js"; import type * as data from "../data.js"; @@ -193,6 +199,7 @@ import type * as envs from "../envs.js"; import type * as executionBindings from "../executionBindings.js"; import type * as expectations from "../expectations.js"; import type * as expectationsSchema from "../expectationsSchema.js"; +import type * as experiments from "../experiments.js"; import type * as externalEvents from "../externalEvents.js"; import type * as failedRunResume from "../failedRunResume.js"; import type * as favoriteViewWrites from "../favoriteViewWrites.js"; @@ -214,6 +221,7 @@ import type * as flowStops from "../flowStops.js"; import type * as flowVersions from "../flowVersions.js"; import type * as folderMove from "../folderMove.js"; import type * as folderSync from "../folderSync.js"; +import type * as foldersSchema from "../foldersSchema.js"; import type * as follow from "../follow.js"; import type * as forkCopy from "../forkCopy.js"; import type * as forkHandoffRepair from "../forkHandoffRepair.js"; @@ -222,6 +230,7 @@ import type * as gitActivity from "../gitActivity.js"; import type * as githubApi from "../githubApi.js"; import type * as githubApp from "../githubApp.js"; import type * as githubIssuesApi from "../githubIssuesApi.js"; +import type * as githubPrPayload from "../githubPrPayload.js"; import type * as githubWebhooks from "../githubWebhooks.js"; import type * as goals from "../goals.js"; import type * as googleOAuth from "../googleOAuth.js"; @@ -241,6 +250,7 @@ import type * as inboxFilters from "../inboxFilters.js"; import type * as inboxHides from "../inboxHides.js"; import type * as inboxProjection from "../inboxProjection.js"; import type * as ingest from "../ingest.js"; +import type * as ingestDeploys from "../ingestDeploys.js"; import type * as ingestHttp from "../ingestHttp.js"; import type * as ingestPromotions from "../ingestPromotions.js"; import type * as ingestSchema from "../ingestSchema.js"; @@ -289,6 +299,8 @@ import type * as lib_castMachineAws from "../lib/castMachineAws.js"; import type * as lib_castMotion from "../lib/castMotion.js"; import type * as lib_castPlayer from "../lib/castPlayer.js"; import type * as lib_changeApprovalCards from "../lib/changeApprovalCards.js"; +import type * as lib_changeApprovalReads from "../lib/changeApprovalReads.js"; +import type * as lib_changeApprovalRecordValidator from "../lib/changeApprovalRecordValidator.js"; import type * as lib_changeApprovalRows from "../lib/changeApprovalRows.js"; import type * as lib_changeGuideValidator from "../lib/changeGuideValidator.js"; import type * as lib_changesAccess from "../lib/changesAccess.js"; @@ -302,6 +314,8 @@ import type * as lib_chatReadState from "../lib/chatReadState.js"; import type * as lib_chatRoundValidator from "../lib/chatRoundValidator.js"; import type * as lib_chatRows from "../lib/chatRows.js"; import type * as lib_chatWakeIds from "../lib/chatWakeIds.js"; +import type * as lib_checkoutRepository from "../lib/checkoutRepository.js"; +import type * as lib_ciRoutes from "../lib/ciRoutes.js"; import type * as lib_ciRunRead from "../lib/ciRunRead.js"; import type * as lib_claimFrontier from "../lib/claimFrontier.js"; import type * as lib_cliErrorStatus from "../lib/cliErrorStatus.js"; @@ -320,6 +334,7 @@ import type * as lib_conversationRows from "../lib/conversationRows.js"; import type * as lib_conversationVisibility from "../lib/conversationVisibility.js"; import type * as lib_convexFieldNames from "../lib/convexFieldNames.js"; import type * as lib_daemonCommandClaim from "../lib/daemonCommandClaim.js"; +import type * as lib_daemonCommandDeviceClaims from "../lib/daemonCommandDeviceClaims.js"; import type * as lib_daemonLiveness from "../lib/daemonLiveness.js"; import type * as lib_decisionAccess from "../lib/decisionAccess.js"; import type * as lib_decisionAudience from "../lib/decisionAudience.js"; @@ -350,6 +365,7 @@ import type * as lib_embeddings from "../lib/embeddings.js"; import type * as lib_enrollHttp from "../lib/enrollHttp.js"; import type * as lib_eventFilterValidator from "../lib/eventFilterValidator.js"; import type * as lib_expectationsApply from "../lib/expectationsApply.js"; +import type * as lib_experiments from "../lib/experiments.js"; import type * as lib_externalAuthor from "../lib/externalAuthor.js"; import type * as lib_fileChangeBody from "../lib/fileChangeBody.js"; import type * as lib_findingStanding from "../lib/findingStanding.js"; @@ -374,6 +390,7 @@ import type * as lib_hostRecovery from "../lib/hostRecovery.js"; import type * as lib_htmlText from "../lib/htmlText.js"; import type * as lib_httpRateLimit from "../lib/httpRateLimit.js"; import type * as lib_huddleGrace from "../lib/huddleGrace.js"; +import type * as lib_inProcessTakeover from "../lib/inProcessTakeover.js"; import type * as lib_inboxOwners from "../lib/inboxOwners.js"; import type * as lib_ingestGroups from "../lib/ingestGroups.js"; import type * as lib_ingestPayloads from "../lib/ingestPayloads.js"; @@ -441,8 +458,11 @@ import type * as lib_orgScope from "../lib/orgScope.js"; import type * as lib_orgSessionFiling from "../lib/orgSessionFiling.js"; import type * as lib_orgTemplateBindNote from "../lib/orgTemplateBindNote.js"; import type * as lib_originatorChain from "../lib/originatorChain.js"; +import type * as lib_ownedChildRows from "../lib/ownedChildRows.js"; import type * as lib_ownerDevice from "../lib/ownerDevice.js"; +import type * as lib_ownersAudit from "../lib/ownersAudit.js"; import type * as lib_ownersChange from "../lib/ownersChange.js"; +import type * as lib_ownersOrigin from "../lib/ownersOrigin.js"; import type * as lib_pageAppValidator from "../lib/pageAppValidator.js"; import type * as lib_pageReaders from "../lib/pageReaders.js"; import type * as lib_pageViews from "../lib/pageViews.js"; @@ -465,14 +485,22 @@ import type * as lib_predictionTargets from "../lib/predictionTargets.js"; import type * as lib_predictionValidators from "../lib/predictionValidators.js"; import type * as lib_presence from "../lib/presence.js"; import type * as lib_priorityAccess from "../lib/priorityAccess.js"; +import type * as lib_priorityCard from "../lib/priorityCard.js"; +import type * as lib_priorityCardAccess from "../lib/priorityCardAccess.js"; +import type * as lib_priorityCardApply from "../lib/priorityCardApply.js"; +import type * as lib_priorityCardPass from "../lib/priorityCardPass.js"; import type * as lib_priorityClassifier from "../lib/priorityClassifier.js"; import type * as lib_priorityClassifierHook from "../lib/priorityClassifierHook.js"; +import type * as lib_priorityFixSessions from "../lib/priorityFixSessions.js"; import type * as lib_priorityGroup from "../lib/priorityGroup.js"; +import type * as lib_priorityInsert from "../lib/priorityInsert.js"; import type * as lib_priorityLinks from "../lib/priorityLinks.js"; import type * as lib_priorityPass from "../lib/priorityPass.js"; import type * as lib_priorityPassParse from "../lib/priorityPassParse.js"; import type * as lib_priorityPassSchedule from "../lib/priorityPassSchedule.js"; import type * as lib_priorityPassSteps from "../lib/priorityPassSteps.js"; +import type * as lib_priorityRecheck from "../lib/priorityRecheck.js"; +import type * as lib_priorityRecheckPrompt from "../lib/priorityRecheckPrompt.js"; import type * as lib_priorityRoutes from "../lib/priorityRoutes.js"; import type * as lib_prioritySessionCount from "../lib/prioritySessionCount.js"; import type * as lib_prioritySessionVisibility from "../lib/prioritySessionVisibility.js"; @@ -494,6 +522,7 @@ import type * as lib_recall from "../lib/recall.js"; import type * as lib_recordingTranscription from "../lib/recordingTranscription.js"; import type * as lib_registerOnly from "../lib/registerOnly.js"; import type * as lib_regretRead from "../lib/regretRead.js"; +import type * as lib_reparentBatch from "../lib/reparentBatch.js"; import type * as lib_replayCap from "../lib/replayCap.js"; import type * as lib_replayChunks from "../lib/replayChunks.js"; import type * as lib_replayImport from "../lib/replayImport.js"; @@ -504,6 +533,7 @@ import type * as lib_replayWrites from "../lib/replayWrites.js"; import type * as lib_repoCacheScope from "../lib/repoCacheScope.js"; import type * as lib_repoRefreshSpec from "../lib/repoRefreshSpec.js"; import type * as lib_repoSearch from "../lib/repoSearch.js"; +import type * as lib_reportsTo from "../lib/reportsTo.js"; import type * as lib_requireUser from "../lib/requireUser.js"; import type * as lib_reviewAnswered from "../lib/reviewAnswered.js"; import type * as lib_roleCharter from "../lib/roleCharter.js"; @@ -521,6 +551,8 @@ import type * as lib_runEnd from "../lib/runEnd.js"; import type * as lib_runGraph from "../lib/runGraph.js"; import type * as lib_runLog from "../lib/runLog.js"; import type * as lib_runnerDevice from "../lib/runnerDevice.js"; +import type * as lib_runnerNames from "../lib/runnerNames.js"; +import type * as lib_runsInParentStamp from "../lib/runsInParentStamp.js"; import type * as lib_sanitize from "../lib/sanitize.js"; import type * as lib_screenRecordingSent from "../lib/screenRecordingSent.js"; import type * as lib_scribe from "../lib/scribe.js"; @@ -545,11 +577,15 @@ import type * as lib_sessionNotify from "../lib/sessionNotify.js"; import type * as lib_sessionOwnerRoutes from "../lib/sessionOwnerRoutes.js"; import type * as lib_sessionPriority from "../lib/sessionPriority.js"; import type * as lib_sessionQueue from "../lib/sessionQueue.js"; +import type * as lib_sessionSendDaily from "../lib/sessionSendDaily.js"; +import type * as lib_sessionSettle from "../lib/sessionSettle.js"; import type * as lib_sessionStarts from "../lib/sessionStarts.js"; import type * as lib_sessionTell from "../lib/sessionTell.js"; +import type * as lib_sessionWatch from "../lib/sessionWatch.js"; import type * as lib_sessionsTally from "../lib/sessionsTally.js"; import type * as lib_shareToken from "../lib/shareToken.js"; import type * as lib_sharedCallMedia from "../lib/sharedCallMedia.js"; +import type * as lib_shipTrack from "../lib/shipTrack.js"; import type * as lib_signalPlacedValidator from "../lib/signalPlacedValidator.js"; import type * as lib_signalPlacement from "../lib/signalPlacement.js"; import type * as lib_siteUrl from "../lib/siteUrl.js"; @@ -576,6 +612,7 @@ import type * as lib_suggestionInputRanking from "../lib/suggestionInputRanking. import type * as lib_suggestionOutcomeWrite from "../lib/suggestionOutcomeWrite.js"; import type * as lib_superseded from "../lib/superseded.js"; import type * as lib_switchCommands from "../lib/switchCommands.js"; +import type * as lib_taskEdges from "../lib/taskEdges.js"; import type * as lib_taskExecution from "../lib/taskExecution.js"; import type * as lib_taskGraph from "../lib/taskGraph.js"; import type * as lib_taskHistory from "../lib/taskHistory.js"; @@ -597,6 +634,7 @@ import type * as lib_teamReadKeyHttp from "../lib/teamReadKeyHttp.js"; import type * as lib_teamRepositories from "../lib/teamRepositories.js"; import type * as lib_teamSeats from "../lib/teamSeats.js"; import type * as lib_teamSessionAnswer from "../lib/teamSessionAnswer.js"; +import type * as lib_templateHost from "../lib/templateHost.js"; import type * as lib_tokenHttp from "../lib/tokenHttp.js"; import type * as lib_tokenRefresh from "../lib/tokenRefresh.js"; import type * as lib_trialDecision from "../lib/trialDecision.js"; @@ -670,10 +708,13 @@ import type * as meetingBots from "../meetingBots.js"; import type * as meetingBotsHttp from "../meetingBotsHttp.js"; import type * as meetingCalendar from "../meetingCalendar.js"; import type * as messageFeed from "../messageFeed.js"; +import type * as messageLines from "../messageLines.js"; import type * as messageViewContracts from "../messageViewContracts.js"; import type * as messages from "../messages.js"; import type * as metricAlerts from "../metricAlerts.js"; +import type * as metricHistory from "../metricHistory.js"; import type * as metrics from "../metrics.js"; +import type * as migrationFolderHeld from "../migrationFolderHeld.js"; import type * as migrations from "../migrations.js"; import type * as modCalls from "../modCalls.js"; import type * as modLocal from "../modLocal.js"; @@ -741,6 +782,7 @@ import type * as permissionRules from "../permissionRules.js"; import type * as permissions from "../permissions.js"; import type * as personalDeploysBackfill from "../personalDeploysBackfill.js"; import type * as pipelines from "../pipelines.js"; +import type * as planFilePurge from "../planFilePurge.js"; import type * as planLog from "../planLog.js"; import type * as planTaskProjectBackfill from "../planTaskProjectBackfill.js"; import type * as planTemplates from "../planTemplates.js"; @@ -748,6 +790,7 @@ import type * as plans from "../plans.js"; import type * as prCli from "../prCli.js"; import type * as prDetails from "../prDetails.js"; import type * as prGuides from "../prGuides.js"; +import type * as prMergeState from "../prMergeState.js"; import type * as prShepherd from "../prShepherd.js"; import type * as predictions from "../predictions.js"; import type * as presencePolicy from "../presencePolicy.js"; @@ -755,8 +798,11 @@ import type * as presenceState from "../presenceState.js"; import type * as principalViewRevisions from "../principalViewRevisions.js"; import type * as priorities from "../priorities.js"; import type * as prioritiesSchema from "../prioritiesSchema.js"; +import type * as priorityCardPost from "../priorityCardPost.js"; import type * as priorityClassifier from "../priorityClassifier.js"; import type * as priorityClassifierEval from "../priorityClassifierEval.js"; +import type * as priorityCreate from "../priorityCreate.js"; +import type * as priorityFixSessionBackfill from "../priorityFixSessionBackfill.js"; import type * as priorityHistory from "../priorityHistory.js"; import type * as priorityPassEval from "../priorityPassEval.js"; import type * as priorityPassInputs from "../priorityPassInputs.js"; @@ -764,7 +810,9 @@ import type * as priorityPassRun from "../priorityPassRun.js"; import type * as priorityPassSchedule from "../priorityPassSchedule.js"; import type * as priorityPassSessions from "../priorityPassSessions.js"; import type * as priorityPassSweep from "../priorityPassSweep.js"; +import type * as priorityRanks from "../priorityRanks.js"; import type * as priorityRead from "../priorityRead.js"; +import type * as priorityRecheck from "../priorityRecheck.js"; import type * as priorityStepKeyBackfill from "../priorityStepKeyBackfill.js"; import type * as priorityWrite from "../priorityWrite.js"; import type * as privacy from "../privacy.js"; @@ -844,6 +892,7 @@ import type * as sessionQuerySearch from "../sessionQuerySearch.js"; import type * as sessionQuerySuggest from "../sessionQuerySuggest.js"; import type * as sessionReads from "../sessionReads.js"; import type * as sessionRelease from "../sessionRelease.js"; +import type * as sessionSendBackfill from "../sessionSendBackfill.js"; import type * as sessionThreads from "../sessionThreads.js"; import type * as sessionTransfer from "../sessionTransfer.js"; import type * as sessionVisibilityPreview from "../sessionVisibilityPreview.js"; @@ -874,6 +923,7 @@ import type * as sources_sentryShape from "../sources/sentryShape.js"; import type * as sources_vendorProjects from "../sources/vendorProjects.js"; import type * as sources_vendorReplay from "../sources/vendorReplay.js"; import type * as spawn from "../spawn.js"; +import type * as sshHost from "../sshHost.js"; import type * as startQueuesSchema from "../startQueuesSchema.js"; import type * as storyMode from "../storyMode.js"; import type * as strandedHandoffs from "../strandedHandoffs.js"; @@ -980,6 +1030,7 @@ declare const fullApi: ApiFromModules<{ apnsVoip: typeof apnsVoip; appConnections: typeof appConnections; artifactMarkdown: typeof artifactMarkdown; + artifactPageShell: typeof artifactPageShell; artifactPages: typeof artifactPages; artifacts: typeof artifacts; artifactsHttp: typeof artifactsHttp; @@ -1011,6 +1062,7 @@ declare const fullApi: ApiFromModules<{ callChat: typeof callChat; callFace: typeof callFace; callGuests: typeof callGuests; + callReads: typeof callReads; callRecordings: typeof callRecordings; callRoomOwnership: typeof callRoomOwnership; callRoomSchema: typeof callRoomSchema; @@ -1046,6 +1098,7 @@ declare const fullApi: ApiFromModules<{ chatDm: typeof chatDm; chatExcerpt: typeof chatExcerpt; chatHandoff: typeof chatHandoff; + chatMessageIds: typeof chatMessageIds; chatRounds: typeof chatRounds; chatSessionReplies: typeof chatSessionReplies; chatText: typeof chatText; @@ -1054,6 +1107,8 @@ declare const fullApi: ApiFromModules<{ checkoutAsk: typeof checkoutAsk; checkouts: typeof checkouts; ciBackfill: typeof ciBackfill; + ciLeases: typeof ciLeases; + ciPool: typeof ciPool; ciRuns: typeof ciRuns; ciVerdicts: typeof ciVerdicts; cleanup: typeof cleanup; @@ -1082,6 +1137,7 @@ declare const fullApi: ApiFromModules<{ conversations: typeof conversations; counters: typeof counters; crons: typeof crons; + daemonCommandClaimsSchema: typeof daemonCommandClaimsSchema; daemonCommandUtils: typeof daemonCommandUtils; daemonLogs: typeof daemonLogs; data: typeof data; @@ -1142,6 +1198,7 @@ declare const fullApi: ApiFromModules<{ executionBindings: typeof executionBindings; expectations: typeof expectations; expectationsSchema: typeof expectationsSchema; + experiments: typeof experiments; externalEvents: typeof externalEvents; failedRunResume: typeof failedRunResume; favoriteViewWrites: typeof favoriteViewWrites; @@ -1163,6 +1220,7 @@ declare const fullApi: ApiFromModules<{ flowVersions: typeof flowVersions; folderMove: typeof folderMove; folderSync: typeof folderSync; + foldersSchema: typeof foldersSchema; follow: typeof follow; forkCopy: typeof forkCopy; forkHandoffRepair: typeof forkHandoffRepair; @@ -1171,6 +1229,7 @@ declare const fullApi: ApiFromModules<{ githubApi: typeof githubApi; githubApp: typeof githubApp; githubIssuesApi: typeof githubIssuesApi; + githubPrPayload: typeof githubPrPayload; githubWebhooks: typeof githubWebhooks; goals: typeof goals; googleOAuth: typeof googleOAuth; @@ -1190,6 +1249,7 @@ declare const fullApi: ApiFromModules<{ inboxHides: typeof inboxHides; inboxProjection: typeof inboxProjection; ingest: typeof ingest; + ingestDeploys: typeof ingestDeploys; ingestHttp: typeof ingestHttp; ingestPromotions: typeof ingestPromotions; ingestSchema: typeof ingestSchema; @@ -1238,6 +1298,8 @@ declare const fullApi: ApiFromModules<{ "lib/castMotion": typeof lib_castMotion; "lib/castPlayer": typeof lib_castPlayer; "lib/changeApprovalCards": typeof lib_changeApprovalCards; + "lib/changeApprovalReads": typeof lib_changeApprovalReads; + "lib/changeApprovalRecordValidator": typeof lib_changeApprovalRecordValidator; "lib/changeApprovalRows": typeof lib_changeApprovalRows; "lib/changeGuideValidator": typeof lib_changeGuideValidator; "lib/changesAccess": typeof lib_changesAccess; @@ -1251,6 +1313,8 @@ declare const fullApi: ApiFromModules<{ "lib/chatRoundValidator": typeof lib_chatRoundValidator; "lib/chatRows": typeof lib_chatRows; "lib/chatWakeIds": typeof lib_chatWakeIds; + "lib/checkoutRepository": typeof lib_checkoutRepository; + "lib/ciRoutes": typeof lib_ciRoutes; "lib/ciRunRead": typeof lib_ciRunRead; "lib/claimFrontier": typeof lib_claimFrontier; "lib/cliErrorStatus": typeof lib_cliErrorStatus; @@ -1269,6 +1333,7 @@ declare const fullApi: ApiFromModules<{ "lib/conversationVisibility": typeof lib_conversationVisibility; "lib/convexFieldNames": typeof lib_convexFieldNames; "lib/daemonCommandClaim": typeof lib_daemonCommandClaim; + "lib/daemonCommandDeviceClaims": typeof lib_daemonCommandDeviceClaims; "lib/daemonLiveness": typeof lib_daemonLiveness; "lib/decisionAccess": typeof lib_decisionAccess; "lib/decisionAudience": typeof lib_decisionAudience; @@ -1299,6 +1364,7 @@ declare const fullApi: ApiFromModules<{ "lib/enrollHttp": typeof lib_enrollHttp; "lib/eventFilterValidator": typeof lib_eventFilterValidator; "lib/expectationsApply": typeof lib_expectationsApply; + "lib/experiments": typeof lib_experiments; "lib/externalAuthor": typeof lib_externalAuthor; "lib/fileChangeBody": typeof lib_fileChangeBody; "lib/findingStanding": typeof lib_findingStanding; @@ -1323,6 +1389,7 @@ declare const fullApi: ApiFromModules<{ "lib/htmlText": typeof lib_htmlText; "lib/httpRateLimit": typeof lib_httpRateLimit; "lib/huddleGrace": typeof lib_huddleGrace; + "lib/inProcessTakeover": typeof lib_inProcessTakeover; "lib/inboxOwners": typeof lib_inboxOwners; "lib/ingestGroups": typeof lib_ingestGroups; "lib/ingestPayloads": typeof lib_ingestPayloads; @@ -1390,8 +1457,11 @@ declare const fullApi: ApiFromModules<{ "lib/orgSessionFiling": typeof lib_orgSessionFiling; "lib/orgTemplateBindNote": typeof lib_orgTemplateBindNote; "lib/originatorChain": typeof lib_originatorChain; + "lib/ownedChildRows": typeof lib_ownedChildRows; "lib/ownerDevice": typeof lib_ownerDevice; + "lib/ownersAudit": typeof lib_ownersAudit; "lib/ownersChange": typeof lib_ownersChange; + "lib/ownersOrigin": typeof lib_ownersOrigin; "lib/pageAppValidator": typeof lib_pageAppValidator; "lib/pageReaders": typeof lib_pageReaders; "lib/pageViews": typeof lib_pageViews; @@ -1414,14 +1484,22 @@ declare const fullApi: ApiFromModules<{ "lib/predictionValidators": typeof lib_predictionValidators; "lib/presence": typeof lib_presence; "lib/priorityAccess": typeof lib_priorityAccess; + "lib/priorityCard": typeof lib_priorityCard; + "lib/priorityCardAccess": typeof lib_priorityCardAccess; + "lib/priorityCardApply": typeof lib_priorityCardApply; + "lib/priorityCardPass": typeof lib_priorityCardPass; "lib/priorityClassifier": typeof lib_priorityClassifier; "lib/priorityClassifierHook": typeof lib_priorityClassifierHook; + "lib/priorityFixSessions": typeof lib_priorityFixSessions; "lib/priorityGroup": typeof lib_priorityGroup; + "lib/priorityInsert": typeof lib_priorityInsert; "lib/priorityLinks": typeof lib_priorityLinks; "lib/priorityPass": typeof lib_priorityPass; "lib/priorityPassParse": typeof lib_priorityPassParse; "lib/priorityPassSchedule": typeof lib_priorityPassSchedule; "lib/priorityPassSteps": typeof lib_priorityPassSteps; + "lib/priorityRecheck": typeof lib_priorityRecheck; + "lib/priorityRecheckPrompt": typeof lib_priorityRecheckPrompt; "lib/priorityRoutes": typeof lib_priorityRoutes; "lib/prioritySessionCount": typeof lib_prioritySessionCount; "lib/prioritySessionVisibility": typeof lib_prioritySessionVisibility; @@ -1443,6 +1521,7 @@ declare const fullApi: ApiFromModules<{ "lib/recordingTranscription": typeof lib_recordingTranscription; "lib/registerOnly": typeof lib_registerOnly; "lib/regretRead": typeof lib_regretRead; + "lib/reparentBatch": typeof lib_reparentBatch; "lib/replayCap": typeof lib_replayCap; "lib/replayChunks": typeof lib_replayChunks; "lib/replayImport": typeof lib_replayImport; @@ -1453,6 +1532,7 @@ declare const fullApi: ApiFromModules<{ "lib/repoCacheScope": typeof lib_repoCacheScope; "lib/repoRefreshSpec": typeof lib_repoRefreshSpec; "lib/repoSearch": typeof lib_repoSearch; + "lib/reportsTo": typeof lib_reportsTo; "lib/requireUser": typeof lib_requireUser; "lib/reviewAnswered": typeof lib_reviewAnswered; "lib/roleCharter": typeof lib_roleCharter; @@ -1470,6 +1550,8 @@ declare const fullApi: ApiFromModules<{ "lib/runGraph": typeof lib_runGraph; "lib/runLog": typeof lib_runLog; "lib/runnerDevice": typeof lib_runnerDevice; + "lib/runnerNames": typeof lib_runnerNames; + "lib/runsInParentStamp": typeof lib_runsInParentStamp; "lib/sanitize": typeof lib_sanitize; "lib/screenRecordingSent": typeof lib_screenRecordingSent; "lib/scribe": typeof lib_scribe; @@ -1494,11 +1576,15 @@ declare const fullApi: ApiFromModules<{ "lib/sessionOwnerRoutes": typeof lib_sessionOwnerRoutes; "lib/sessionPriority": typeof lib_sessionPriority; "lib/sessionQueue": typeof lib_sessionQueue; + "lib/sessionSendDaily": typeof lib_sessionSendDaily; + "lib/sessionSettle": typeof lib_sessionSettle; "lib/sessionStarts": typeof lib_sessionStarts; "lib/sessionTell": typeof lib_sessionTell; + "lib/sessionWatch": typeof lib_sessionWatch; "lib/sessionsTally": typeof lib_sessionsTally; "lib/shareToken": typeof lib_shareToken; "lib/sharedCallMedia": typeof lib_sharedCallMedia; + "lib/shipTrack": typeof lib_shipTrack; "lib/signalPlacedValidator": typeof lib_signalPlacedValidator; "lib/signalPlacement": typeof lib_signalPlacement; "lib/siteUrl": typeof lib_siteUrl; @@ -1525,6 +1611,7 @@ declare const fullApi: ApiFromModules<{ "lib/suggestionOutcomeWrite": typeof lib_suggestionOutcomeWrite; "lib/superseded": typeof lib_superseded; "lib/switchCommands": typeof lib_switchCommands; + "lib/taskEdges": typeof lib_taskEdges; "lib/taskExecution": typeof lib_taskExecution; "lib/taskGraph": typeof lib_taskGraph; "lib/taskHistory": typeof lib_taskHistory; @@ -1546,6 +1633,7 @@ declare const fullApi: ApiFromModules<{ "lib/teamRepositories": typeof lib_teamRepositories; "lib/teamSeats": typeof lib_teamSeats; "lib/teamSessionAnswer": typeof lib_teamSessionAnswer; + "lib/templateHost": typeof lib_templateHost; "lib/tokenHttp": typeof lib_tokenHttp; "lib/tokenRefresh": typeof lib_tokenRefresh; "lib/trialDecision": typeof lib_trialDecision; @@ -1619,10 +1707,13 @@ declare const fullApi: ApiFromModules<{ meetingBotsHttp: typeof meetingBotsHttp; meetingCalendar: typeof meetingCalendar; messageFeed: typeof messageFeed; + messageLines: typeof messageLines; messageViewContracts: typeof messageViewContracts; messages: typeof messages; metricAlerts: typeof metricAlerts; + metricHistory: typeof metricHistory; metrics: typeof metrics; + migrationFolderHeld: typeof migrationFolderHeld; migrations: typeof migrations; modCalls: typeof modCalls; modLocal: typeof modLocal; @@ -1690,6 +1781,7 @@ declare const fullApi: ApiFromModules<{ permissions: typeof permissions; personalDeploysBackfill: typeof personalDeploysBackfill; pipelines: typeof pipelines; + planFilePurge: typeof planFilePurge; planLog: typeof planLog; planTaskProjectBackfill: typeof planTaskProjectBackfill; planTemplates: typeof planTemplates; @@ -1697,6 +1789,7 @@ declare const fullApi: ApiFromModules<{ prCli: typeof prCli; prDetails: typeof prDetails; prGuides: typeof prGuides; + prMergeState: typeof prMergeState; prShepherd: typeof prShepherd; predictions: typeof predictions; presencePolicy: typeof presencePolicy; @@ -1704,8 +1797,11 @@ declare const fullApi: ApiFromModules<{ principalViewRevisions: typeof principalViewRevisions; priorities: typeof priorities; prioritiesSchema: typeof prioritiesSchema; + priorityCardPost: typeof priorityCardPost; priorityClassifier: typeof priorityClassifier; priorityClassifierEval: typeof priorityClassifierEval; + priorityCreate: typeof priorityCreate; + priorityFixSessionBackfill: typeof priorityFixSessionBackfill; priorityHistory: typeof priorityHistory; priorityPassEval: typeof priorityPassEval; priorityPassInputs: typeof priorityPassInputs; @@ -1713,7 +1809,9 @@ declare const fullApi: ApiFromModules<{ priorityPassSchedule: typeof priorityPassSchedule; priorityPassSessions: typeof priorityPassSessions; priorityPassSweep: typeof priorityPassSweep; + priorityRanks: typeof priorityRanks; priorityRead: typeof priorityRead; + priorityRecheck: typeof priorityRecheck; priorityStepKeyBackfill: typeof priorityStepKeyBackfill; priorityWrite: typeof priorityWrite; privacy: typeof privacy; @@ -1793,6 +1891,7 @@ declare const fullApi: ApiFromModules<{ sessionQuerySuggest: typeof sessionQuerySuggest; sessionReads: typeof sessionReads; sessionRelease: typeof sessionRelease; + sessionSendBackfill: typeof sessionSendBackfill; sessionThreads: typeof sessionThreads; sessionTransfer: typeof sessionTransfer; sessionVisibilityPreview: typeof sessionVisibilityPreview; @@ -1823,6 +1922,7 @@ declare const fullApi: ApiFromModules<{ "sources/vendorProjects": typeof sources_vendorProjects; "sources/vendorReplay": typeof sources_vendorReplay; spawn: typeof spawn; + sshHost: typeof sshHost; startQueuesSchema: typeof startQueuesSchema; storyMode: typeof storyMode; strandedHandoffs: typeof strandedHandoffs; diff --git a/packages/convex/convex/accountPool.test.ts b/packages/convex/convex/accountPool.test.ts index 6390aa86c6..7baf1a202e 100644 --- a/packages/convex/convex/accountPool.test.ts +++ b/packages/convex/convex/accountPool.test.ts @@ -338,6 +338,21 @@ describe("the personal pool: every account on every one of the owner's machines" expect(db._tables.account_shares).toHaveLength(1); }); + test("a machine reserved for CI gets nothing sealed to it, and is told to drop the copies it holds", async () => { + const db = fixture(); + await beat(db); + const shareId = db._tables.account_shares[0]._id; + await store(db, shareId, ["ashot-host", "line-host"]); + expect((await poolFor(db, ASHOT, "ashot-host")).copies).toHaveLength(1); + db._tables.devices.find((d: any) => d.device_id === "ashot-host").reserved_for = "ci: codecast-sh/codecast pool"; + expect(await targetsOf(db)).toEqual(["line-host"]); + expect((await poolFor(db, ASHOT, "ashot-host")).copies).toEqual([]); + // Any other reservation keeps the account: only "ci:" opts a machine out. + db._tables.devices.find((d: any) => d.device_id === "ashot-host").reserved_for = "evals"; + expect(await targetsOf(db)).toEqual(["ashot-host", "line-host"]); + expect((await poolFor(db, ASHOT, "ashot-host")).copies).toHaveLength(1); + }); + test("a host's pool copies never become rows of their own", async () => { const db = fixture(); db._tables.devices.find((d: any) => d.device_id === "ashot-host").cc_accounts = { diff --git a/packages/convex/convex/changeApprovals.landing.test.ts b/packages/convex/convex/changeApprovals.landing.test.ts new file mode 100644 index 0000000000..09407d1781 --- /dev/null +++ b/packages/convex/convex/changeApprovals.landing.test.ts @@ -0,0 +1,212 @@ +// Codecast's `approval` status on a run's landing commit, with no pull request (ct-100350 "landing"): the same rule +// read from GitHub's comparison of the default branch with the commit, keyed by the run. The rule itself and the +// pull request's status are changeApprovals.test.ts. +import { describe, expect, test } from "bun:test"; +import { getFunctionName } from "convex/server"; +import { makeFakeDb } from "./testDb"; +import { evaluateLanding, settle, sweepLandings } from "./changeApprovals"; +import { actionCtx, gh, github, installation, LAND_PATCH, MB, REPO, useMockedGitHub } from "./changeApprovals.testkit"; +import { approvalStampFor, claimPress, settleCardApproval } from "./lib/changeApprovalRows"; + +useMockedGitHub(); + +describe("a landing commit, with no pull request", () => { + const SQUASH = "5".repeat(40); + const CARRIED = "6".repeat(40); + const JUDGED = "outreach/line/change/land.cast"; + const reviewed = (mechanism: boolean, head = SQUASH) => ({ node_statuses: [{ node_id: "review", status: "completed", session_id: "rev", started_at: 2 }], review_verdict: { node_id: "review", verdict: "ship", head_sha: head, mechanism, at: 3, attempt: 1 } }); + const landingRun = (over: Record = {}) => ({ + _id: "run1", user_id: "host", team_id: "team1", status: "running", created_at: 1, task_id: "t1", primary_conversation_id: "c_log", + landing: { repository: REPO, first_sha: SQUASH, sha: SQUASH, at: 1 }, ...reviewed(false), ...over, + }); + const users = [{ _id: "u_jason", name: "Jason Benn" }, { _id: "u_ashot", name: "Ashot" }, { _id: "host", name: "Host" }]; + const world = (tables: Record = {}) => { + const scheduled: Array<{ name: string; args: any }> = []; + const db = makeFakeDb(structuredClone({ + github_app_installations: [installation], pull_requests: [], change_approvals: [], users, team_memberships: users.map((u, i) => ({ _id: `m${i}`, team_id: "team1", user_id: u._id })), + conversations: [{ _id: "c_log", session_id: "wf-run1", user_id: "host", title: "Change" }], anchors: [], session_decisions: [], decision_inbox: [], task_comments: [], pending_messages: [], counters: [], + tasks: [{ _id: "t1", title: "Edit land", user_id: "host" }], workflow_runs: [landingRun()], ...tables, + })); + const ctx = { db, scheduler: { runAfter: async (_ms: number, ref: any, args: any) => { scheduled.push({ name: getFunctionName(ref), args }); } } }; + return { db, ctx, scheduled, run: () => db._tables.workflow_runs[0] }; + }; + const people = { title: "Edit land", area_owner: { user_id: "u_ashot", name: "Ashot" }, engineers: [{ user_id: "u_jason", name: "Jason" }] }; + const args = { repository: REPO, run_id: "run1", head_sha: SQUASH, judged: [JUDGED], key: "k1", whole_key: "w1", people }; + const cards = (db: any) => db._tables.session_decisions.filter((d: any) => d.approval_card); + + /** GitHub as a landing reads it: the repository's default branch and main's comparison with the commit. */ + function landingGitHub(sha: string, over: Record = {}) { + github(); + const files = [{ filename: JUDGED, status: "modified", patch: LAND_PATCH, additions: 1, deletions: 1 }]; + gh.routes.unshift( + { method: "GET", match: new RegExp(`/repos/${REPO}$`), reply: () => ({ json: { default_branch: "main" } }) }, + { method: "GET", match: new RegExp(`/compare/main\\.\\.\\.${sha}$`), reply: () => ({ json: { ahead_by: 1, merge_base_commit: { sha: MB }, files, commits: [{ commit: { message: "Edit land\n\nRequested-by: Samvit" }, author: { login: "x" } }], ...over } }) }, + ); + } + + test("the status is worked out from main's comparison with the commit and posted on it, and stored on the run's landing", async () => { + landingGitHub(SQUASH); + const w = world(); + const { ctx } = actionCtx(w.db); + const out: any = await (evaluateLanding as any)._handler(ctx, { repository: REPO, run_id: "run1", sha: SQUASH }); + expect(out).toMatchObject({ state: "pending", description: `needs Samvit: edits ${JUDGED}`, posted: true, context: "approval (shadow)", head_sha: SQUASH }); + const post = gh.calls.find((c) => c.method === "POST" && /statuses/.test(c.url))!; + expect(post.url).toEndWith(`/repos/${REPO}/statuses/${SQUASH}`); + // Nothing on the landing path reads a pull request. + expect(gh.calls.some((c) => /\/pulls/.test(c.url))).toBe(false); + expect(w.run().landing.approval).toMatchObject({ head_sha: SQUASH, state: "pending", judged_files: [JUDGED], run_id: "run1" }); + expect(w.run().landing.approval.whole_key).toMatch(/^whole:[0-9a-f]{40}$/); + }); + + test("nothing is posted for a commit GitHub does not have yet, one main already holds, or a run that can no longer land it", async () => { + const posts = () => gh.calls.filter((c) => c.method === "POST" && /statuses/.test(c.url)).length; + landingGitHub(SQUASH); + gh.routes.unshift({ method: "GET", match: new RegExp(`/compare/main\\.\\.\\.${SQUASH}$`), reply: () => ({ status: 404 }) }); + expect(await (evaluateLanding as any)._handler(actionCtx(world().db).ctx, { repository: REPO, run_id: "run1" })).toEqual({ opted: true, open: false }); + gh.routes.shift(); + gh.routes.unshift({ method: "GET", match: new RegExp(`/compare/main\\.\\.\\.${SQUASH}$`), reply: () => ({ json: { ahead_by: 0, status: "identical", files: [], commits: [] } }) }); + expect(await (evaluateLanding as any)._handler(actionCtx(world().db).ctx, { repository: REPO, run_id: "run1" })).toEqual({ opted: true, open: false }); + for (const over of [{ status: "completed" }, { status: "failed" }, { merge: { sha: SQUASH, branch: "b", into: "main", at: 2 } }]) { + expect(await (evaluateLanding as any)._handler(actionCtx(world({ workflow_runs: [landingRun(over)] }).db).ctx, { repository: REPO, run_id: "run1" })).toEqual({ opted: true, open: false }); + } + expect(posts()).toBe(0); + }); + + test("a Ship press ties to the first landing commit's judged diff, and still does on the commit carried onto a newer main", async () => { + const press = { _id: "p1", repository: REPO, workflow_run_id: "run1", source: "ship_press", files: [JUDGED], user_id: "u_jason", created_at: 1 }; + const carried = landingRun({ pressed_approval_id: "p1", landing: { repository: REPO, first_sha: SQUASH, sha: CARRIED, at: 2 }, station_rebases: [{ from: SQUASH, to: CARRIED, at: 2, attempt: 1 }] }); + const w = world({ workflow_runs: [carried], change_approvals: [press] }); + expect(await (settle as any)._handler(w.ctx, { ...args, head_sha: CARRIED, first_key: "k1" })).toMatchObject({ state: "success", description: "approved by Jason Benn (Ship press)" }); + const tied = w.db._tables.change_approvals[0]; + expect(tied).toMatchObject({ judged_key: "k1", head_sha: CARRIED }); + expect(tied.pr_number).toBeUndefined(); + expect(w.run().landing.approval).toMatchObject({ head_sha: CARRIED, state: "success", judged_key: "k1", whole_key: "whole:w1" }); + // An unrelated commit (no recorded rebase from the first) ties nothing. + const unrelated = world({ workflow_runs: [{ ...carried, station_rebases: [] }], change_approvals: [press] }); + expect(await (settle as any)._handler(unrelated.ctx, { ...args, head_sha: CARRIED })).toMatchObject({ state: "pending" }); + expect(unrelated.db._tables.change_approvals[0].judged_key).toBeUndefined(); + }); + + test("a recorded rebase to a commit whose judged diff is not the first commit's binds no press: a person is asked", async () => { + const press = { _id: "p1", repository: REPO, workflow_run_id: "run1", source: "ship_press", files: [JUDGED], user_id: "u_jason", created_at: 1 }; + const carried = landingRun({ pressed_approval_id: "p1", landing: { repository: REPO, first_sha: SQUASH, sha: CARRIED, at: 2 }, station_rebases: [{ from: SQUASH, to: CARRIED, at: 2, attempt: 1 }], ...reviewed(false, CARRIED) }); + // The first commit's diff unread (it is gone, or unreadable) or different: the claimed link is not taken on trust. + for (const first_key of [undefined, "k_first"]) { + const w = world({ workflow_runs: [carried], change_approvals: [press] }); + expect(await (settle as any)._handler(w.ctx, { ...args, head_sha: CARRIED, ...(first_key ? { first_key } : {}) })).toMatchObject({ state: "pending", description: `needs Jason Benn: edits ${JUDGED}` }); + expect(w.db._tables.change_approvals[0].judged_key).toBeUndefined(); + expect(cards(w.db)).toHaveLength(1); + } + // End to end: the evaluation reads the first commit's diff from GitHub too, and a different one there ties nothing. + landingGitHub(CARRIED); + const other = [{ filename: JUDGED, status: "modified", patch: "@@ -1 +1 @@\n-a\n+something else\n", additions: 1, deletions: 1 }]; + gh.routes.unshift({ method: "GET", match: new RegExp(`/compare/main\\.\\.\\.${SQUASH}$`), reply: () => ({ json: { ahead_by: 1, merge_base_commit: { sha: MB }, files: other, commits: [{ commit: { message: "Edit land" }, author: { login: "x" } }] } }) }); + const e2e = world({ workflow_runs: [carried], change_approvals: [press] }); + expect(await (evaluateLanding as any)._handler(actionCtx(e2e.db).ctx, { repository: REPO, run_id: "run1" })).toMatchObject({ state: "pending", head_sha: CARRIED }); + expect(gh.calls.some((c) => c.url.endsWith(`/compare/main...${SQUASH}`))).toBe(true); + expect(e2e.db._tables.change_approvals[0].judged_key).toBeUndefined(); + }); + + test("a carried commit with the first commit's very diff is approved by the press end to end", async () => { + landingGitHub(CARRIED); + const files = [{ filename: JUDGED, status: "modified", patch: LAND_PATCH, additions: 1, deletions: 1 }]; + gh.routes.unshift({ method: "GET", match: new RegExp(`/compare/main\\.\\.\\.${SQUASH}$`), reply: () => ({ json: { ahead_by: 1, merge_base_commit: { sha: MB }, files, commits: [{ commit: { message: "Edit land" }, author: { login: "x" } }] } }) }); + const press = { _id: "p1", repository: REPO, workflow_run_id: "run1", source: "ship_press", files: [JUDGED], user_id: "u_jason", created_at: 1 }; + const carried = landingRun({ pressed_approval_id: "p1", landing: { repository: REPO, first_sha: SQUASH, sha: CARRIED, at: 2 }, station_rebases: [{ from: SQUASH, to: CARRIED, at: 2, attempt: 1 }], ...reviewed(false, CARRIED) }); + const w = world({ workflow_runs: [carried], change_approvals: [press] }); + expect(await (evaluateLanding as any)._handler(actionCtx(w.db).ctx, { repository: REPO, run_id: "run1" })).toMatchObject({ state: "success", head_sha: CARRIED }); + expect(w.db._tables.change_approvals[0]).toMatchObject({ head_sha: CARRIED }); + }); + + test("the sweep picks up live landings whose commit has no settled success, and leaves the rest", async () => { + const at = (id: string, over: Record) => landingRun({ _id: id, ...over }); + const ok = { head_sha: SQUASH, state: "success", description: "ok" }; + const w = world({ workflow_runs: [ + at("never", {}), + at("unposted", { landing: { repository: REPO, first_sha: SQUASH, sha: SQUASH, at: 1, approval: { ...ok, state: "unposted" } } }), + at("waiting", { status: "pending", landing: { repository: REPO, first_sha: SQUASH, sha: SQUASH, at: 1, approval: { ...ok, state: "pending" } } }), + at("moved", { landing: { repository: REPO, first_sha: SQUASH, sha: CARRIED, at: 1, approval: ok } }), + at("settled", { landing: { repository: REPO, first_sha: SQUASH, sha: SQUASH, at: 1, approval: ok } }), + at("done", { status: "completed" }), + at("merged", { merge: { sha: SQUASH, branch: "b", into: "main", at: 2 } }), + at("elsewhere", { landing: { repository: "other/repo", first_sha: SQUASH, sha: SQUASH, at: 1 } }), + ] }); + expect(((await (sweepLandings as any)._handler(w.ctx, { repository: REPO })) as string[]).sort()).toEqual(["moved", "never", "unposted", "waiting"]); + }); + + test("a mechanism asks a person on a card about the landing; their Approve merge is the run's, keyed by its diff, and nobody else's run counts", async () => { + const w = world({ workflow_runs: [landingRun(reviewed(true))], change_approvals: [ + // Another run's approval of the very same whole diff approves nothing here. + { _id: "other", repository: REPO, workflow_run_id: "run2", judged_key: "whole:w1", source: "card", files: [JUDGED], user_id: "u_ashot", created_at: 1 }, + ] }); + expect(await (settle as any)._handler(w.ctx, args)).toMatchObject({ state: "pending", description: "needs Ashot: the review called it a mechanism" }); + const [card] = cards(w.db); + expect(card.question).toBe(`Approve landing ${REPO}@${SQUASH.slice(0, 10)}: Edit land?`); + expect(card.approval).toMatchObject({ repository: REPO, sha: SQUASH, run_id: "run1", judged_key: "whole:w1", reason: "mechanism", asked: ["u_ashot"] }); + expect(card.approval.pr_number).toBeUndefined(); + expect(card.context_md).toContain(`https://github.com/${REPO}/commit/${SQUASH}`); + expect(w.run().landing.approval).toMatchObject({ card_id: card._id, card_key: "whole:w1:mechanism" }); + await settleCardApproval(w.ctx as any, card, { status: "answered", answer_index: 0 }, { kind: "user", user_id: "u_ashot" as any }, 50); + const approval = w.db._tables.change_approvals.find((a: any) => a.decision_id === card._id); + expect(approval).toMatchObject({ workflow_run_id: "run1", judged_key: "whole:w1", head_sha: SQUASH, source: "card" }); + expect(approval.pr_number).toBeUndefined(); + expect(w.scheduled).toContainEqual({ name: "changeApprovals:evaluateLanding", args: { repository: REPO, run_id: "run1", sha: SQUASH, post: true } }); + expect(await (settle as any)._handler(w.ctx, args)).toMatchObject({ state: "success", description: `approved by Ashot (${card.short_id})` }); + }); + + test("the run's own card stamps the landing it shows, and its Ship approves both keys for that run", async () => { + const w = world(); + await (settle as any)._handler(w.ctx, args); + const stamp: any = await approvalStampFor(w.ctx as any, "run1" as any); + expect(stamp).toEqual({ approval: { repository: REPO, run_id: "run1", sha: SQUASH, judged_key: "k1", whole_key: "whole:w1", files: [JUDGED] } }); + const own = { _id: "sd_own", workflow_run_id: "run1", options: [{ label: "Ship" }, { label: "Revise" }], conversation_id: "c_log", ...stamp }; + await settleCardApproval(w.ctx as any, own as any, { status: "answered", answer_index: 0 }, { kind: "user", user_id: "host" as any }, 60); + expect(w.db._tables.change_approvals.map((a: any) => [a.judged_key, a.workflow_run_id, a.head_sha, a.pr_number])).toEqual([["k1", "run1", SQUASH, undefined], ["whole:w1", "run1", SQUASH, undefined]]); + // A carry moves the landing on: the stamp follows only once the new commit's status is worked out. + w.run().landing = { ...w.run().landing, sha: CARRIED }; + expect(await approvalStampFor(w.ctx as any, "run1" as any)).toEqual({}); + }); + + test("an approval carries to another run of the same task while its diff is unchanged; a changed diff asks again", async () => { + // run1 stopped (main stayed red); the session ran the change again as run2, which landed a new commit of the same diff. + const stopped = landingRun({ status: "failed" }); + const again = landingRun({ _id: "run2", created_at: 10, ...reviewed(true, CARRIED), review_verdict: { ...reviewed(true, CARRIED).review_verdict, attempt: 10 }, node_statuses: [{ node_id: "review", status: "completed", session_id: "rev", started_at: 11 }], landing: { repository: REPO, first_sha: CARRIED, sha: CARRIED, at: 10 } }); + const cardYes = { _id: "a1", repository: REPO, workflow_run_id: "run1", task_id: "t1", judged_key: "whole:w1", source: "card", files: [JUDGED], user_id: "u_ashot", decision_id: "sd_1", created_at: 5 }; + const w = world({ workflow_runs: [again, stopped], change_approvals: [cardYes], session_decisions: [{ _id: "sd_1", short_id: "sd-1" }] }); + const run2 = { ...args, run_id: "run2", head_sha: CARRIED }; + expect(await (settle as any)._handler(w.ctx, run2)).toMatchObject({ state: "success", description: "approved by Ashot (sd-1)" }); + expect(cards(w.db)).toEqual([]); + // Another task's approval of the same diff is not this task's. + const other = world({ workflow_runs: [again, stopped], change_approvals: [{ ...cardYes, task_id: "t9", workflow_run_id: "run9" }] }); + expect(await (settle as any)._handler(other.ctx, run2)).toMatchObject({ state: "pending", description: "needs Ashot: the review called it a mechanism" }); + // The new run's diff changed: asked again. + expect(await (settle as any)._handler(w.ctx, { ...run2, whole_key: "w2" })).toMatchObject({ state: "pending", description: "needs Ashot: the review called it a mechanism" }); + // A Revise on the new run's own card takes back the earlier run's yes too: an earlier yes never outlives a later no. + const revise = { _id: "sd_own2", workflow_run_id: "run2", options: [{ label: "Ship" }, { label: "Revise" }], conversation_id: "c_log" }; + await settleCardApproval(w.ctx as any, revise as any, { status: "answered", answer_index: 1 }, { kind: "user", user_id: "host" as any }, 70); + expect(w.db._tables.change_approvals[0].revoked_at).toBe(70); + expect(await (settle as any)._handler(w.ctx, run2)).toMatchObject({ state: "pending" }); + }); + + test("a Ship press an earlier run of the task claimed but never tied (it stopped before pushing) is the next run's press", async () => { + const stopped = landingRun({ status: "failed", pressed_approval_id: "p1", landing: undefined }); + const again = landingRun({ _id: "run2", landing: { repository: REPO, first_sha: CARRIED, sha: CARRIED, at: 10 }, ...reviewed(false, CARRIED) }); + const press = { _id: "p1", repository: REPO, workflow_run_id: "run1", task_id: "t1", source: "ship_press", files: [JUDGED], user_id: "u_jason", created_at: 1 }; + const w = world({ workflow_runs: [again, stopped], change_approvals: [press] }); + expect(await (settle as any)._handler(w.ctx, { ...args, run_id: "run2", head_sha: CARRIED })).toMatchObject({ state: "success", description: "approved by Jason Benn (Ship press)" }); + expect(w.db._tables.change_approvals[0]).toMatchObject({ judged_key: "k1", head_sha: CARRIED, task_id: "t1" }); + }); + + test("a press is stamped with the task of the run that claims it", async () => { + const w = world({ change_approvals: [{ _id: "p1", repository: REPO, source: "ship_press", files: [JUDGED], user_id: "u_jason", conversation_id: "c_log", created_at: 100 }] }); + expect(await claimPress(w.ctx as any, "run1" as any, "c_log" as any, 200)).toBe("p1"); + expect(w.db._tables.change_approvals[0]).toMatchObject({ workflow_run_id: "run1", task_id: "t1" }); + }); + + test("a settle for a commit the run has since replaced changes nothing and says so", async () => { + const w = world({ workflow_runs: [landingRun({ landing: { repository: REPO, first_sha: SQUASH, sha: CARRIED, at: 2 } })] }); + expect(await (settle as any)._handler(w.ctx, args)).toEqual({ state: "pending", description: `replaced by ${CARRIED.slice(0, 10)}`, context: "approval (shadow)" }); + expect(w.run().landing.approval).toBeUndefined(); + await expect((settle as any)._handler(w.ctx, { ...args, pr_number: 7 })).rejects.toThrow("one of them"); + }); +}); diff --git a/packages/convex/convex/changeApprovals.test.ts b/packages/convex/convex/changeApprovals.test.ts index c72d785996..341a9873e1 100644 --- a/packages/convex/convex/changeApprovals.test.ts +++ b/packages/convex/convex/changeApprovals.test.ts @@ -1,11 +1,12 @@ // Codecast's `approval` status (ct-100350): the rule (decide), the status worked out from a mocked GitHub and posted, // the approvals a person's card and press make or revoke, and the merge as codecast's app. The automatic review of a pull -// request no run is behind, and its hold, are changeApprovals.automatic.test.ts. +// request no run is behind, and its hold, are changeApprovals.automatic.test.ts; a run's landing commit with no pull +// request is changeApprovals.landing.test.ts. import { describe, expect, test } from "bun:test"; import { getFunctionName } from "convex/server"; import { makeFakeDb } from "./testDb"; import { decide, evaluate, mechanismOf, mergeAsApp, settle, sweep, type ApprovalFacts } from "./changeApprovals"; -import { actionCtx, gh, github, HEAD, installation, LAND_PATCH, MB, prRow, REPO, useMockedGitHub } from "./changeApprovals.testkit"; +import { actionCtx, gh, github, HEAD, installation, prRow, REPO, useMockedGitHub } from "./changeApprovals.testkit"; import { HOST_TOKEN_PERMISSIONS } from "./githubApp"; import { changeJudgedFiles, claimPress, gateOf, noticeCaptainRevertMerged, settleCardApproval } from "./lib/changeApprovalRows"; import { processPRSynchronizeEvent } from "./githubWebhooks"; @@ -320,11 +321,16 @@ describe("the run behind it", () => { test("the sweep works out every open pull request of each opted-in repository, a few seconds apart", async () => { const scheduled: Array<[number, any]> = []; const ctx: any = { - runQuery: async (ref: any, a: any) => (getFunctionName(ref) === "changeApprovals:optedRepositories" ? [REPO] : a.repository === REPO ? [7, 8] : []), - scheduler: { runAfter: async (ms: number, _ref: any, a: any) => { scheduled.push([ms, a.pr_number]); } }, + runQuery: async (ref: any, a: any) => { + const name = getFunctionName(ref); + if (name === "changeApprovals:optedRepositories") return [REPO]; + if (name === "changeApprovals:sweepLandings") return a.repository === REPO ? ["run9"] : []; + return a.repository === REPO ? [7, 8] : []; + }, + scheduler: { runAfter: async (ms: number, _ref: any, a: any) => { scheduled.push([ms, a.pr_number ?? a.run_id]); } }, }; - expect(await (sweep as any)._handler(ctx, {})).toEqual({ repositories: 1, pulls: 2 }); - expect(scheduled).toEqual([[0, 7], [3000, 8]]); + expect(await (sweep as any)._handler(ctx, {})).toEqual({ repositories: 1, pulls: 2, landings: 1 }); + expect(scheduled).toEqual([[0, 7], [3000, 8], [6000, "run9"]]); }); }); diff --git a/packages/convex/convex/changeApprovals.ts b/packages/convex/convex/changeApprovals.ts index 8b20942bf8..e8666f3693 100644 --- a/packages/convex/convex/changeApprovals.ts +++ b/packages/convex/convex/changeApprovals.ts @@ -28,6 +28,13 @@ // owners file beside the judges file (` `), else the pull request's // author; a mechanism, an engineer or that owner. // +// landing a run that lands with no pull request (one commit squashed onto main's tip, pushed for CI, then main +// fast-forwarded to it) reports each push (orgLineMerge.recordRunLanding). The same rule reads the change from +// GitHub's comparison of the default branch with that commit and posts the same status on it; the run, never a +// pull request number, keys its press, approvals and cards. A commit carried onto a newer main is the first one +// through a recorded rebase. Another run of the same task (one that stopped and was run again) carries the +// approvals of an unchanged diff, and a Revise or Drop on any of them takes back the task's. A commit no run reported is not evaluated at all: nothing posts on it. +// // Nothing posts for a repository until an admin opts it in (setGate), "shadow" first, under its own context. import { v } from "convex/values"; import { internalAction, internalMutation, internalQuery, mutation, query } from "./functions"; @@ -38,16 +45,14 @@ import { verifyApiToken } from "./apiTokens"; import { normalizeRepository, repositoryKeyOfRemote } from "@codecast/shared/contracts"; import { canAccessConversation } from "./lib/access"; import { requireInstallationRevoker } from "./githubApp"; -import { fetchPRFiles, PR_FILES_CAP, type PRPath } from "./githubApi"; import { patchPullRequest } from "./prShepherd"; import { coveredHeads, runAttempt } from "./orgLineMerge"; -import { approvalContext, askerOf, changeJudgedFiles, gateOf, isCam, isReleaseCaptain, mayReadGate, preBuildYes } from "./lib/changeApprovalRows"; +import { approvalContext, askerOf, changeJudgedFiles, gateOf, isCam, isReleaseCaptain, landingApprovals, mayReadGate, preBuildYes } from "./lib/changeApprovalRows"; import { askReviewForMechanism, cardPeople, cardStale, postApprovalCard, withdrawApprovalCard, type CardReason } from "./lib/changeApprovalCards"; -import { MECHANISM_FILE } from "./lib/automaticReview"; import { automaticOutcome, automaticReviewFor, claimHead, countedWithoutRun, type Claim } from "./lib/automaticReviewHold"; import { automaticReviewValidator } from "./lib/automaticReviewValidator"; -import { GITHUB, encodePath, rest } from "./lib/githubRest"; -import { diffKey, isJudged, judgedPaths, keyChanged, keyEntriesFor, ownerOf, parseJudges, parseOwners, pathDiffsOf, pathsOf, requestedBy, revertedShas, type GitHubFile } from "./lib/judgedDiff"; +import { GITHUB, rest } from "./lib/githubRest"; +import { readLanding, readPull, shownStatus, wholeKey } from "./lib/changeApprovalReads"; /** GitHub cuts a status description at 140 characters. */ const DESCRIPTION_MAX = 140; @@ -156,176 +161,6 @@ export function cardReason(f: ApprovalFacts): CardReason | null { return f.judged.length && !f.press ? "judged" : null; } -// ── Reading GitHub ── - -/** The newest status GitHub shows on a commit under one context (its list is newest first), or undefined. */ -async function shownStatus(repository: string, sha: string, context: string, token: string): Promise<{ state?: string; description?: string } | undefined> { - const statuses = await rest(`${GITHUB}/repos/${repository}/commits/${sha}/statuses?per_page=100`, token); - return (Array.isArray(statuses.json) ? statuses.json : []).find((s: any) => s?.context === context); -} - -const dirOf = (path: string) => (path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""); -const baseOf = (path: string) => path.slice(path.lastIndexOf("/") + 1); - -/** - * Modes (from each parent tree's entries) and texts (a renamed file's two sides), by GraphQL "sha:path" - * expressions, a hundred to a call. A mode reads as git prints it ("100644"); a binary or cut text reads null. - */ -async function readObjects(repository: string, token: string, wants: Array<{ sha: string; path: string; text: boolean }>): Promise<{ mode: (sha: string, path: string) => string | null; text: (sha: string, path: string) => string | null }> { - const [owner, name] = repository.split("/"); - const trees = new Map>(); - const texts = new Map(); - const asks = [ - ...[...new Set(wants.map((w) => `${w.sha}:${dirOf(w.path)}`))].map((e) => ({ e, kind: "tree" as const })), - ...[...new Set(wants.filter((w) => w.text).map((w) => `${w.sha}:${w.path}`))].map((e) => ({ e, kind: "blob" as const })), - ]; - for (let i = 0; i < asks.length; i += 100) { - const chunk = asks.slice(i, i + 100); - const vars = chunk.map((_, j) => `$e${j}: String!`).join(", "); - const fields = chunk.map((_, j) => `o${j}: object(expression: $e${j}) { ... on Tree { entries { name mode } } ... on Blob { text isBinary isTruncated } }`).join("\n"); - const variables: Record = { owner, name }; - chunk.forEach((a, j) => { variables[`e${j}`] = a.e; }); - const r = await rest(`${GITHUB}/graphql`, token, { method: "POST", body: { query: `query($owner: String!, $name: String!, ${vars}) { repository(owner: $owner, name: $name) { ${fields} } }`, variables } }); - if (r.json?.errors?.length) throw new Error(`GitHub GraphQL: ${r.json.errors[0]?.message ?? "error"}`); - const repo = r.json?.data?.repository ?? {}; - chunk.forEach((a, j) => { - const o = repo[`o${j}`]; - if (a.kind === "tree") trees.set(a.e, new Map((o?.entries ?? []).map((x: any) => [String(x.name), Number(x.mode).toString(8)]))); - else texts.set(a.e, o && !o.isBinary && !o.isTruncated && typeof o.text === "string" ? o.text : null); - }); - } - return { - mode: (sha, path) => trees.get(`${sha}:${dirOf(path)}`)?.get(baseOf(path)) ?? null, - text: (sha, path) => texts.get(`${sha}:${path}`) ?? null, - }; -} - -/** GitHub's entries completed with what the rebuild needs from each side, for the paths `keep` selects. */ -async function withSides(repository: string, token: string, files: PRPath[], base: string, head: string, keep: (p: string) => boolean): Promise { - const chosen = files.filter((f) => pathsOf(f).some(keep)); - const wants = chosen.flatMap((f) => { - const old = f.previous_filename ?? f.filename; - const renamed = f.status === "renamed" && !!f.previous_filename; - return [ - ...(f.status === "added" ? [] : [{ sha: base, path: old, text: renamed }]), - ...(f.status === "removed" ? [] : [{ sha: head, path: f.filename, text: renamed }]), - ]; - }); - const read = wants.length ? await readObjects(repository, token, wants) : null; - return chosen.map((f) => { - const old = f.previous_filename ?? f.filename; - const renamed = f.status === "renamed" && !!f.previous_filename; - return { - ...f, - base_mode: f.status === "added" ? null : read!.mode(base, old), - head_mode: f.status === "removed" ? null : read!.mode(head, f.filename), - ...(renamed ? { base_text: read!.text(base, old), head_text: read!.text(head, f.filename) } : {}), - }; - }); -} - -/** - * The key of the pull request's whole diff against its merge base (patch-id --verbatim, as the judged diff's): what a - * card that read the change whole approves, so a pure rebase carries it and any code change asks again. When a file's - * diff cannot be rebuilt (binary, too large, unreadable), undefined: settle then keys it to the head, so every push - * asks again. - */ -async function wholeKey(repository: string, token: string, paths: PRPath[], base: string, head: string): Promise { - try { - const all = pathDiffsOf(await withSides(repository, token, paths, base, head, () => true), () => true); - return "unreadable" in all ? undefined : await diffKey(all.diffs); - } catch { - return undefined; - } -} - -async function prMessages(repository: string, token: string, prNumber: number): Promise { - const commits: any[] = []; - for (let page = 1; page <= 3; page++) { - const r = await rest(`${GITHUB}/repos/${repository}/pulls/${prNumber}/commits?per_page=100&page=${page}`, token); - const batch: any[] = r.json ?? []; - commits.push(...batch); - if (batch.length < 100) break; - } - return commits.map((c) => String(c.commit?.message ?? "")); -} - -/** Who a card may go to, as GitHub and main's files beside the judges file name them. */ -export type PullPeople = { - title: string; - author_login: string | null; - /** The area's owner by main's owners file (lib/judgedDiff parseOwners), or null when the file or its area is missing. */ - area_owner: { user_id: string; name: string } | null; - /** Main's engineers file: one ` ` a line; null when GitHub could not be read (none is not []). */ - engineers: Array<{ user_id: string; name: string }> | null; -}; - -export type PullRead = - | { open: false } - | { open: true; head_sha: string; unreadable: string; judges?: string[]; people: PullPeople } - | { - open: true; head_sha: string; judged: string[]; key: string; whole_key?: string; judges: string[]; reverts: boolean; requested_by?: string; people: PullPeople; - base_sha: string; paths: string[]; default_branch: string; - /** Where main's mechanism file is (lib/automaticReview MECHANISM_FILE, beside the judges file): read only when the automatic review runs. */ - mechanism_path: string; - }; - -/** Main's engineers file: ` ` a line, blank and "#" lines skipped. */ -export function parseEngineers(text: string): Array<{ user_id: string; name: string }> { - return text.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).flatMap((l) => { - const m = /^(\S+)\s+(.+)$/.exec(l); - return m ? [{ user_id: m[1], name: m[2].trim() }] : []; - }); -} - -/** Everything the rule reads from GitHub for one pull request. Never throws past the head: a failure is unreadable. */ -export async function readPull(repository: string, prNumber: number, token: string, judgesPath: string): Promise { - const pr = await fetchPRFiles(repository, prNumber, token); - if (pr.state !== "open" || !pr.head_sha) return { open: false }; - const head = pr.head_sha; - const main = pr.default_branch ?? pr.base_ref ?? "main"; - const changed = pr.paths.flatMap(pathsOf); - const beside = (name: string) => `${judgesPath.includes("/") ? judgesPath.slice(0, judgesPath.lastIndexOf("/") + 1) : ""}${name}`; - const onMain = async (path: string) => { - const r = await rest(`${GITHUB}/repos/${repository}/contents/${encodePath(path)}?ref=${encodeURIComponent(main)}`, token, { accept: "application/vnd.github.raw+json" }); - return r.status === 404 ? null : r.text ?? ""; - }; - const people: PullPeople = { title: pr.title ?? "", author_login: pr.author_login ?? null, area_owner: null, engineers: null }; - try { - const [ownersText, engineersText] = await Promise.all([onMain(beside("owners.txt")), onMain(beside("engineers.txt"))]); - const owners = ownersText === null ? [] : parseOwners(ownersText); - people.engineers = engineersText === null ? [] : parseEngineers(engineersText); - people.area_owner = ownerOf(changed, owners); - const judgesText = await onMain(judgesPath); - if (judgesText === null) return { open: true, head_sha: head, unreadable: `${judgesPath} on ${main}`, people }; - const judges = parseJudges(judgesText); - if (!pr.complete || pr.paths.length >= PR_FILES_CAP) return { open: true, head_sha: head, unreadable: "every file (over 3,000, or GitHub cut the list short)", judges, people }; - const compare = await rest(`${GITHUB}/repos/${repository}/compare/${encodeURIComponent(main)}...${head}`, token); - const mb: string | undefined = compare.json?.merge_base_commit?.sha; - if (!mb) return { open: true, head_sha: head, unreadable: `the merge base with ${main}`, judges, people }; - // A `name#key` entry judges a file of that name only when its key's value changed: read both sides to decide. - const byKey = changed.filter((p) => !isJudged(p, judges) && keyEntriesFor(p, judges).length); - const sides = byKey.length ? await readObjects(repository, token, byKey.flatMap((p) => [{ sha: mb, path: p, text: true }, { sha: head, path: p, text: true }])) : null; - const keyHits = byKey.filter((p) => keyEntriesFor(p, judges).some((k) => keyChanged(sides!.text(mb, p), sides!.text(head, p), k.key))); - const judged = judgedPaths(changed, judges, keyHits); - // The area is the judged files' when there are any. - if (judged.length) people.area_owner = ownerOf(judged, owners) ?? people.area_owner; - const rebuilt = pathDiffsOf(await withSides(repository, token, pr.paths, mb, head, (p) => judged.includes(p)), (p) => judged.includes(p)); - if ("unreadable" in rebuilt) return { open: true, head_sha: head, unreadable: `${rebuilt.unreadable}'s diff`, judges, people }; - const key = await diffKey(rebuilt.diffs); - const whole_key = await wholeKey(repository, token, pr.paths, mb, head); - const messages = await prMessages(repository, token, prNumber); - const asker = requestedBy(messages); - // The Captain's exemption is for a pull request of reverts only: one other commit and it is judged like any. - return { - open: true, head_sha: head, judged, key, ...(whole_key ? { whole_key } : {}), judges, reverts: messages.length > 0 && messages.every((m) => revertedShas(m).length > 0), ...(asker ? { requested_by: asker } : {}), people, - base_sha: mb, paths: changed, default_branch: main, mechanism_path: beside(MECHANISM_FILE), - }; - } catch (error) { - return { open: true, head_sha: head, unreadable: `GitHub (${(error instanceof Error ? error.message : String(error)).slice(0, 60)})`, people }; - } -} - /** Why a token cannot post statuses, or null when it can or nobody recorded what it may do. */ export function statusesRefusal(permissions: Record | undefined): string | null { if (!permissions) return null; @@ -336,21 +171,33 @@ export function statusesRefusal(permissions: Record | undefined) export type Evaluation = { opted: false } | { opted: true; open: false } | ({ opted: true; open: true; head_sha: string; context: string; posted: boolean; unchanged?: boolean; reason?: string } & ApprovalVerdict); -async function evaluateCore(ctx: any, args: { repository: string; pr_number: number; post: boolean }): Promise { +/** What an evaluation is about: a pull request, or a run's landing commit (no pull request). */ +type Subject = { pr_number: number } | { run_id: Id<"workflow_runs"> }; + +async function evaluateCore(ctx: any, args: { repository: string; post: boolean } & Subject): Promise { const repository = normalizeRepository(args.repository); const gate: any = await ctx.runQuery(internal.changeApprovals.gateFor, { repository }); if (!gate) return { opted: false }; + // A landing is read at the sha its run holds now, while the run can still land it. + const landing: { sha: string; title: string; first_sha?: string } | null = "run_id" in args ? await ctx.runQuery(internal.changeApprovals.landingOf, { repository, run_id: args.run_id }) : null; + if ("run_id" in args && !landing) return { opted: true, open: false }; + const subject: Subject = "run_id" in args ? { run_id: args.run_id } : { pr_number: args.pr_number }; const minted: { token: string; permissions?: Record } = await ctx.runAction(internal.githubApp.getInstallationToken, { installation_id: gate.installation_id }); - const read = await readPull(repository, args.pr_number, minted.token, gate.judges_path); + const read = landing ? await readLanding(repository, landing.sha, minted.token, gate.judges_path, landing.title) : await readPull(repository, (subject as { pr_number: number }).pr_number, minted.token, gate.judges_path); if (!read.open) return { opted: true, open: false }; - // No codecast run behind it: the automatic review reads this head, once (lib/automaticReviewHold.ts). - const automatic = "unreadable" in read ? undefined : await automaticReviewFor(ctx, { - repository, pr_number: args.pr_number, head_sha: read.head_sha, base_sha: read.base_sha, paths: read.paths, + // A landing carried off its first commit: that commit's judged diff, which a press or a pre-build yes approved, is read + // too, so a recorded rebase binds them only when the diff it made is the same one (settle firstHead). + const first = landing?.first_sha && !("unreadable" in read) ? await readLanding(repository, landing.first_sha, minted.token, gate.judges_path, landing.title) : null; + const first_key = first?.open && !("unreadable" in first) ? first.key : undefined; + // No codecast run behind it: the automatic review reads this head, once (lib/automaticReviewHold.ts). A landing + // always has its run. + const automatic = "unreadable" in read || !("pr_number" in subject) ? undefined : await automaticReviewFor(ctx, { + repository, pr_number: subject.pr_number, head_sha: read.head_sha, base_sha: read.base_sha, paths: read.paths, default_branch: read.default_branch, mechanism_path: read.mechanism_path, token: minted.token, }); const verdict: ApprovalVerdict & { context: string } = await ctx.runMutation(internal.changeApprovals.settle, { - repository, pr_number: args.pr_number, head_sha: read.head_sha, - ...(automatic ? { automatic } : {}), + repository, ...subject, head_sha: read.head_sha, + ...(automatic ? { automatic } : {}), ...(first_key !== undefined ? { first_key } : {}), ...("unreadable" in read ? { unreadable: read.unreadable } : { judged: read.judged, key: read.key, ...(read.whole_key ? { whole_key: read.whole_key } : {}), ...(read.reverts ? { reverts: true } : {}), @@ -369,7 +216,7 @@ async function evaluateCore(ctx: any, args: { repository: string; pr_number: num if (!args.post) return { ...done, posted: false }; const refusal = statusesRefusal(minted.permissions); const unposted = async (reason: string) => { - await ctx.runMutation(internal.changeApprovals.noteUnposted, { repository, pr_number: args.pr_number, head_sha: read.head_sha, reason: fit(reason) }); + await ctx.runMutation(internal.changeApprovals.noteUnposted, { repository, ...subject, head_sha: read.head_sha, reason: fit(reason) }); return { ...done, posted: false, reason }; }; if (refusal) return unposted(refusal); @@ -394,27 +241,82 @@ export const evaluate = internalAction({ }, }); +/** + * Work a run's landing commit's status out and, with `post`, post it on the commit from the app. `sha` is the one the + * trigger saw: when the run has moved on to another, the evaluation scheduled for that one posts instead. + */ +export const evaluateLanding = internalAction({ + args: { repository: v.string(), run_id: v.id("workflow_runs"), sha: v.optional(v.string()), post: v.optional(v.boolean()) }, + handler: async (ctx, args): Promise => { + const { token: _token, ...out } = await evaluateCore(ctx, { repository: args.repository, run_id: args.run_id, post: args.post ?? true }) as any; + return out; + }, +}); + +/** + * The landing an evaluation reads: the run's current landing sha in this repository, the title its card shows (the + * task's, else the flow's), and the first sha when the landing has moved off it, or null when there is nothing to land + * any more (the run finished or failed, or its merge landed that sha). + */ +export const landingOf = internalQuery({ + args: { repository: v.string(), run_id: v.id("workflow_runs") }, + handler: async (ctx, args): Promise<{ sha: string; title: string; first_sha?: string } | null> => { + const run: any = await ctx.db.get(args.run_id); + const landing = run?.landing; + if (!landing || normalizeRepository(landing.repository) !== normalizeRepository(args.repository)) return null; + if (run.status === "completed" || run.status === "failed" || run.merge?.sha === landing.sha) return null; + return { sha: landing.sha, title: await landingTitle(ctx, run), ...(landing.first_sha !== landing.sha ? { first_sha: landing.first_sha } : {}) }; + }, +}); + +/** + * The live landing runs of a repository the sweep works out again: those whose current commit has no settled success + * (never evaluated, an evaluation that failed or could not post, or one still waiting), at most SWEEP_PRS a status. + */ +export const sweepLandings = internalQuery({ + args: { repository: v.string() }, + handler: async (ctx, args): Promise>> => { + const live: any[] = []; + for (const status of ["running", "pending"] as const) { + live.push(...await ctx.db.query("workflow_runs").withIndex("by_landing", (q) => q.eq("landing.repository", args.repository).eq("status", status)).take(SWEEP_PRS)); + } + const settled = (run: any) => run.landing.approval?.head_sha === run.landing.sha && run.landing.approval.state === "success"; + return live.filter((run) => run.merge?.sha !== run.landing.sha && !settled(run)).map((run) => run._id); + }, +}); + +async function landingTitle(ctx: { db: any }, run: any): Promise { + const task: any = run.task_id ? await ctx.db.get(run.task_id) : null; + if (task?.title) return String(task.title); + const workflow: any = run.workflow_id ? await ctx.db.get(run.workflow_id) : null; + return String(workflow?.name ?? ""); +} + /** How many open pull requests one sweep reads per repository, and how far apart their reads start. */ const SWEEP_PRS = 100; const SWEEP_SPACING_MS = 3_000; /** - * The periodic sweep (crons.ts): every opted-in repository's open pull requests are worked out again, so a dropped - * webhook or a deploy mid-event never leaves one pending with nobody told. Reads start a few seconds apart, and a - * status GitHub already shows the same on its head is not posted again. + * The periodic sweep (crons.ts): every opted-in repository's open pull requests, and its live landings not yet at + * success, are worked out again, so a dropped webhook, a failed evaluation or a deploy mid-event never leaves one pending + * with nobody told. Reads start a few seconds apart, and a status GitHub already shows the same is not posted again. */ export const sweep = internalAction({ args: {}, - handler: async (ctx): Promise<{ repositories: number; pulls: number }> => { + handler: async (ctx): Promise<{ repositories: number; pulls: number; landings: number }> => { const repositories: string[] = await ctx.runQuery(internal.changeApprovals.optedRepositories, {}); let n = 0; + let pulls = 0; for (const repository of repositories) { const numbers: number[] = await ctx.runQuery(internal.changeApprovals.openNumbers, { repository }); for (const pr_number of numbers.slice(0, SWEEP_PRS)) { + pulls++; await ctx.scheduler.runAfter(n++ * SWEEP_SPACING_MS, internal.changeApprovals.evaluate, { repository, pr_number, post: true }); } + const runs: Array> = await ctx.runQuery(internal.changeApprovals.sweepLandings, { repository }); + for (const run_id of runs) await ctx.scheduler.runAfter(n++ * SWEEP_SPACING_MS, internal.changeApprovals.evaluateLanding, { repository, run_id, post: true }); } - return { repositories: repositories.length, pulls: n }; + return { repositories: repositories.length, pulls, landings: n - pulls }; }, }); @@ -477,14 +379,17 @@ export function mechanismOf(run: any, head: string): boolean | null { } /** - * The records half of a status: the run behind the pull request and its review's answer, a Ship press tied to the - * judged diff of the first head the run pushed, the approvals for this diff (a card approves only the diff it was - * stamped with), and the verdict, stored on the pull request's rows. + * The records half of a status: the run behind the change and its review's answer, a Ship press tied to the judged + * diff of the first head the run pushed, the approvals for this diff (a card approves only the diff it was stamped + * with), and the verdict, stored on the pull request's rows. A landing (`run_id`, no pull request) is the same rule + * keyed by its run: the press ties to the first landing sha or a recorded rebase of it, approvals are the run's, and + * the verdict is stored on the run's landing. */ export const settle = internalMutation({ args: { repository: v.string(), - pr_number: v.number(), + pr_number: v.optional(v.number()), + run_id: v.optional(v.id("workflow_runs")), head_sha: v.string(), unreadable: v.optional(v.string()), judged: v.optional(v.array(v.string())), @@ -494,6 +399,8 @@ export const settle = internalMutation({ requested_by: v.optional(v.string()), judges: v.optional(v.array(v.string())), automatic: v.optional(automaticReviewValidator), + // A landing moved off its first commit: the judged-diff key of that first commit, read with this one (evaluateCore). + first_key: v.optional(v.string()), people: v.optional(v.object({ title: v.string(), author_login: v.optional(v.string()), @@ -510,14 +417,35 @@ export const settle = internalMutation({ const row = await ctx.db.get(gate.installation_row); if (row) await ctx.db.patch(row._id, { approval_gate: (row.approval_gate ?? []).map((g) => (normalizeRepository(g.repository) === repository ? { ...g, ...(args.judges ? { judges: args.judges } : {}), ...(readEngineers ? { engineers: readEngineers } : {}) } : g)) }); } - const run: any = await ctx.db.query("workflow_runs").withIndex("by_pr", (q) => q.eq("pr.repository", repository).eq("pr.number", args.pr_number)).order("desc").first(); + const landing = args.run_id !== undefined; + if (landing === (args.pr_number !== undefined)) throw new Error("settle names a pull request or a run's landing, one of them"); + const run: any = landing + ? await ctx.db.get(args.run_id!) + : await ctx.db.query("workflow_runs").withIndex("by_pr", (q) => q.eq("pr.repository", repository).eq("pr.number", args.pr_number!)).order("desc").first(); + const context = approvalContext(gate.mode); + if (landing && (!run?.landing || normalizeRepository(run.landing.repository) !== repository)) throw new Error(`run ${args.run_id} has no landing in ${repository}`); + // The run moved on to another landing commit while this one was read: that one's evaluation settles it. + if (landing && run.landing.sha !== args.head_sha) return { state: "pending", description: fit(`replaced by ${run.landing.sha.slice(0, 10)}`), context }; + const name = landing ? `${repository}@${args.head_sha.slice(0, 10)}` : `${repository}#${args.pr_number}`; + const byPr = landing ? {} : { pr_number: args.pr_number! }; const key = args.key; const judged = args.judged ?? []; + // The first head the run pushed: a Ship press and an engineer's pre-build yes bind to its judged diff. A landing + // commit carried onto a newer main by a recorded rebase is still that head, but only when its judged diff is the + // first commit's: a rebase record is the runner's claim, never checked here (orgLineMerge.recordStationRebaseCore), + // so a claimed link to a different diff binds nothing and a person is asked again. + const firstHead = (head: string) => (landing + ? head === run.landing.first_sha || (args.first_key !== undefined && args.first_key === args.key && coveredHeads(run, runAttempt(run), run.landing.first_sha).has(head)) + : run?.pr?.first_head_sha === head); if (run && key !== undefined) { - const press: any = run.pressed_approval_id ? await ctx.db.get(run.pressed_approval_id) : null; - if (press && !press.revoked_at && press.judged_key === undefined && run.pr?.first_head_sha === args.head_sha && judged.every((p) => press.files.includes(p))) { - await ctx.db.patch(press._id, { pr_number: args.pr_number, judged_key: key, head_sha: args.head_sha }); + // A landing run no press started stands on one an earlier run of its task claimed and never tied (it stopped + // before it pushed a landing). + const press: any = run.pressed_approval_id ? await ctx.db.get(run.pressed_approval_id) + : landing ? (await landingApprovals(ctx, run)).filter((a) => a.source === "ship_press" && a.judged_key === undefined && !a.revoked_at).sort((a, b) => b.created_at - a.created_at)[0] ?? null + : null; + if (press && !press.revoked_at && press.judged_key === undefined && firstHead(args.head_sha) && judged.every((p) => press.files.includes(p))) { + await ctx.db.patch(press._id, { ...byPr, judged_key: key, head_sha: args.head_sha, ...(run.task_id ? { task_id: run.task_id } : {}) }); } } @@ -526,11 +454,11 @@ export const settle = internalMutation({ const engineers = args.people?.engineers ?? gate.engineers ?? []; const camAsked = !!run && isCam(await askerOf(ctx, run)); const engineerYes = camAsked ? await preBuildYes(ctx, run, engineers) : null; - if (engineerYes && key !== undefined && run.pr?.first_head_sha === args.head_sha) { + if (engineerYes && key !== undefined && firstHead(args.head_sha)) { const tied = await ctx.db.query("change_approvals").withIndex("by_run", (q) => q.eq("workflow_run_id", run._id)).collect(); if (!tied.some((a) => a.source === "engineer_yes" && String(a.decision_id) === String(engineerYes.decision_id))) { await ctx.db.insert("change_approvals", { - repository, pr_number: args.pr_number, judged_key: key, files: judged, user_id: engineerYes.user_id, source: "engineer_yes", + repository, ...byPr, judged_key: key, files: judged, user_id: engineerYes.user_id, source: "engineer_yes", workflow_run_id: run._id, ...(run.task_id ? { task_id: run.task_id } : {}), decision_id: engineerYes.decision_id, head_sha: args.head_sha, created_at: Date.now(), }); } @@ -543,12 +471,14 @@ export const settle = internalMutation({ // Whole keys are namespaced (`whole:`, `head:`) apart from judged-diff keys: when every changed file is judged the two // patch ids are equal, and a yes to the judged files must never read as a yes to the change whole. const wholeKey = args.whole_key ? `whole:${args.whole_key}` : `head:${args.head_sha}`; - const keyed = async (k: string | undefined): Promise[]> => (k === undefined ? [] : (await ctx.db - .query("change_approvals") - .withIndex("by_pr_key", (q) => q.eq("repository", repository).eq("pr_number", args.pr_number).eq("judged_key", k)) - .collect()).filter((a) => !a.revoked_at).sort((a, b) => b.created_at - a.created_at)); + // A landing's approvals are its run's and its task's other runs' (lib/changeApprovalRows landingApprovals); a pull + // request's, its number's. + const keyed = async (k: string | undefined): Promise[]> => (k === undefined ? [] : (landing + ? await landingApprovals(ctx, run, k) + : await ctx.db.query("change_approvals").withIndex("by_pr_key", (q) => q.eq("repository", repository).eq("pr_number", args.pr_number).eq("judged_key", k)).collect() + ).filter((a) => !a.revoked_at).sort((a, b) => b.created_at - a.created_at)); // With no run behind the pull request, only codecast's own approval card counts (lib/automaticReviewHold.ts). - const countable = async (rows: Doc<"change_approvals">[]) => (run ? rows : countedWithoutRun(ctx, repository, args.pr_number, rows)); + const countable = async (rows: Doc<"change_approvals">[]) => (run ? rows : countedWithoutRun(ctx, repository, args.pr_number!, rows)); const approvals = await countable(await keyed(key)); const wholeRow = (await countable(await keyed(wholeKey))).find((a) => a.source === "card"); const pressRow = approvals.find((a) => a.source === "ship_press"); @@ -559,9 +489,9 @@ export const settle = internalMutation({ const press = pressRow ? { who: await nameOf(ctx, pressRow.user_id) } : judgedCardRow ? { who: await nameOf(ctx, judgedCardRow.user_id), ref: await refOf(judgedCardRow) } : yesRow ? { who: await nameOf(ctx, yesRow.user_id), ref: `${await refOf(yesRow)} before the build` } : null; - const rows = await ctx.db.query("pull_requests").withIndex("by_repository_number", (q) => q.eq("repository", repository).eq("number", args.pr_number)).collect(); + const rows = landing ? [] : await ctx.db.query("pull_requests").withIndex("by_repository_number", (q) => q.eq("repository", repository).eq("number", args.pr_number!)).collect(); const pr = rows[0] ?? null; - const before = pr?.approval; + const before = landing ? run.landing.approval : pr?.approval; // A card codecast asked and then took back (or that is gone) asks nothing now: its key no longer stands, so the // question is asked again. A card someone answered keeps it. const heldCard: any = before?.card_id ? await ctx.db.get(before.card_id) : null; @@ -605,54 +535,59 @@ export const settle = internalMutation({ // A review that finished without a mechanism answer is asked again, once per head, while it can still answer. const askedReview = run && runState === "live" && mechanism === null && before?.review_asked !== args.head_sha - && (await askReviewForMechanism(ctx, run, args.head_sha, `${repository}#${args.pr_number}`, runAttempt(run))); + && (await askReviewForMechanism(ctx, run, args.head_sha, name, runAttempt(run))); // The one card a person is asked, per judged diff and question; the one it replaces is taken back first. const reason: CardReason | null = cardReason(facts); // A card about the judged files binds to their diff; any other reads the change whole. const cardKey = reason === "judged" && key !== undefined ? key : wholeKey; const stale = cardStale(beforeKey, { diffs: reason ? [cardKey] : [key, wholeKey].filter((k): k is string => !!k), reason, success: verdict.state === "success" }); - if (stale && before?.card_id) await withdrawApprovalCard(ctx, before.card_id, now, "The pull request's judged diff or what it waits on changed; a new card asks if anything is needed."); + if (stale && before?.card_id) await withdrawApprovalCard(ctx, before.card_id, now, `${landing ? "The landing's" : "The pull request's"} judged diff or what it waits on changed; a new card asks if anything is needed.`); const posted = reason ? await postApprovalCard(ctx, { - repository, pr_number: args.pr_number, head_sha: args.head_sha, key: cardKey, judged, reason, to: to[reason], run, pr, + repository, ...byPr, head_sha: args.head_sha, key: cardKey, judged, reason, to: to[reason], run, pr, title: args.people?.title ?? pr?.title ?? "", before_key: beforeKey, now, // The automatic review's own words are what the card shows, its reason or why it gave none. ...(auto ? { words: `${auto.failed ? "The automatic review could not answer" : `The automatic review of this head (${auto.mechanism ? "a mechanism" : "not a mechanism"})`}: ${auto.reason}` } : {}), ...(held ? { held } : {}), }) : null; - for (const row of rows) { - await patchPullRequest(ctx, row._id, { - approval: { - head_sha: args.head_sha, state: verdict.state, description: verdict.description, - // Both keys as approvals bind to them: the run's own card stamps them (lib/changeApprovalRows approvalStampFor). - ...(key !== undefined ? { judged_key: key, judged_files: judged, whole_key: wholeKey } : {}), - ...(run ? { run_id: run._id } : {}), - ...(typeof mechanism === "boolean" ? { mechanism } : {}), - ...(captainRevert ? { captain_revert: true } : {}), - ...(posted ? { card_key: posted.card_key, card_id: posted.card_id } : beforeKey && !stale ? { card_key: beforeKey, ...(before?.card_id ? { card_id: before.card_id } : {}) } : {}), - ...(askedReview ? { review_asked: args.head_sha } : before?.review_asked ? { review_asked: before.review_asked } : {}), - ...(before?.engineer_told ? { engineer_told: true } : {}), - // An answer is stored only over its own head's claim (or nothing): an older head's late answer never - // overwrites a newer head's record, though its hold still holds. - ...(answer && (!before?.automatic || before.automatic.head_sha === args.head_sha) ? { automatic: answer } : before?.automatic ? { automatic: before.automatic } : {}), - ...(held ? { held } : {}), - }, - }); - } + const record = { + head_sha: args.head_sha, state: verdict.state, description: verdict.description, + // Both keys as approvals bind to them: the run's own card stamps them (lib/changeApprovalRows approvalStampFor). + ...(key !== undefined ? { judged_key: key, judged_files: judged, whole_key: wholeKey } : {}), + ...(run ? { run_id: run._id } : {}), + ...(typeof mechanism === "boolean" ? { mechanism } : {}), + ...(captainRevert ? { captain_revert: true } : {}), + ...(posted ? { card_key: posted.card_key, card_id: posted.card_id } : beforeKey && !stale ? { card_key: beforeKey, ...(before?.card_id ? { card_id: before.card_id } : {}) } : {}), + ...(askedReview ? { review_asked: args.head_sha } : before?.review_asked ? { review_asked: before.review_asked } : {}), + ...(before?.engineer_told ? { engineer_told: true } : {}), + // An answer is stored only over its own head's claim (or nothing): an older head's late answer never + // overwrites a newer head's record, though its hold still holds. + ...(answer && (!before?.automatic || before.automatic.head_sha === args.head_sha) ? { automatic: answer } : before?.automatic ? { automatic: before.automatic } : {}), + ...(held ? { held } : {}), + }; + if (landing) await ctx.db.patch(run._id, { landing: { ...run.landing, approval: record } }); + for (const row of rows) await patchPullRequest(ctx, row._id, { approval: record }); // A hold an older head's answer set reaches the pull request's head now, not at the next sweep. - if (newHold && pr?.head_sha && pr.head_sha !== args.head_sha) await ctx.scheduler.runAfter(0, internal.changeApprovals.evaluate, { repository, pr_number: args.pr_number, post: true }); - return { ...verdict, context: approvalContext(gate.mode) }; + if (newHold && pr?.head_sha && pr.head_sha !== args.head_sha) await ctx.scheduler.runAfter(0, internal.changeApprovals.evaluate, { repository, pr_number: args.pr_number!, post: true }); + return { ...verdict, context }; }, }); /** The person who installed codecast's app for the repository: a personal install's owner, else who installed it. */ const installerOf = (installation: any): Id<"users"> | undefined => installation?.scope_user_id ?? installation?.installed_by_user_id ?? undefined; -/** The status was worked out and could not be posted: the pull request says why. */ +/** The status was worked out and could not be posted: the pull request (or the run's landing) says why. */ export const noteUnposted = internalMutation({ - args: { repository: v.string(), pr_number: v.number(), head_sha: v.string(), reason: v.string() }, + args: { repository: v.string(), pr_number: v.optional(v.number()), run_id: v.optional(v.id("workflow_runs")), head_sha: v.string(), reason: v.string() }, handler: async (ctx, args) => { - const rows = await ctx.db.query("pull_requests").withIndex("by_repository_number", (q) => q.eq("repository", args.repository).eq("number", args.pr_number)).collect(); + if (args.run_id) { + const run = await ctx.db.get(args.run_id); + const a = run?.landing?.approval; + if (run?.landing && a?.head_sha === args.head_sha) await ctx.db.patch(run._id, { landing: { ...run.landing, approval: { ...a, state: "unposted", description: args.reason } } }); + return; + } + if (args.pr_number === undefined) return; + const rows = await ctx.db.query("pull_requests").withIndex("by_repository_number", (q) => q.eq("repository", args.repository).eq("number", args.pr_number!)).collect(); for (const pr of rows) { if (pr.approval?.head_sha !== args.head_sha) continue; await patchPullRequest(ctx, pr._id, { approval: { ...pr.approval, state: "unposted", description: args.reason } }); diff --git a/packages/convex/convex/ciPool.test.ts b/packages/convex/convex/ciPool.test.ts new file mode 100644 index 0000000000..49d4db6423 --- /dev/null +++ b/packages/convex/convex/ciPool.test.ts @@ -0,0 +1,244 @@ +import { describe, expect, test } from "bun:test"; +import { applyPlan, BUSY_STALE_MS, withLeaseDemand, demandFromRows, IDLE_MS, MAX_AWAKE, ON_DEMAND_HOURS, parsePoolHosts, planCiPool, poolSettings, QUEUE_WINDOW_MS, type PoolHost } from "./ciPool"; +import { Ec2Error } from "./lib/castMachineAws"; + +const now = Date.parse("2026-11-28T21:00:00Z"); +const host = (name: string, over: Partial = {}): PoolHost => + ({ id: `i-${name.replace(/\D/g, "").padStart(8, "0")}`, name, market: "spot", state: "stopped", startedAt: now - 3 * 3600_000, ...over }); +const none = { queued: 0, busy: [], lastActivity: {} }; + +// Shaped like a real DescribeInstances answer for the pool (codecast-ci-1, 2026-11-28), trimmed. +function instanceXml(o: { id: string; name: string; state: string; code: number; spot: boolean; launch: string; role?: string }) { + return `${o.id}ami-0fcb94efd00764cf7${o.code}${o.state}` + + `c7i.4xlarge${o.launch}${o.spot ? "spotsir-c5983rpk" : ""}` + + `aws:ec2launchtemplate:version1Name${o.name}` + + `codecast-role${o.role ?? "ci-pool"}` + + `eni-0380b098e4cab522c045275879943`; +} +const describeXml = (...items: string[]) => + `rr-1${items.join("")}`; + +describe("parsePoolHosts", () => { + test("reads each instance's own name, market, state and start, and skips anything without the pool tag", () => { + const xml = describeXml( + instanceXml({ id: "i-0cd8f718dbabbba52", name: "codecast-ci-1", state: "running", code: 16, spot: true, launch: "2026-11-28T20:33:21.000Z" }), + instanceXml({ id: "i-0aaaaaaaaaaaaaaa1", name: "codecast-ci-od-1", state: "stopped", code: 80, spot: false, launch: "2026-11-27T10:00:00.000Z" }), + instanceXml({ id: "i-0bbbbbbbbbbbbbbb2", name: "convex-prod", state: "running", code: 16, spot: false, launch: "2026-11-01T00:00:00.000Z", role: "prod" }), + ); + expect(parsePoolHosts(xml)).toEqual([ + { id: "i-0cd8f718dbabbba52", name: "codecast-ci-1", market: "spot", state: "running", startedAt: Date.parse("2026-11-28T20:33:21Z") }, + { id: "i-0aaaaaaaaaaaaaaa1", name: "codecast-ci-od-1", market: "on-demand", state: "stopped", startedAt: Date.parse("2026-11-27T10:00:00Z") }, + ]); + }); + + test("reads EC2's own indented XML", () => { + const xml = describeXml(instanceXml({ id: "i-09b1486610133bd7a", name: "codecast-ci-2", state: "running", code: 16, spot: true, launch: "2026-11-29T03:12:37.000Z" })) + .replace(/>\n <"); + expect(parsePoolHosts(xml)).toEqual([{ id: "i-09b1486610133bd7a", name: "codecast-ci-2", market: "spot", state: "running", startedAt: Date.parse("2026-11-29T03:12:37Z") }]); + }); +}); + +describe("demandFromRows", () => { + test("a sha with an Actions row and no runner row is queued; a runner row in progress keeps its host busy", () => { + const d = demandFromRows([ + { sha: "a", kind: "workflow", status: "queued", updated_at: now - 60_000 }, + { sha: "b", kind: "workflow", status: "in_progress", updated_at: now - 60_000 }, + { sha: "b", kind: "runner", status: "in_progress", host: "codecast-ci-1", updated_at: now - 120_000 }, + { sha: "c", kind: "workflow", status: "completed", updated_at: now - QUEUE_WINDOW_MS - 1 }, + { sha: "d", kind: "runner", status: "in_progress", host: "codecast-ci-2", updated_at: now - BUSY_STALE_MS - 1 }, + ], now); + expect(d.queued).toBe(1); + expect(d.busy).toEqual(["codecast-ci-1"]); + expect(d.lastActivity).toEqual({ "codecast-ci-1": now - 120_000, "codecast-ci-2": now - BUSY_STALE_MS - 1 }); + }); +}); + +describe("planCiPool", () => { + test("nothing queued and nothing awake: nothing to do", () => { + expect(planCiPool([host("codecast-ci-1"), host("codecast-ci-2")], none, now)).toEqual({ candidates: [], want: 0, stop: [] }); + }); + + test("queued work with no free host wakes one, spot before on-demand", () => { + const od = host("codecast-ci-9", { market: "on-demand" }); + const plan = planCiPool([od, host("codecast-ci-2"), host("codecast-ci-1")], { ...none, queued: 1 }, now); + expect(plan.want).toBe(1); + expect(plan.candidates).toEqual([host("codecast-ci-1").id, host("codecast-ci-2").id, od.id]); + }); + + test("a free awake host takes the queued work: nothing starts, and it is not stopped", () => { + const up = host("codecast-ci-1", { state: "running", startedAt: now - 2 * IDLE_MS }); + expect(planCiPool([up, host("codecast-ci-2")], { ...none, queued: 1 }, now)).toEqual({ candidates: [], want: 0, stop: [] }); + }); + + test("a busy host does not count as free", () => { + const up = host("codecast-ci-1", { state: "running" }); + expect(planCiPool([up, host("codecast-ci-2")], { queued: 1, busy: ["codecast-ci-1"], lastActivity: {} }, now).want).toBe(1); + }); + + test("never more than MAX_AWAKE awake", () => { + const hosts = Array.from({ length: 6 }, (_, i) => host(`codecast-ci-${i + 1}`, i < MAX_AWAKE - 1 ? { state: "running" } : {})); + const busy = hosts.filter((h) => h.state === "running").map((h) => h.name); + expect(planCiPool(hosts, { queued: 10, busy, lastActivity: {} }, now).want).toBe(1); + }); + + test("a host idle past IDLE_MS is stopped; one that just started or just ran is kept", () => { + const idle = host("codecast-ci-1", { state: "running", startedAt: now - IDLE_MS - 1 }); + const fresh = host("codecast-ci-2", { state: "running", startedAt: now - 60_000 }); + const ran = host("codecast-ci-3", { state: "running", startedAt: now - 3 * IDLE_MS }); + const plan = planCiPool([idle, fresh, ran], { queued: 0, busy: [], lastActivity: { "codecast-ci-3": now - 60_000 } }, now); + expect(plan.stop).toEqual([idle.id]); + }); + + test("a busy host is never stopped, however long since its start", () => { + const up = host("codecast-ci-1", { state: "running", startedAt: now - 10 * IDLE_MS }); + expect(planCiPool([up], { queued: 0, busy: ["codecast-ci-1"], lastActivity: {} }, now).stop).toEqual([]); + }); +}); + +describe("applyPlan", () => { + test("a spot host that refuses to start falls through to the next, on-demand last", async () => { + const calls: string[] = []; + const call = async (p: Record) => { + calls.push(`${p.Action} ${p["InstanceId.1"]}`); + if (p["InstanceId.1"] === "i-spot1") throw new Ec2Error("InsufficientInstanceCapacity"); + if (p["InstanceId.1"] === "i-spot2") throw new Ec2Error("IncorrectSpotRequestState"); + return ""; + }; + const out = await applyPlan({ candidates: ["i-spot1", "i-spot2", "i-od1", "i-od2"], want: 1, stop: ["i-idle"] }, call, () => {}); + expect(out).toEqual({ started: ["i-od1"], stopped: ["i-idle"] }); + expect(calls).toEqual(["StopInstances i-idle", "StartInstances i-spot1", "StartInstances i-spot2", "StartInstances i-od1"]); + }); + + test("a spot host still settling after a stop is waited for, not replaced by on-demand; a capacity refusal is", async () => { + const calls: string[] = []; + const refuse: Record = { "i-spot1": "InsufficientInstanceCapacity", "i-spot2": "IncorrectSpotRequestState" }; + const call = async (p: Record) => { + calls.push(p["InstanceId.1"]!); + if (refuse[p["InstanceId.1"]!]) throw new Ec2Error(refuse[p["InstanceId.1"]!]!); + return ""; + }; + const plan = { candidates: ["i-spot1", "i-spot2", "i-od1"], want: 1, stop: [], onDemand: ["i-od1"] }; + expect(await applyPlan(plan, call, () => {})).toEqual({ started: [], stopped: [] }); + expect(calls).toEqual(["i-spot1", "i-spot2"]); + calls.length = 0; + expect(await applyPlan({ ...plan, candidates: ["i-spot1", "i-od1"] }, call, () => {})).toEqual({ started: ["i-od1"], stopped: [] }); + }); + + test("the plan names its on-demand candidates", () => { + const od = host("codecast-ci-od-9", { market: "on-demand" }); + expect(planCiPool([od, host("codecast-ci-2")], { ...none, queued: 1 }, now).onDemand).toEqual([od.id]); + }); + + test("any other AWS error stops the pass", async () => { + const call = async () => { throw new Ec2Error("UnauthorizedOperation"); }; + await expect(applyPlan({ candidates: ["i-1"], want: 1, stop: [] }, call, () => {})).rejects.toThrow("UnauthorizedOperation"); + }); +}); + +describe("withLeaseDemand", () => { + const base = { queued: 3, busy: ["codecast-ci-1"], lastActivity: { "codecast-ci-1": now } }; + test("the lease queue replaces commit_ci's stand-in, and its busy hosts add to the runner rows'", () => { + const lanes = [ + { repository: "codecast-sh/codecast", lane: "darwin", waiting: 9, running: 0, busy_hosts: ["intern-box-m4pro"] }, + { repository: "codecast-sh/codecast", lane: "linux", waiting: 1, running: 1, busy_hosts: ["codecast-ci-2"] }, + ]; + expect(withLeaseDemand(base, lanes)).toEqual({ queued: 1, busy: ["codecast-ci-1", "codecast-ci-2"], lastActivity: base.lastActivity }); + }); + test("no lease module, or no linux lane for the pool: commit_ci decides", () => { + expect(withLeaseDemand(base, null)).toBe(base); + expect(withLeaseDemand(base, [{ repository: "acme/app", lane: "linux", waiting: 5, running: 0, busy_hosts: [] }])).toBe(base); + }); +}); + +describe("demand (convex-test)", () => { + test("reads only the pool repository's recent commit_ci rows", async () => { + const { convexTest } = await import("convex-test"); + const schema = (await import("./schema")).default; + const { allModules } = await import("./testModules.testkit"); + const { internal } = await import("./_generated/api"); + const t = convexTest(schema, allModules); + const at = Date.now(); + await t.run(async (ctx: any) => { + const row = (repository: string, sha: string, kind: string, status: string, updated_at: number, host?: string) => + ctx.db.insert("commit_ci", { workspace: "user:x", repository, sha, name: "CI", kind, status, started_at: updated_at, updated_at, ...(host ? { host } : {}) }); + await row("codecast-sh/codecast", "a".repeat(40), "workflow", "in_progress", at - 60_000); + await row("codecast-sh/codecast", "b".repeat(40), "workflow", "in_progress", at - 60_000); + await row("codecast-sh/codecast", "b".repeat(40), "runner", "in_progress", at - 30_000, "codecast-ci-1"); + await row("codecast-sh/codecast", "c".repeat(40), "workflow", "queued", at - 3 * 3600_000); + await row("acme/app", "d".repeat(40), "workflow", "queued", at - 60_000); + }); + const d = await t.query(internal.ciPool.demand, {}); + expect(d.queued).toBe(1); + expect(d.busy).toEqual(["codecast-ci-1"]); + }); +}); + +describe("tick (convex-test)", () => { + test("a pool registration that throws (no team routes the repository) is logged and the tick goes on", async () => { + const { convexTest } = await import("convex-test"); + const { setSystemTime } = await import("bun:test"); + const schema = (await import("./schema")).default; + const { allModules } = await import("./testModules.testkit"); + const { internal } = await import("./_generated/api"); + const env = { CI_POOL_ENABLED: process.env.CI_POOL_ENABLED, ID: process.env.CAST_MACHINES_AWS_ACCESS_KEY_ID, SECRET: process.env.CAST_MACHINES_AWS_SECRET_ACCESS_KEY }; + const realFetch = globalThis.fetch; + const warn = console.warn; + const warned: string[] = []; + process.env.CI_POOL_ENABLED = "1"; + process.env.CAST_MACHINES_AWS_ACCESS_KEY_ID = "AKIATEST"; + process.env.CAST_MACHINES_AWS_SECRET_ACCESS_KEY = "secret"; + globalThis.fetch = (async () => new Response(describeXml(instanceXml({ id: "i-0000000000000001", name: "codecast-ci-1", state: "stopped", code: 80, spot: true, launch: "2026-11-28T18:00:00.000Z" })))) as unknown as typeof fetch; + console.warn = (...a: unknown[]) => { warned.push(a.map(String).join(" ")); }; + // Minute 0 is when the tick registers the pool; no team has the GitHub App on the repository, so it throws. + setSystemTime(new Date("2026-11-28T22:00:10Z")); + try { + const t = convexTest(schema, allModules); + const out = await t.action(internal.ciPool.tick, {}); + expect(out).toMatchObject({ hosts: 1, queued: 0 }); + expect(warned.some((w) => w.includes("registering codecast-sh/codecast failed") && w.includes("No codecast team"))).toBe(true); + } finally { + setSystemTime(); + globalThis.fetch = realFetch; + console.warn = warn; + for (const [k, v] of [["CI_POOL_ENABLED", env.CI_POOL_ENABLED], ["CAST_MACHINES_AWS_ACCESS_KEY_ID", env.ID], ["CAST_MACHINES_AWS_SECRET_ACCESS_KEY", env.SECRET]] as const) { + if (v === undefined) delete process.env[k]; else process.env[k] = v; + } + } + }); +}); + +describe("idle window and on-demand cap", () => { + const running = (name: string, over: Partial = {}) => host(name, { state: "running", startedAt: now - 60 * 60_000, ...over }); + const quiet = (names: string[], ago: number) => ({ ...none, lastActivity: Object.fromEntries(names.map((n) => [n, now - ago])) }); + + test("settings come from the environment, with defaults for absent or bad values", () => { + expect(poolSettings({}, 0)).toEqual({ idleMs: IDLE_MS, onDemand: true, onDemandHours: ON_DEMAND_HOURS }); + expect(poolSettings({ CI_POOL_IDLE_MINUTES: "2", CI_POOL_ON_DEMAND_HOURS: "10" }, 10 * 3600)).toEqual({ idleMs: 120_000, onDemand: false, onDemandHours: 10 }); + expect(poolSettings({ CI_POOL_IDLE_MINUTES: "soon", CI_POOL_ON_DEMAND_HOURS: "-1" }, 0)).toMatchObject({ idleMs: IDLE_MS, onDemandHours: ON_DEMAND_HOURS }); + }); + + test("a spot host stops at the configured window, an on-demand host after a minute", () => { + const spot = running("codecast-ci-1"); + const od = running("codecast-ci-od-9", { market: "on-demand" }); + const s = { idleMs: 10 * 60_000, onDemand: true }; + expect(planCiPool([spot, od], quiet([spot.name, od.name], 2 * 60_000), now, s).stop).toEqual([od.id]); + expect(planCiPool([spot, od], quiet([spot.name, od.name], 10 * 60_000), now, s).stop).toEqual([od.id, spot.id]); + }); + + test("queued work keeps a free host; the on-demand one goes first when there are more free hosts than work", () => { + const spot = running("codecast-ci-1"); + const od = running("codecast-ci-od-9", { market: "on-demand" }); + expect(planCiPool([spot, od], { ...quiet([spot.name, od.name], IDLE_MS), queued: 1 }, now).stop).toEqual([od.id]); + }); + + test("once the month's on-demand hours are spent: no on-demand start, and a free one stops even with work queued", () => { + const od = host("codecast-ci-od-9", { market: "on-demand" }); + const off = { idleMs: IDLE_MS, onDemand: false }; + expect(planCiPool([od, host("codecast-ci-1")], { ...none, queued: 1 }, now, off)).toEqual({ candidates: [host("codecast-ci-1").id], want: 1, stop: [] }); + expect(planCiPool([od], { ...none, queued: 1 }, now, off)).toEqual({ candidates: [], want: 0, stop: [] }); + const up = running("codecast-ci-od-9", { market: "on-demand", startedAt: now - 30_000 }); + expect(planCiPool([up], { ...none, queued: 2 }, now, off).stop).toEqual([up.id]); + // A run in progress on it finishes first. + expect(planCiPool([up], { queued: 2, busy: [up.name], lastActivity: {} }, now, off).stop).toEqual([]); + }); +}); diff --git a/packages/convex/convex/http.ts b/packages/convex/convex/http.ts index 9bcae9d0b1..05dd5be65a 100644 --- a/packages/convex/convex/http.ts +++ b/packages/convex/convex/http.ts @@ -22,6 +22,7 @@ import { cliAuthRequest } from "./cliAuthHttp"; import { registerCliPreflight, registerCliRoute, type CliRouteOptions } from "./lib/cliRoute"; import { registerPriorityRoutes } from "./lib/priorityRoutes"; import { registerDeployPauseRoutes } from "./lib/deployPauseRoutes"; +import { registerCiRoutes } from "./lib/ciRoutes"; import { registerSessionOwnerRoutes } from "./lib/sessionOwnerRoutes"; import { INGEST_PREFIXES, ingestPreflight, ingestServe } from "./ingestHttp"; import { publishedKeys } from "./lib/codecastSigning"; @@ -2761,6 +2762,7 @@ http.route({ api_token: body.api_token, status: body.status, ...(body.project_id ? { project_id: body.project_id } : {}), + ...(typeof body.originating_conversation_id === "string" ? { originating_conversation_id: body.originating_conversation_id } : {}), ...(Array.isArray(body.refs) ? { refs: body.refs.filter((r: unknown) => typeof r === "string").slice(0, 200) } : {}), }); return new Response(JSON.stringify(result), { status: 200, @@ -3462,7 +3464,7 @@ cliRoute("/cli/line/merge/check", async (ctx, body) => ctx.runQuery(api.orgLineM cliRoute("/cli/line/merge/record", async (ctx, body) => ctx.runMutation(api.orgLineMerge.record, body)); // The Merge station: the run's own graph cleared it to land with no card, on the proof the server recorded. cliRoute("/cli/workflow-runs/clear", async (ctx, body) => ctx.runMutation(api.orgLineMerge.clearForMerge, body)); -for (const [route, fn, write] of [["workflow-runs/ci-verdict", api.orgLineMerge.recordCiVerdict, true], ["workflow-runs/review-verdict", api.orgLineMerge.recordReviewVerdict, true], ["workflow-runs/rebase", api.orgLineMerge.recordStationRebase, true], ["workflow-runs/pr", api.orgLineMerge.recordRunPr, true], ["workflow-runs/merge-proof", api.orgLineMerge.mergeProof, false], ["repo-lease", api.repoLeases.lease, true], ["main-red/open", api.mainRed.open, false]] as const) cliRoute(`/cli/${route}`, async (ctx, body) => write ? ctx.runMutation(fn as any, body) : ctx.runQuery(fn as any, body)); +for (const [route, fn, write] of [["workflow-runs/ci-verdict", api.orgLineMerge.recordCiVerdict, true], ["workflow-runs/review-verdict", api.orgLineMerge.recordReviewVerdict, true], ["workflow-runs/rebase", api.orgLineMerge.recordStationRebase, true], ["workflow-runs/pr", api.orgLineMerge.recordRunPr, true], ["workflow-runs/landing", api.orgLineMerge.recordRunLanding, true], ["workflow-runs/merge-proof", api.orgLineMerge.mergeProof, false], ["repo-lease", api.repoLeases.lease, true], ["main-red/open", api.mainRed.open, false]] as const) cliRoute(`/cli/${route}`, async (ctx, body) => write ? ctx.runMutation(fn as any, body) : ctx.runQuery(fn as any, body)); cliRoute("/cli/line/requeue", async (ctx, body) => ctx.runMutation(api.orgLine.requeueFromCli, body)); // `cast flow show|on|off` on a team's live flow (liveFlows.ts). on and off are a person's, on the web: the CLI's are refused with that reason. cliRoute("/cli/flow/live/show", async (ctx, body) => ctx.runQuery(api.liveFlows.showFromCli, body)); @@ -3482,9 +3484,6 @@ cliRoute("/cli/line/fixloop/summary", async (ctx, body) => ctx.runQuery((api as cliRoute("/cli/deploys/get", async (ctx, body) => ctx.runQuery(api.deploys.get, body)); // A team's CLI floor and which of its machines run a release (teamCliFloor.ts). for (const [route, fn, write] of [["set", api.teamCliFloor.set, true], ["fleet", api.teamCliFloor.fleet, false], ["lower", api.teamCliFloor.lower, true], ["forced", api.teamCliFloor.forcedRelease, false], ["tell-release", api.teamCliFloor.tellRelease, true], ["tell-other-teams", api.teamCliFloor.tellOtherTeams, true]] as const) cliRoute(`/cli/team-cli-floor/${route}`, async (ctx, body) => write ? ctx.runMutation(fn as any, body) : ctx.runQuery(fn as any, body)); -// Our own CI runner's verdict per commit (ciVerdicts.ts): logs upload through /cli/images/upload-url first. -cliRoute("/cli/ci/record", async (ctx, body) => ctx.runMutation(api.ciVerdicts.record, body)); -for (const r of ["show", "log"] as const) cliRoute(`/cli/ci/${r}`, async (ctx, body) => ctx.runQuery(api.ciVerdicts[r], body)); // Deploy targets (deploys.md DP10 to DP14): the checkout's declared targets, each one's live sha and waiting queue, a deploy of one from codecast, a ship pass. cliRoute("/cli/deploys/targets/publish", async (ctx, body) => ctx.runMutation(api.deployTargets.publish, body), { forwardDeviceId: true }); cliRoute("/cli/deploys/targets", async (ctx, body) => ctx.runQuery(api.deployTargets.view, body)); @@ -3497,7 +3496,7 @@ cliRoute("/cli/pipelines", async (ctx, body) => ctx.runQuery(api.pipelines.forTe cliRoute("/cli/checkouts/report", async (ctx, body) => ctx.runMutation(api.checkouts.report, body), { forwardDeviceId: true }); cliRoute("/cli/checkouts", async (ctx, body) => ctx.runQuery(api.checkouts.forTeam, body)); cliRoute("/cli/deploys/target/request", async (ctx, body) => ctx.runMutation(api.deployTargets.request, body)); -registerDeployPauseRoutes(http); +registerDeployPauseRoutes(http); registerCiRoutes(http); cliRoute("/cli/deploys/target/for-deploy", async (ctx, body) => ctx.runQuery(api.deployTargets.forDeploy, body)); cliRoute("/cli/deploys/main-commits", async (ctx, body) => ctx.runMutation(api.deployTargets.reportMainCommits, body)); cliRoute("/cli/deploys/ship-pass", async (ctx, body) => ctx.runMutation(api.deployTargets.recordShipPass, body), { forwardDeviceId: true }); diff --git a/packages/convex/convex/judgeReview.test.ts b/packages/convex/convex/judgeReview.test.ts index 6a8cb4bf8d..133663232c 100644 --- a/packages/convex/convex/judgeReview.test.ts +++ b/packages/convex/convex/judgeReview.test.ts @@ -10,6 +10,7 @@ import { hashToken } from "./apiTokens"; import { findingLabeled, markFindingWrong, sweepJudgeReviews } from "./judgeReview"; import { JUDGE_REVIEW_ATTEMPTS, JUDGE_REVIEW_GRAPH } from "@codecast/shared/contracts/judgeReview"; import { LINE_RUNS_PER_RUNNER, type LineLoads } from "./orgLine"; +import { roleHandsToday } from "./lib/orgCaps"; const TOKEN = "cast_judge_review_token"; const T0 = Date.now(); @@ -80,7 +81,7 @@ describe("marking a finding wrong", () => { const commands = await s.t.run(async (ctx) => await ctx.db.query("daemon_commands").collect()); expect(commands.map((c: any) => JSON.parse(c.args))).toEqual([{ workflow_run_id: run._id, workflow_slug: JUDGE_REVIEW_GRAPH }]); // The diagnosis is a hand of the role. - expect((await s.get(s.role)).counters.hands).toBe(1); + expect(await s.t.run(async (ctx) => await roleHandsToday(ctx, (await ctx.db.get(s.role))!, Date.now()))).toBe(1); }); test("in a trial project the line never starts a diagnosis, and the run that ruled it records one from waiting", async () => { diff --git a/packages/convex/convex/lib/changeApprovalReads.ts b/packages/convex/convex/lib/changeApprovalReads.ts new file mode 100644 index 0000000000..cfae49f167 --- /dev/null +++ b/packages/convex/convex/lib/changeApprovalReads.ts @@ -0,0 +1,219 @@ +// What codecast's approval status reads from GitHub for one change (changeApprovals.ts holds the rule and its +// header): the pull request's or landing commit's files, main's judges, owners and engineers files beside the +// judges file, the judged paths and both diff keys against the merge base, and the commits' Requested-by and +// revert lines. +import { fetchPRFiles, PR_FILES_CAP, type PRPath } from "../githubApi"; +import { MECHANISM_FILE } from "./automaticReview"; +import { GITHUB, encodePath, rest } from "./githubRest"; +import { diffKey, isJudged, judgedPaths, keyChanged, keyEntriesFor, ownerOf, parseJudges, parseOwners, pathDiffsOf, pathsOf, requestedBy, revertedShas, type GitHubFile } from "./judgedDiff"; + +/** The newest status GitHub shows on a commit under one context (its list is newest first), or undefined. */ +export async function shownStatus(repository: string, sha: string, context: string, token: string): Promise<{ state?: string; description?: string } | undefined> { + const statuses = await rest(`${GITHUB}/repos/${repository}/commits/${sha}/statuses?per_page=100`, token); + return (Array.isArray(statuses.json) ? statuses.json : []).find((s: any) => s?.context === context); +} + +const dirOf = (path: string) => (path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""); +const baseOf = (path: string) => path.slice(path.lastIndexOf("/") + 1); + +/** + * Modes (from each parent tree's entries) and texts (a renamed file's two sides), by GraphQL "sha:path" + * expressions, a hundred to a call. A mode reads as git prints it ("100644"); a binary or cut text reads null. + */ +async function readObjects(repository: string, token: string, wants: Array<{ sha: string; path: string; text: boolean }>): Promise<{ mode: (sha: string, path: string) => string | null; text: (sha: string, path: string) => string | null }> { + const [owner, name] = repository.split("/"); + const trees = new Map>(); + const texts = new Map(); + const asks = [ + ...[...new Set(wants.map((w) => `${w.sha}:${dirOf(w.path)}`))].map((e) => ({ e, kind: "tree" as const })), + ...[...new Set(wants.filter((w) => w.text).map((w) => `${w.sha}:${w.path}`))].map((e) => ({ e, kind: "blob" as const })), + ]; + for (let i = 0; i < asks.length; i += 100) { + const chunk = asks.slice(i, i + 100); + const vars = chunk.map((_, j) => `$e${j}: String!`).join(", "); + const fields = chunk.map((_, j) => `o${j}: object(expression: $e${j}) { ... on Tree { entries { name mode } } ... on Blob { text isBinary isTruncated } }`).join("\n"); + const variables: Record = { owner, name }; + chunk.forEach((a, j) => { variables[`e${j}`] = a.e; }); + const r = await rest(`${GITHUB}/graphql`, token, { method: "POST", body: { query: `query($owner: String!, $name: String!, ${vars}) { repository(owner: $owner, name: $name) { ${fields} } }`, variables } }); + if (r.json?.errors?.length) throw new Error(`GitHub GraphQL: ${r.json.errors[0]?.message ?? "error"}`); + const repo = r.json?.data?.repository ?? {}; + chunk.forEach((a, j) => { + const o = repo[`o${j}`]; + if (a.kind === "tree") trees.set(a.e, new Map((o?.entries ?? []).map((x: any) => [String(x.name), Number(x.mode).toString(8)]))); + else texts.set(a.e, o && !o.isBinary && !o.isTruncated && typeof o.text === "string" ? o.text : null); + }); + } + return { + mode: (sha, path) => trees.get(`${sha}:${dirOf(path)}`)?.get(baseOf(path)) ?? null, + text: (sha, path) => texts.get(`${sha}:${path}`) ?? null, + }; +} + +/** GitHub's entries completed with what the rebuild needs from each side, for the paths `keep` selects. */ +async function withSides(repository: string, token: string, files: PRPath[], base: string, head: string, keep: (p: string) => boolean): Promise { + const chosen = files.filter((f) => pathsOf(f).some(keep)); + const wants = chosen.flatMap((f) => { + const old = f.previous_filename ?? f.filename; + const renamed = f.status === "renamed" && !!f.previous_filename; + return [ + ...(f.status === "added" ? [] : [{ sha: base, path: old, text: renamed }]), + ...(f.status === "removed" ? [] : [{ sha: head, path: f.filename, text: renamed }]), + ]; + }); + const read = wants.length ? await readObjects(repository, token, wants) : null; + return chosen.map((f) => { + const old = f.previous_filename ?? f.filename; + const renamed = f.status === "renamed" && !!f.previous_filename; + return { + ...f, + base_mode: f.status === "added" ? null : read!.mode(base, old), + head_mode: f.status === "removed" ? null : read!.mode(head, f.filename), + ...(renamed ? { base_text: read!.text(base, old), head_text: read!.text(head, f.filename) } : {}), + }; + }); +} + +/** + * The key of the pull request's whole diff against its merge base (patch-id --verbatim, as the judged diff's): what a + * card that read the change whole approves, so a pure rebase carries it and any code change asks again. When a file's + * diff cannot be rebuilt (binary, too large, unreadable), undefined: settle then keys it to the head, so every push + * asks again. + */ +export async function wholeKey(repository: string, token: string, paths: PRPath[], base: string, head: string): Promise { + try { + const all = pathDiffsOf(await withSides(repository, token, paths, base, head, () => true), () => true); + return "unreadable" in all ? undefined : await diffKey(all.diffs); + } catch { + return undefined; + } +} + +async function prMessages(repository: string, token: string, prNumber: number): Promise { + const commits: any[] = []; + for (let page = 1; page <= 3; page++) { + const r = await rest(`${GITHUB}/repos/${repository}/pulls/${prNumber}/commits?per_page=100&page=${page}`, token); + const batch: any[] = r.json ?? []; + commits.push(...batch); + if (batch.length < 100) break; + } + return commits.map((c) => String(c.commit?.message ?? "")); +} + +/** Who a card may go to, as GitHub and main's files beside the judges file name them. */ +export type PullPeople = { + title: string; + author_login: string | null; + /** The area's owner by main's owners file (lib/judgedDiff parseOwners), or null when the file or its area is missing. */ + area_owner: { user_id: string; name: string } | null; + /** Main's engineers file: one ` ` a line; null when GitHub could not be read (none is not []). */ + engineers: Array<{ user_id: string; name: string }> | null; +}; + +export type PullRead = + | { open: false } + | { open: true; head_sha: string; unreadable: string; judges?: string[]; people: PullPeople } + | { + open: true; head_sha: string; judged: string[]; key: string; whole_key?: string; judges: string[]; reverts: boolean; requested_by?: string; people: PullPeople; + base_sha: string; paths: string[]; default_branch: string; + /** Where main's mechanism file is (lib/automaticReview MECHANISM_FILE, beside the judges file): read only when the automatic review runs. */ + mechanism_path: string; + }; + +/** Main's engineers file: ` ` a line, blank and "#" lines skipped. */ +export function parseEngineers(text: string): Array<{ user_id: string; name: string }> { + return text.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).flatMap((l) => { + const m = /^(\S+)\s+(.+)$/.exec(l); + return m ? [{ user_id: m[1], name: m[2].trim() }] : []; + }); +} + +/** Everything the rule reads from GitHub for one pull request. Never throws past the head: a failure is unreadable. */ +export async function readPull(repository: string, prNumber: number, token: string, judgesPath: string): Promise { + const pr = await fetchPRFiles(repository, prNumber, token); + if (pr.state !== "open" || !pr.head_sha) return { open: false }; + return readChange(repository, token, judgesPath, { + head: pr.head_sha, main: pr.default_branch ?? pr.base_ref ?? "main", files: pr.paths, complete: pr.complete && pr.paths.length < PR_FILES_CAP, + title: pr.title ?? "", author_login: pr.author_login ?? null, messages: () => prMessages(repository, token, prNumber), + }); +} + +/** GitHub lists at most this many files in a comparison. */ +const COMPARE_FILES_CAP = 300; + +/** + * The same for a run's landing commit, with no pull request: the change is the comparison of the default branch with + * the commit (its files, merge base and commit messages), titled by the run. Not open when GitHub does not have the + * commit yet (a rebase is recorded before its push) or the default branch already holds it (it landed). + */ +export async function readLanding(repository: string, sha: string, token: string, judgesPath: string, title: string): Promise { + let main = "main"; + try { + const repo = await rest(`${GITHUB}/repos/${repository}`, token); + main = repo.json?.default_branch ?? main; + const compare = await rest(`${GITHUB}/repos/${repository}/compare/${encodeURIComponent(main)}...${sha}`, token); + if (compare.status === 404 || !compare.json) return { open: false }; + if (!compare.json.ahead_by) return { open: false }; + const commits: any[] = compare.json.commits ?? []; + const files: PRPath[] = compare.json.files ?? []; + const merge_base: string | undefined = compare.json.merge_base_commit?.sha; + return readChange(repository, token, judgesPath, { + head: sha, main, files, complete: files.length < COMPARE_FILES_CAP && commits.length === compare.json.ahead_by, merge_base, title, + author_login: commits.at(-1)?.author?.login ?? null, messages: async () => commits.map((c) => String(c.commit?.message ?? "")), + }); + } catch (error) { + return { open: true, head_sha: sha, unreadable: `GitHub (${(error instanceof Error ? error.message : String(error)).slice(0, 60)})`, people: { title, author_login: null, area_owner: null, engineers: null } }; + } +} + +/** + * What the rule reads for a change, once its files are known: main's judges, owners and engineers files, the judged + * paths and both diff keys against the merge base, and the commits' Requested-by and revert lines. Never throws past + * the head: a failure is unreadable. + */ +async function readChange(repository: string, token: string, judgesPath: string, c: { + head: string; main: string; files: PRPath[]; complete: boolean; title: string; author_login: string | null; + /** Known already (a landing's comparison); else read from GitHub's comparison with main. */ + merge_base?: string; + messages: () => Promise; +}): Promise { + const { head, main } = c; + const changed = c.files.flatMap(pathsOf); + const beside = (name: string) => `${judgesPath.includes("/") ? judgesPath.slice(0, judgesPath.lastIndexOf("/") + 1) : ""}${name}`; + const onMain = async (path: string) => { + const r = await rest(`${GITHUB}/repos/${repository}/contents/${encodePath(path)}?ref=${encodeURIComponent(main)}`, token, { accept: "application/vnd.github.raw+json" }); + return r.status === 404 ? null : r.text ?? ""; + }; + const people: PullPeople = { title: c.title, author_login: c.author_login, area_owner: null, engineers: null }; + try { + const [ownersText, engineersText] = await Promise.all([onMain(beside("owners.txt")), onMain(beside("engineers.txt"))]); + const owners = ownersText === null ? [] : parseOwners(ownersText); + people.engineers = engineersText === null ? [] : parseEngineers(engineersText); + people.area_owner = ownerOf(changed, owners); + const judgesText = await onMain(judgesPath); + if (judgesText === null) return { open: true, head_sha: head, unreadable: `${judgesPath} on ${main}`, people }; + const judges = parseJudges(judgesText); + if (!c.complete) return { open: true, head_sha: head, unreadable: "every file (over 3,000, or GitHub cut the list short)", judges, people }; + const mb = c.merge_base ?? (await rest(`${GITHUB}/repos/${repository}/compare/${encodeURIComponent(main)}...${head}`, token)).json?.merge_base_commit?.sha; + if (!mb) return { open: true, head_sha: head, unreadable: `the merge base with ${main}`, judges, people }; + // A `name#key` entry judges a file of that name only when its key's value changed: read both sides to decide. + const byKey = changed.filter((p) => !isJudged(p, judges) && keyEntriesFor(p, judges).length); + const sides = byKey.length ? await readObjects(repository, token, byKey.flatMap((p) => [{ sha: mb, path: p, text: true }, { sha: head, path: p, text: true }])) : null; + const keyHits = byKey.filter((p) => keyEntriesFor(p, judges).some((k) => keyChanged(sides!.text(mb, p), sides!.text(head, p), k.key))); + const judged = judgedPaths(changed, judges, keyHits); + // The area is the judged files' when there are any. + if (judged.length) people.area_owner = ownerOf(judged, owners) ?? people.area_owner; + const rebuilt = pathDiffsOf(await withSides(repository, token, c.files, mb, head, (p) => judged.includes(p)), (p) => judged.includes(p)); + if ("unreadable" in rebuilt) return { open: true, head_sha: head, unreadable: `${rebuilt.unreadable}'s diff`, judges, people }; + const key = await diffKey(rebuilt.diffs); + const whole_key = await wholeKey(repository, token, c.files, mb, head); + const messages = await c.messages(); + const asker = requestedBy(messages); + // The Captain's exemption is for a change of reverts only: one other commit and it is judged like any. + return { + open: true, head_sha: head, judged, key, ...(whole_key ? { whole_key } : {}), judges, reverts: messages.length > 0 && messages.every((m) => revertedShas(m).length > 0), ...(asker ? { requested_by: asker } : {}), people, + base_sha: mb, paths: changed, default_branch: main, mechanism_path: beside(MECHANISM_FILE), + }; + } catch (error) { + return { open: true, head_sha: head, unreadable: `GitHub (${(error instanceof Error ? error.message : String(error)).slice(0, 60)})`, people }; + } +} diff --git a/packages/convex/convex/lib/changeApprovalRecordValidator.ts b/packages/convex/convex/lib/changeApprovalRecordValidator.ts new file mode 100644 index 0000000000..9cf4c5130a --- /dev/null +++ b/packages/convex/convex/lib/changeApprovalRecordValidator.ts @@ -0,0 +1,31 @@ +// The `approval` status codecast last worked out for a change's head (changeApprovals.ts), as schema.ts stores it on a +// pull request's row (pull_requests.approval) and on a run's landing commit (workflow_runs.landing.approval). A leaf: +// schema.ts imports it. +import { v } from "convex/values"; +import { automaticReviewValidator } from "./automaticReviewValidator"; + +export const changeApprovalRecordValidator = v.object({ + head_sha: v.string(), + state: v.union(v.literal("success"), v.literal("pending"), v.literal("unposted")), + description: v.string(), + judged_key: v.optional(v.string()), + judged_files: v.optional(v.array(v.string())), + // The key of the pull request's whole diff, which a card that read the change whole approves. + whole_key: v.optional(v.string()), + run_id: v.optional(v.id("workflow_runs")), + // The review's mechanism answer as it counted, and whether this is a Release Captain's revert. + mechanism: v.optional(v.boolean()), + captain_revert: v.optional(v.boolean()), + // The approval card codecast posted, keyed by the judged diff and the question, so a re-post never posts twice; + // the head whose missing mechanism answer was asked of the review; an engineer told of a merged Captain revert. + card_key: v.optional(v.string()), + card_id: v.optional(v.id("session_decisions")), + review_asked: v.optional(v.string()), + engineer_told: v.optional(v.boolean()), + // With no codecast run behind it: what codecast's automatic review said about a head (lib/automaticReview.ts), + // kept so each head is read once. + automatic: v.optional(automaticReviewValidator), + // An automatic review called a head of this pull request a mechanism: every head is a person's to read + // until a person approves it on a card (changeApprovalRows clearHold). Set by any such answer, whatever its head. + held: v.optional(v.string()), +}); diff --git a/packages/convex/convex/lib/ciRoutes.ts b/packages/convex/convex/lib/ciRoutes.ts new file mode 100644 index 0000000000..1715b5bbf8 --- /dev/null +++ b/packages/convex/convex/lib/ciRoutes.ts @@ -0,0 +1,14 @@ +// The CLI routes for our own CI runner (ciVerdicts.ts, ciLeases.ts), kept out of http.ts, which may not grow. +import type { HttpRouter } from "convex/server"; +import { api } from "../_generated/api"; +import { registerCliRoute } from "./cliRoute"; + +export function registerCiRoutes(http: HttpRouter): void { + // Our own CI runner's verdict per commit (ciVerdicts.ts): logs upload through /cli/images/upload-url first. + registerCliRoute(http, "/cli/ci/record", async (ctx, body) => ctx.runMutation(api.ciVerdicts.record, body)); + for (const r of ["show", "log"] as const) registerCliRoute(http, `/cli/ci/${r}`, async (ctx, body) => ctx.runQuery(api.ciVerdicts[r], body)); + // Which pool host runs a commit's CI (ciLeases.ts): enqueue what landed on main, claim one sha, heartbeat, finish. + for (const r of ["enqueue", "claim", "heartbeat", "finish", "release"] as const) registerCliRoute(http, `/cli/ci/lease/${r}`, async (ctx, body) => ctx.runMutation(api.ciLeases[r], body)); + registerCliRoute(http, "/cli/ci/lease/register-pool", async (ctx, body) => ctx.runMutation(api.ciLeases.registerPool, body)); + registerCliRoute(http, "/cli/ci/lease/pending", async (ctx, body) => ctx.runQuery(api.ciLeases.pending, body)); +} diff --git a/packages/convex/convex/lib/secretAskFirst.ts b/packages/convex/convex/lib/secretAskFirst.ts new file mode 100644 index 0000000000..5810759b70 --- /dev/null +++ b/packages/convex/convex/lib/secretAskFirst.ts @@ -0,0 +1,89 @@ +// Ask first's gate on an agent's read (docs/architecture/vault.md): whether a +// session's approval still holds, and the decision a read files when it does +// not. secrets.ts runs it inside the read; it lives here so the decision path +// (askCore) is not part of the vault module itself. + +import { APPROVE_FOR_SESSION, DENY, SECRET_APPROVAL_TTL_MS, type SecretNeedsApproval, type SecretReadPurpose } from "@codecast/shared/contracts/secrets"; +import type { Doc, Id } from "../_generated/dataModel"; +import { askCore } from "../sessionDecisions"; +import { ASKS_TO_USE, approvalContext, approvalSecrets, joinNames, recordSecretEvent } from "./secretApprovals"; + +type SecretRow = Doc<"secrets">; + +/** An approval lets its session read while the session is active, for SECRET_APPROVAL_TTL_MS at most. */ +export const approvalHolds = (a: Doc<"secret_approvals"> | null | undefined, conversation: any, now: number) => + a?.status === "approved" && now - a.at < SECRET_APPROVAL_TTL_MS && conversation?.status === "active"; + +/** + * Ask first: every gated secret of an agent's read needs an approval for + * that conversation. Without one, a decision is filed on the conversation + * (or the open one reused, its why rewritten when a newer one comes) and the + * read answers with it instead of values. + * Only the conversation's owner reads under its approval, so naming someone + * else's approved session lends nothing. + */ +export async function askFirstGate( + ctx: any, + userId: Id<"users">, + rows: SecretRow[], + conversationId: Id<"conversations"> | undefined, + purpose: SecretReadPurpose, + why: string | undefined, +): Promise { + const gated = rows.filter((r) => r.ask_first); + if (!gated.length) return null; + const conversation: any = conversationId ? await ctx.db.get(conversationId) : null; + // An ended session's approval lends nothing: its id is visible to every other session of the user. + if (!conversation || !conversation.session_id || String(conversation.user_id) !== String(userId) || conversation.status !== "active") { + return { error: `${gated[0].name} is Ask first: a person approves each session's use, so read it from inside your own live agent session` }; + } + const now = Date.now(); + const approvals: { decision: string; secret: string }[] = []; + const fresh: { row: SecretRow; existing: Doc<"secret_approvals"> | null }[] = []; + for (const row of gated) { + const existing = await ctx.db + .query("secret_approvals") + .withIndex("by_secret_conversation", (q: any) => q.eq("secret_id", row._id).eq("conversation_id", conversation._id)) + .first(); + if (approvalHolds(existing, conversation, now)) continue; + const open = existing?.status === "pending" ? await ctx.db.get(existing.decision_id) : null; + if (open?.status === "pending") { + // A newer why rewrites the open decision in place; a repeat without one leaves it as asked. + const context_md = approvalContext(await approvalSecrets(ctx, open._id), purpose, why); + if (why?.trim() && open.context_md !== context_md) await ctx.db.patch(open._id, { context_md, updated_at: now }); + approvals.push({ decision: open.short_id, secret: row.name }); + continue; + } + fresh.push({ row, existing }); + } + // Every secret this read still needs goes on one decision: one Approve, and at most one Touch ID, opens them all. + if (fresh.length) { + const batch = fresh.map((f) => f.row); + const names = joinNames(batch.map((r) => r.name)); + const asked = await askCore(ctx, { userId: conversation.user_id }, { + session_id: conversation.session_id, + question: `${conversation.title || conversation.short_id || "A session"}${ASKS_TO_USE}${names}`, + options: [{ label: APPROVE_FOR_SESSION }, { label: DENY }], + context_md: approvalContext(batch, purpose, why), + category: "access", + blocking: true, + }); + if (asked?.error) return { error: `Could not ask for ${names}: ${asked.error}` }; + if (batch.some((r) => r.touch_id)) await ctx.db.patch(asked.id, { touch_id: true }); + for (const { row, existing } of fresh) { + const fields = { decision_id: asked.id, status: "pending" as const, approved_by: undefined, at: now }; + if (existing) await ctx.db.patch(existing._id, fields); + else await ctx.db.insert("secret_approvals", { secret_id: row._id, workspace: row.workspace, conversation_id: conversation._id, ...fields }); + await recordSecretEvent(ctx, row, "approval_requested", { actor: userId, conversation_id: conversation._id, purpose, decision_id: asked.id }); + approvals.push({ decision: asked.short_id, secret: row.name }); + } + } + if (!approvals.length) return null; + const ids = [...new Set(approvals.map((a) => a.decision))].join(", "); + const names = approvals.map((a) => a.secret).join(", "); + return { + needs_approval: approvals[0], + approvals, + message: `${names} ${approvals.length > 1 ? "are" : "is"} Ask first: a person approves this session in ${ids}. End your turn dormant naming ${ids}; the answer wakes you, then run the same command again.`, + }; +} diff --git a/packages/convex/convex/secrets.ts b/packages/convex/convex/secrets.ts index f93ba7780c..99384fa2f2 100644 --- a/packages/convex/convex/secrets.ts +++ b/packages/convex/convex/secrets.ts @@ -29,8 +29,9 @@ import { decryptRefreshToken, encryptRefreshToken } from "./googleOAuth"; import { connectionKey } from "./tokenConnectors"; import { nextShortId } from "./counters"; import { emitNotification } from "./notificationRouter"; -import { askCore, peopleFor, withdrawCore } from "./sessionDecisions"; -import { ASKS_TO_USE, approvalContext, approvalSecrets, bumpRedaction, joinNames, recordSecretEvent, redactionCounter, refreshApprovalDecision } from "./lib/secretApprovals"; +import { peopleFor, withdrawCore } from "./sessionDecisions"; +import { approvalHolds, askFirstGate } from "./lib/secretAskFirst"; +import { bumpRedaction, recordSecretEvent, redactionCounter, refreshApprovalDecision } from "./lib/secretApprovals"; import { consumePresence } from "./lib/presence"; import { displayName } from "./lib/displayNames"; import { findConversationByAnyRefWhere } from "./conversationSessionLookup"; @@ -46,8 +47,6 @@ import { loginSitesProblem, siteProblem, ambiguousSecretName, - APPROVE_FOR_SESSION, - DENY, envFor, envNameProblem, payloadFingerprint, @@ -58,14 +57,12 @@ import { signinExpiresAt, signinScopeProblem, validatePayload, - SECRET_APPROVAL_TTL_MS, SECRET_VERSION_TTL_MS, type LoginPayload, type SecretKind, type SecretMeta, type SecretNeedsApproval, type SecretPayload, - type SecretReadPurpose, type SecretVersionMeta, type SigninPayload, } from "@codecast/shared/contracts/secrets"; @@ -280,10 +277,6 @@ async function loadCiphertexts(ctx: any, refs: ValueRef[]): Promise<(string | nu // ── Ask first approvals ────────────────────────────────────────────────────── -/** An approval lets its session read while the session is active, for SECRET_APPROVAL_TTL_MS at most. */ -const approvalHolds = (a: Doc<"secret_approvals"> | null | undefined, conversation: any, now: number) => - a?.status === "approved" && now - a.at < SECRET_APPROVAL_TTL_MS && conversation?.status === "active"; - /** * Drop a secret's approvals. After a new value, the approved ones: a person * approved the value they knew. When Ask first is switched or the secret @@ -1188,80 +1181,6 @@ export const readTargets = internalQuery({ }, }); -/** - * Ask first: every gated secret of an agent's read needs an approval for - * that conversation. Without one, a decision is filed on the conversation - * (or the open one reused, its why rewritten when a newer one comes) and the - * read answers with it instead of values. - * Only the conversation's owner reads under its approval, so naming someone - * else's approved session lends nothing. - */ -async function askFirstGate( - ctx: any, - userId: Id<"users">, - rows: SecretRow[], - conversationId: Id<"conversations"> | undefined, - purpose: SecretReadPurpose, - why: string | undefined, -): Promise { - const gated = rows.filter((r) => r.ask_first); - if (!gated.length) return null; - const conversation: any = conversationId ? await ctx.db.get(conversationId) : null; - // An ended session's approval lends nothing: its id is visible to every other session of the user. - if (!conversation || !conversation.session_id || String(conversation.user_id) !== String(userId) || conversation.status !== "active") { - return { error: `${gated[0].name} is Ask first: a person approves each session's use, so read it from inside your own live agent session` }; - } - const now = Date.now(); - const approvals: { decision: string; secret: string }[] = []; - const fresh: { row: SecretRow; existing: Doc<"secret_approvals"> | null }[] = []; - for (const row of gated) { - const existing = await ctx.db - .query("secret_approvals") - .withIndex("by_secret_conversation", (q: any) => q.eq("secret_id", row._id).eq("conversation_id", conversation._id)) - .first(); - if (approvalHolds(existing, conversation, now)) continue; - const open = existing?.status === "pending" ? await ctx.db.get(existing.decision_id) : null; - if (open?.status === "pending") { - // A newer why rewrites the open decision in place; a repeat without one leaves it as asked. - const context_md = approvalContext(await approvalSecrets(ctx, open._id), purpose, why); - if (why?.trim() && open.context_md !== context_md) await ctx.db.patch(open._id, { context_md, updated_at: now }); - approvals.push({ decision: open.short_id, secret: row.name }); - continue; - } - fresh.push({ row, existing }); - } - // Every secret this read still needs goes on one decision: one Approve, and at most one Touch ID, opens them all. - if (fresh.length) { - const batch = fresh.map((f) => f.row); - const names = joinNames(batch.map((r) => r.name)); - const asked = await askCore(ctx, { userId: conversation.user_id }, { - session_id: conversation.session_id, - question: `${conversation.title || conversation.short_id || "A session"}${ASKS_TO_USE}${names}`, - options: [{ label: APPROVE_FOR_SESSION }, { label: DENY }], - context_md: approvalContext(batch, purpose, why), - category: "access", - blocking: true, - }); - if (asked?.error) return { error: `Could not ask for ${names}: ${asked.error}` }; - if (batch.some((r) => r.touch_id)) await ctx.db.patch(asked.id, { touch_id: true }); - for (const { row, existing } of fresh) { - const fields = { decision_id: asked.id, status: "pending" as const, approved_by: undefined, at: now }; - if (existing) await ctx.db.patch(existing._id, fields); - else await ctx.db.insert("secret_approvals", { secret_id: row._id, workspace: row.workspace, conversation_id: conversation._id, ...fields }); - await recordSecretEvent(ctx, row, "approval_requested", { actor: userId, conversation_id: conversation._id, purpose, decision_id: asked.id }); - approvals.push({ decision: asked.short_id, secret: row.name }); - } - } - if (!approvals.length) return null; - const ids = [...new Set(approvals.map((a) => a.decision))].join(", "); - const names = approvals.map((a) => a.secret).join(", "); - return { - needs_approval: approvals[0], - approvals, - message: `${names} ${approvals.length > 1 ? "are" : "is"} Ask first: a person approves this session in ${ids}. End your turn dormant naming ${ids}; the answer wakes you, then run the same command again.`, - }; -} - export const recordReads = internalMutation({ args: { user_id: v.id("users"), @@ -1295,14 +1214,45 @@ export const recordReads = internalMutation({ // An Ask first value reaching this user's agents the first time joins their daemon's feed (redactionRows); a reveal reached only their screen. if (kind !== "revealed" && row.ask_first && !(await reachedUser(ctx, row, args.user_id))) await bumpRedaction(ctx, row.workspace); await recordSecretEvent(ctx, row, kind, { actor: args.user_id, conversation_id: args.conversation_id, purpose: args.purpose }); - if (args.kind === "read") { - await ctx.db.patch(row._id, { last_used_at: now, last_used_by_conversation: args.conversation_id, use_count: (row.use_count ?? 0) + 1 }); - } + if (args.kind === "read") await ctx.scheduler.runAfter(USE_TALLY_DELAY_MS, internal.secrets.tallyUse, { id: row._id, through: now }); } return null; }, }); +/** + * A read leaves its use on the row later. Patching the row inside the read + * made every concurrent read of one secret conflict on it, and a burst (a + * fleet starting with the same key, 22 in one minute on 2026-12-02) failed + * the reads themselves after Convex's retries. The read's event is the + * record; `tallyUse` runs USE_TALLY_DELAY_MS later and folds the read events + * since the row's last_used_at into use_count, last_used_at and + * last_used_by_conversation. By then every read that started before the + * cutoff has committed, so nothing is counted twice or skipped, and the + * first tally of a burst counts it all: the later ones find nothing and + * write nothing. + */ +const USE_TALLY_DELAY_MS = 10_000; +const USE_TALLY_SETTLE_MS = 3_000; +const USE_KINDS = new Set(["read", "signed_in"]); + +export const tallyUse = internalMutation({ + args: { id: v.id("secrets"), through: v.number() }, + handler: async (ctx, args) => { + const row = await ctx.db.get(args.id); + if (!row) return 0; + const from = row.last_used_at ?? 0; + const through = Math.max(args.through, Date.now() - USE_TALLY_SETTLE_MS); + if (through <= from) return 0; + const events = await ctx.db.query("secret_events").withIndex("by_secret_at", (q) => q.eq("secret_id", args.id).gt("at", from).lte("at", through)).collect(); + const uses = events.filter((e) => USE_KINDS.has(e.kind)); + const last = uses.at(-1); + if (!last) return 0; + await ctx.db.patch(row._id, { last_used_at: last.at, last_used_by_conversation: last.conversation_id, use_count: (row.use_count ?? 0) + uses.length }); + return uses.length; + }, +}); + /** Decrypt rows whose read was already recorded; one that no longer decrypts refuses the whole read. */ async function openRows(ctx: any, rows: ({ name: string; workspace: string } & ValueRef)[]): Promise<{ payloads: SecretPayload[] } | { error: string }> { const encs = await loadCiphertexts(ctx, rows); diff --git a/packages/electron/installedApps/e2e/run.mjs b/packages/electron/installedApps/e2e/run.mjs index f6e41fb1a8..0f10851fa0 100644 --- a/packages/electron/installedApps/e2e/run.mjs +++ b/packages/electron/installedApps/e2e/run.mjs @@ -88,7 +88,7 @@ const SLUG = PROD ? flag("--slug") : "e2eneedsyou"; // Stand-in pages: one declaring no icon, one whose team turned installs off. const NOICON = "e2enoicon"; const BLOCKED = "e2eblocked"; -const KEY = PROD ? flag("--k") : "e2ekey"; +const KEY = PROD ? flag("--k") || process.env.CODECAST_E2E_K || null : "e2ekey"; if (PROD && !SLUG) { console.error("--prod needs --slug of a published page (and --k for a gated one)"); process.exit(2); @@ -132,6 +132,9 @@ function assert(cond, message) { if (!cond) throw new Error(message); } const eq = (a, b, what) => assert(JSON.stringify(a) === JSON.stringify(b), `${what}: expected ${JSON.stringify(b)}, got ${JSON.stringify(a)}`); +/** A URL with its gate keys (k, e, m, i) masked, for anything printed or saved. */ +const redactKeys = (u) => String(u).replace(/([?&#](?:k|e|m|i)=)[^&#\s]+/g, "$1…"); + const shot = (name, png) => { const file = path.join(SHOTS, name); fs.writeFileSync(file, png); @@ -469,7 +472,7 @@ async function runHost(kind, standin) { eq(plist.CFBundleIdentifier, bundleId, "bundle id"); eq(plist.CodecastAppSlug, SLUG, "slug"); eq(plist.CodecastHostBundleId, "com.github.Electron", "host bundle id"); - assert(plist.CodecastPageUrl === `${pageOrigin}/${SLUG}?host=app${gateQs}`, `page URL ${plist.CodecastPageUrl}`); + assert(plist.CodecastPageUrl === `${pageOrigin}/${SLUG}?host=app${gateQs}`, `page URL ${redactKeys(plist.CodecastPageUrl)}`); eq([plist.CodecastWindowWidth, plist.CodecastWindowHeight, plist.CodecastMinWidth, plist.CodecastMinHeight], [facts.app.window.width, facts.app.window.height, facts.app.window.minWidth, facts.app.window.minHeight], "window keys"); assert(fs.existsSync(path.join(record.bundlePath, "Contents/Resources/client.js")), "no client.js"); execFileSync("codesign", ["--verify", "--deep", "--strict", record.bundlePath], { stdio: "pipe" }); @@ -493,11 +496,32 @@ async function runHost(kind, standin) { const t = await target("the app window", (t) => isPageUrl(t.url, pageOrigin, "window") && (!KEY || new URL(t.url).searchParams.get("k") === KEY)); const partition = path.join(userData, "Partitions", `app-${SLUG}`); await until("the partition on disk", () => fs.existsSync(partition), 10_000); - return t.url.replace(pageOrigin, ""); + return redactKeys(t.url.replace(pageOrigin, "")); }); } if (PROD) { - skip("page checks", "--prod: no probe in the real page, no control over its data or versions"); + // The real page runs on its own data: it must load it, put its count on + // the menu bar (when the manifest asks for it), and draw a window worth + // looking at. The probe-driven checks need the stand-in. + if (asked.includes("menu-bar")) { + await check("the real page loads its data and puts its count on the menu bar", async () => { + if (kind === "mac") { + await until("a menu bar title from the page", () => /\[appshim\] tray title "\d+"/.test(logText()), 90_000); + return logText().match(/\[appshim\] tray title "(\d+)"/g).pop(); + } + await until("a menu bar title from the page", async () => (await mainRec()).titles.some((t) => /^\d+$/.test(t)), 90_000); + return `title ${(await mainRec()).titles.filter((t) => /^\d+$/.test(t)).pop()}`; + }); + } + await check("screenshot of the app window", async () => { + // A page may reveal its rows over a second or two (Needs you staggers + // them); shoot what a person sees once it has settled. + await sleep(3000); + if (kind === "mac") return (await snapshot("mac-prod")).files.window; + const t = await target("the app window", (t) => isPageUrl(t.url, pageOrigin, "window")); + return shot("electron-prod-window.png", await (await open(t)).screenshot()); + }); + skip("probe checks", "--prod: no probe in the real page, no control over its versions"); } else { const win = await windowPage({ since: pageSince }); await check("cast.app.info() reports the app, its version and grants", async () => { @@ -832,7 +856,7 @@ async function runHost(kind, standin) { } await until("the app window to close", async () => !(await targets()).some((t) => t.url.startsWith(`${pageOrigin}/${SLUG}`)), 10_000); const rec = await mainRec(); - assert(rec.traysDestroyed >= 1, "the tray item was not destroyed"); + if (!PROD || asked.includes("menu-bar")) assert(rec.traysDestroyed >= 1, "the tray item was not destroyed"); if (!PROD) assert(!(await main.eval(`process.mainModule.require("electron").globalShortcut.isRegistered("CmdOrCtrl+Alt+Shift+F19")`)), "the shortcut is still registered"); if (!PROD) { // The page's origin, read back in the app's partition through a document with no sandbox. diff --git a/packages/electron/package.json b/packages/electron/package.json index d2b18089bf..d63faddb68 100644 --- a/packages/electron/package.json +++ b/packages/electron/package.json @@ -14,7 +14,7 @@ "prebuild:local": "npm run native", "start": "electron .", "dev": "CODECAST_URL=https://local.codecast.sh electron .", - "test": "node --test *.test.js installedApps/*.test.js appshim/*.test.js", + "test": "node -e \"require('electron')\" && node --test *.test.js installedApps/*.test.js appshim/*.test.js", "build": "NOTARIZE_KEYCHAIN_PROFILE=codecast electron-builder -m", "build:dir": "electron-builder -m --config.mac.target=dir", "build:local": "electron-builder -m --config.mac.target=dir --config.mac.identity=null", diff --git a/packages/mobile/app/decisions/[id].tsx b/packages/mobile/app/decisions/[id].tsx index 37da676feb..2ad5ac4731 100644 --- a/packages/mobile/app/decisions/[id].tsx +++ b/packages/mobile/app/decisions/[id].tsx @@ -115,6 +115,12 @@ export default function DecisionScreen() { {source.question} {settled} + {/* Settled or not, the conversation that asked is one tap away. */} + {row?.conversation_id ? ( + router.push(`/session/${row.conversation_id}`)} hitSlop={8}> + {row.session_title || 'Open the conversation'} › + + ) : null} {flow} {nextId ? : null} diff --git a/packages/shared/blame/index.ts b/packages/shared/blame/index.ts index 93927881be..db35774da7 100644 --- a/packages/shared/blame/index.ts +++ b/packages/shared/blame/index.ts @@ -208,6 +208,18 @@ export function extractSessionTrailer(message: string | null | undefined): strin return splitSessionTrailer(message).session; } +/** + * How many Codecast-Session trailers a commit message's last paragraph carries, + * whatever their values (short ids included). More than one marks a sweep: one + * session committed several sessions' work, so the commit alone does not say + * which of them wrote a given line. + */ +export function sessionTrailerCount(message: string | null | undefined): number { + if (!message) return 0; + const paragraphs = message.replace(/\r\n/g, "\n").trimEnd().split(/\n[ \t]*\n/); + return (paragraphs[paragraphs.length - 1] ?? "").split("\n").filter((line) => TRAILER_LINE.test(line.trim())).length; +} + /** * A commit message with the Codecast-Session trailer lines that * extractSessionTrailer reads taken out (a paragraph left empty goes with diff --git a/packages/shared/blame/sessionTrailer.test.ts b/packages/shared/blame/sessionTrailer.test.ts index 80365e8a32..a744f9b910 100644 --- a/packages/shared/blame/sessionTrailer.test.ts +++ b/packages/shared/blame/sessionTrailer.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { extractSessionTrailer, sessionTrailerValue, SESSION_TRAILER_KEY, splitSessionTrailer } from "./index"; +import { extractSessionTrailer, sessionTrailerCount, sessionTrailerValue, SESSION_TRAILER_KEY, splitSessionTrailer } from "./index"; const ID = "jx7bq5kz13a2eypp4a6vdqznas7zvrw2"; const trailer = `${SESSION_TRAILER_KEY}: ${sessionTrailerValue(ID)}`; @@ -84,3 +84,12 @@ describe("splitSessionTrailer", () => { } }); }); + +describe("sessionTrailerCount", () => { + test("counts every trailer in the last paragraph, short ids included; quoted ones don't count", () => { + expect(sessionTrailerCount(`fix: a\n\n${trailer}`)).toBe(1); + expect(sessionTrailerCount("feat: sweep\n\nCodecast-Session: jx70369\nCodecast-Session: jx70e0f\nCodecast-Session: jx70gmc")).toBe(3); + expect(sessionTrailerCount(`feat: about trailers\n\n${trailer}\n\nmore prose`)).toBe(0); + expect(sessionTrailerCount(undefined)).toBe(0); + }); +}); diff --git a/packages/shared/contracts/ciWorkflow.test.ts b/packages/shared/contracts/ciWorkflow.test.ts new file mode 100644 index 0000000000..fc49417ab1 --- /dev/null +++ b/packages/shared/contracts/ciWorkflow.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, test } from "bun:test"; +import { condition, dispatchInputs, evaluate, expandMatrix, ExprError, foldResults, globRegex, interpolate, jobStarts, planWorkflow, resolveValue, workflowTriggers, type ExprContext, type Workflow } from "./ciWorkflow"; + +const ctx: ExprContext = { + github: { event_name: "push", ref: "refs/heads/main", event: { before: "abc" } }, + matrix: { shard: 2, part: "e2e" }, + needs: { code_paths: { result: "success", outputs: { run_web: "true", run_cli: "false" } }, a: { result: "skipped" }, b: { result: "success" } }, + env: {}, +}; + +describe("expressions, as GitHub evaluates them", () => { + test.each([ + ["github.event_name == 'push'", true], + ["github.event_name == 'PUSH'", true], + ["github.event_name != 'pull_request' && matrix.shard == 2", true], + ["matrix.shard == '2'", true], + ["needs.code_paths.outputs.run_cli == 'true'", false], + ["needs.code_paths.outputs.missing == 'true'", false], + ["!(matrix.part == 'e2e')", false], + ["contains(github.ref, 'main')", true], + ["startsWith(github.ref, 'refs/heads/')", true], + ["contains(needs.*.result, 'skipped')", true], + ["format('{0}-{1}', matrix.part, matrix.shard) == 'e2e-2'", true], + ["github.event.pull_request.number || 'main'", "main"], + ["matrix['part']", "e2e"], + ])("%s", (expr, want) => expect(evaluate(expr, ctx)).toBe(want)); + + test("an `if:` without a status function needs success() too; always() and failure() read the job's state", () => { + expect(condition("matrix.shard == 2", ctx)).toBe(true); + expect(condition("matrix.shard == 2", { ...ctx, status: { failed: true, cancelled: false } })).toBe(false); + expect(condition("always() && matrix.shard == 2", { ...ctx, status: { failed: true, cancelled: false } })).toBe(true); + expect(condition("${{ !cancelled() }}", { ...ctx, status: { failed: true, cancelled: false } })).toBe(true); + expect(condition("failure()", { ...ctx, status: { failed: true, cancelled: false } })).toBe(true); + expect(condition(undefined, ctx)).toBe(true); + expect(condition(false, ctx)).toBe(false); + }); + + test("text is filled in; a whole expression keeps its type", () => { + expect(interpolate("shard ${{ matrix.shard }}/4 of ${{ github.event_name }}", ctx)).toBe("shard 2/4 of push"); + expect(resolveValue("${{ matrix.shard == 2 }}", ctx)).toBe(true); + expect(resolveValue("${{ fromJSON('[1,2]') }}", ctx)).toEqual([1, 2]); + }); + + test("what it cannot evaluate throws rather than guess", () => { + expect(() => evaluate("hashFiles('bun.lock')", ctx)).toThrow(ExprError); + expect(() => evaluate("nosuch.thing", ctx)).toThrow(ExprError); + }); +}); + +describe("matrices", () => { + test("a product of lists, less exclude, with include extending or adding rows", () => { + expect(expandMatrix({ os: ["a", "b"], n: [1, 2], exclude: [{ os: "b", n: 2 }], include: [{ os: "a", extra: "x" }, { os: "c", n: 9 }] })).toEqual([ + { os: "a", n: 1, extra: "x" }, + { os: "a", n: 2, extra: "x" }, + { os: "b", n: 1 }, + { os: "c", n: 9 }, + ]); + }); + test("include alone is one row per entry; none is one runner", () => { + expect(expandMatrix({ include: [{ k: "a" }, { k: "b" }] })).toEqual([{ k: "a" }, { k: "b" }]); + expect(expandMatrix(undefined)).toEqual([{}]); + }); + test("a key, include or the whole matrix may be an expression, read against the run's context", () => { + const pick = (push: string, pr: string) => `\${{ fromJSON(github.event_name == 'push' && '${push}' || '${pr}') }}`; + const pr: ExprContext = { github: { event_name: "pull_request" } }; + const push: ExprContext = { github: { event_name: "push" } }; + expect(expandMatrix({ n: pick("[1]", "[1,2]") }, pr)).toEqual([{ n: 1 }, { n: 2 }]); + expect(expandMatrix({ n: pick("[1]", "[1,2]") }, push)).toEqual([{ n: 1 }]); + expect(expandMatrix({ include: pick('[{"k":"all"}]', '[{"k":"a"},{"k":"b"}]') }, pr)).toEqual([{ k: "a" }, { k: "b" }]); + expect(expandMatrix("${{ fromJSON('{\"n\":[1,2]}') }}", pr)).toEqual([{ n: 1 }, { n: 2 }]); + }); + test("a value it cannot read as a list fails as an expression error, naming the key", () => { + // A job output the context does not hold, and one that is not JSON, are both unreadable here. + expect(() => expandMatrix({ n: "${{ fromJSON(needs.a.outputs.list) }}" }, {})).toThrow(ExprError); + expect(() => expandMatrix({ n: "${{ fromJSON(needs.a.outputs.list) }}" }, { needs: { a: { result: "success", outputs: {} } } })).toThrow(ExprError); + expect(() => expandMatrix({ n: "1/4" })).toThrow("matrix n must be a list"); + }); +}); + +describe("on: filters", () => { + const wf: Workflow = { on: { push: { branches: ["main"], paths: ["app/**", ".github/workflows/**", "!app/docs/**"] }, pull_request: { branches: ["main"] } }, jobs: {} }; + test("branches and paths, with negation, as GitHub reads them", () => { + expect(workflowTriggers(wf, "push", { branch: "main", changed: ["app/backend/x.ts"] }).runs).toBe(true); + expect(workflowTriggers(wf, "push", { branch: "main", changed: ["README.md"] }).runs).toBe(false); + expect(workflowTriggers(wf, "push", { branch: "main", changed: ["app/docs/a.md"] }).runs).toBe(false); + expect(workflowTriggers(wf, "push", { branch: "dev", changed: ["app/x"] }).runs).toBe(false); + expect(workflowTriggers(wf, "push", { branch: "main", changed: null }).runs).toBe(true); + expect(workflowTriggers(wf, "pull_request", { branch: "main", changed: ["README.md"] }).runs).toBe(true); + }); + test("globs", () => { + expect(globRegex("a/**/b.ts").test("a/b.ts")).toBe(true); + expect(globRegex("a/**/b.ts").test("a/x/y/b.ts")).toBe(true); + expect(globRegex("a/*.ts").test("a/x/b.ts")).toBe(false); + }); +}); + +describe("the job graph", () => { + const wf: Workflow = { + jobs: { + gate: { "runs-on": "ubuntu-latest", outputs: { go: "${{ steps.s.outputs.go }}" } }, + work: { needs: "gate", if: "needs.gate.outputs.go == 'true'", "runs-on": "ubuntu-latest", strategy: { matrix: { shard: [1, 2] } }, name: "work (${{ matrix.shard }}/2)" }, + after: { needs: ["work"], "runs-on": "ubuntu-latest" }, + mac: { needs: "gate", "runs-on": "macos-15", "continue-on-error": true }, + verify: { needs: ["gate", "work", "after"], if: "always()", "runs-on": "ubuntu-latest" }, + }, + }; + const facts = { event: "push" as const, repository: "o/r", sha: "s", branch: "main" }; + test("a skipped need skips what depends on it, unless its if: says always()", () => { + const plan = planWorkflow(wf, facts, (job) => (job === "gate" ? { outputs: { go: "false" } } : {})); + expect(plan.map((p) => [p.job, p.starts])).toEqual([["gate", true], ["work", false], ["after", false], ["mac", true], ["verify", true]]); + }); + test("matrix runners carry GitHub's names, their OS and whether they count", () => { + const plan = planWorkflow(wf, facts, (job) => (job === "gate" ? { outputs: { go: "true" } } : {})); + expect(plan.find((p) => p.job === "work")!.runs.map((r) => r.name)).toEqual(["work (1/2)", "work (2/2)"]); + expect(plan.find((p) => p.job === "mac")!.runs[0]).toMatchObject({ os: "darwin", counts: false }); + }); + test("a failed need fails success() for everything after it", () => { + const state = { gate: { result: "success" as const, outputs: { go: "true" } }, work: { result: "failure" as const, outputs: {} } }; + expect(jobStarts(wf, "after", state, {})).toBe(false); + expect(jobStarts(wf, "verify", { ...state, after: { result: "skipped", outputs: {} } }, {})).toBe(true); + expect(foldResults(["success", "failure"])).toBe("failure"); + expect(foldResults(["skipped", "skipped"])).toBe("skipped"); + }); +}); + +describe("dispatchInputs", () => { + const wf = { on: { workflow_dispatch: { inputs: { dry_run: { type: "boolean", default: false }, version: { type: "string", required: true }, lane: { type: "choice", options: ["a", "b"], default: "a" } } } }, jobs: {} } as any; + test("given values, defaults, and booleans as booleans", () => { + expect(dispatchInputs(wf, { version: "1.2.3" })).toEqual({ inputs: { dry_run: false, version: "1.2.3", lane: "a" } }); + expect(dispatchInputs(wf, { version: "1", dry_run: "true", lane: "b" })).toEqual({ inputs: { dry_run: true, version: "1", lane: "b" } }); + }); + test("refuses what GitHub refuses", () => { + expect(dispatchInputs(wf, {})).toEqual({ problem: "input version is required" }); + expect(dispatchInputs(wf, { version: "1", extra: "x" })).toEqual({ problem: "the workflow declares no input extra" }); + expect(dispatchInputs(wf, { version: "1", dry_run: "yes" })).toEqual({ problem: 'input dry_run is a boolean, not "yes"' }); + expect(dispatchInputs(wf, { version: "1", lane: "c" })).toEqual({ problem: "input lane must be one of a, b" }); + expect(dispatchInputs({ on: { push: {} }, jobs: {} } as any, {})).toEqual({ problem: "the workflow has no on.workflow_dispatch" }); + }); +}); diff --git a/packages/shared/contracts/ciWorkflow.ts b/packages/shared/contracts/ciWorkflow.ts new file mode 100644 index 0000000000..39265e63c9 --- /dev/null +++ b/packages/shared/contracts/ciWorkflow.ts @@ -0,0 +1,600 @@ +// A GitHub Actions workflow (a repo's .github/workflows/ci.yml) read as data: its `${{ }}` expressions, `if:` +// conditions, matrices, `on:` filters and job graph, the way GitHub evaluates them. Two readers share it: +// scripts/ci/local.ts (CI's checks on a laptop, standing in for a pull request) and `cast ci run` (codecast's own +// runner, which plans a commit's jobs for its push or pull_request event, or runs a workflow_dispatch workflow such as +// a CLI release with its inputs, on a CI host). Pure: the +// caller parses the YAML (Bun.YAML) and passes the object in. + +export type Workflow = { on?: unknown; env?: Record; jobs: Record; [k: string]: unknown }; +export type WorkflowStep = { + name?: string; + id?: string; + if?: unknown; + uses?: string; + run?: string; + with?: Record; + env?: Record; + shell?: string; + "working-directory"?: string; + "continue-on-error"?: unknown; + "timeout-minutes"?: unknown; +}; +export type WorkflowJob = { + name?: string; + needs?: string | string[]; + if?: unknown; + "runs-on"?: unknown; + "timeout-minutes"?: unknown; + "continue-on-error"?: unknown; + strategy?: { matrix?: unknown; "fail-fast"?: unknown; "max-parallel"?: unknown }; + outputs?: Record; + env?: Record; + services?: Record; + defaults?: { run?: { shell?: string; "working-directory"?: string } }; + steps?: WorkflowStep[]; + uses?: string; +}; + +export type Matrix = Record; +/** The contexts an expression reads: github, env, matrix, needs, steps, secrets, inputs, job, runner, vars. */ +export type ExprContext = Record & { + /** The job's status functions: success(), failure(), cancelled(). Absent means everything before succeeded. */ + status?: { failed: boolean; cancelled: boolean }; +}; + +/** An expression this reader cannot evaluate (hashFiles, an unknown function, a syntax it does not parse). */ +export class ExprError extends Error {} + +// ── expressions ───────────────────────────────────────────────────────────── + +type Tok = { t: "num" | "str" | "id" | "op" | "punc"; v: string }; + +function tokenize(src: string): Tok[] { + const out: Tok[] = []; + let i = 0; + while (i < src.length) { + const c = src[i]!; + if (/\s/.test(c)) { i++; continue; } + if (c === "'") { + let s = ""; + i++; + for (;;) { + if (i >= src.length) throw new ExprError(`unterminated string in: ${src}`); + if (src[i] === "'") { + if (src[i + 1] === "'") { s += "'"; i += 2; continue; } + i++; + break; + } + s += src[i++]; + } + out.push({ t: "str", v: s }); + continue; + } + const two = src.slice(i, i + 2); + if (["==", "!=", "<=", ">=", "&&", "||"].includes(two)) { out.push({ t: "op", v: two }); i += 2; continue; } + if ("<>!".includes(c)) { out.push({ t: "op", v: c }); i++; continue; } + if ("()[].,*".includes(c)) { out.push({ t: "punc", v: c }); i++; continue; } + const num = /^(0x[0-9a-fA-F]+|-?\d+(\.\d+)?([eE][+-]?\d+)?)/.exec(src.slice(i)); + if (num && (c === "-" || /\d/.test(c))) { out.push({ t: "num", v: num[0] }); i += num[0].length; continue; } + const id = /^[A-Za-z_][A-Za-z0-9_-]*/.exec(src.slice(i)); + if (id) { out.push({ t: "id", v: id[0] }); i += id[0].length; continue; } + throw new ExprError(`unexpected "${c}" in: ${src}`); + } + return out; +} + +type Node = + | { k: "lit"; v: unknown } + | { k: "ctx"; name: string } + | { k: "prop"; of: Node; key: Node | "*" } + | { k: "not"; of: Node } + | { k: "bin"; op: string; a: Node; b: Node } + | { k: "call"; fn: string; args: Node[] }; + +function parse(src: string): Node { + const toks = tokenize(src); + let p = 0; + const peek = () => toks[p]; + const take = (v?: string) => { + const t = toks[p]; + if (!t || (v !== undefined && t.v !== v)) throw new ExprError(`expected ${v ?? "a value"} in: ${src}`); + p++; + return t; + }; + const binary = (next: () => Node, ops: string[]) => (): Node => { + let a = next(); + while (peek()?.t === "op" && ops.includes(peek()!.v)) { + const op = take().v; + a = { k: "bin", op, a, b: next() }; + } + return a; + }; + const primary = (): Node => { + const t = take(); + let node: Node; + if (t.t === "num") node = { k: "lit", v: Number(t.v) }; + else if (t.t === "str") node = { k: "lit", v: t.v }; + else if (t.v === "(") { node = or(); take(")"); } + else if (t.t === "id") { + if (t.v === "true" || t.v === "false") node = { k: "lit", v: t.v === "true" }; + else if (t.v === "null") node = { k: "lit", v: null }; + else if (peek()?.v === "(") { + take("("); + const args: Node[] = []; + if (peek()?.v !== ")") { args.push(or()); while (peek()?.v === ",") { take(","); args.push(or()); } } + take(")"); + node = { k: "call", fn: t.v.toLowerCase(), args }; + } else node = { k: "ctx", name: t.v }; + } else throw new ExprError(`unexpected "${t.v}" in: ${src}`); + for (;;) { + if (peek()?.v === ".") { + take("."); + const key = take(); + node = key.v === "*" ? { k: "prop", of: node, key: "*" } : { k: "prop", of: node, key: { k: "lit", v: key.v } }; + } else if (peek()?.v === "[") { + take("["); + if (peek()?.v === "*") { take("*"); take("]"); node = { k: "prop", of: node, key: "*" }; } + else { const key = or(); take("]"); node = { k: "prop", of: node, key }; } + } else return node; + } + }; + const unary = (): Node => (peek()?.v === "!" && peek()?.t === "op" ? (take(), { k: "not", of: unary() }) : primary()); + const cmp = binary(unary, ["<", ">", "<=", ">="]); + const eq = binary(cmp, ["==", "!="]); + const and = binary(eq, ["&&"]); + const or = binary(and, ["||"]); + const node = or(); + if (p !== toks.length) throw new ExprError(`unexpected "${toks[p]!.v}" in: ${src}`); + return node; +} + +/** GitHub's truthiness: false, 0, -0, "", null and NaN are falsy; everything else (objects, arrays) is truthy. */ +export const truthy = (v: unknown) => !(v === false || v === 0 || v === "" || v === null || v === undefined || Number.isNaN(v)); + +function toNumber(v: unknown): number { + if (v === null || v === undefined) return 0; + if (typeof v === "boolean") return v ? 1 : 0; + if (typeof v === "number") return v; + if (typeof v === "string") return v.trim() === "" ? 0 : Number(v); + return NaN; +} + +/** GitHub's loose comparison: strings case-insensitively, mixed types as numbers, objects by identity. */ +function looseEq(a: unknown, b: unknown): boolean { + if (a === undefined) a = null; + if (b === undefined) b = null; + if (typeof a === "string" && typeof b === "string") return a.toLowerCase() === b.toLowerCase(); + if (typeof a === typeof b && (typeof a !== "object" || a === null)) return a === b; + if ((typeof a === "object" && a !== null) || (typeof b === "object" && b !== null)) return a === b; + return toNumber(a) === toNumber(b); +} + +/** A value as GitHub turns it into a string inside `${{ }}` text. */ +export function exprString(v: unknown): string { + if (v === null || v === undefined) return ""; + if (typeof v === "boolean") return v ? "true" : "false"; + if (typeof v === "number") return String(v); + if (typeof v === "string") return v; + return JSON.stringify(v, null, 2); +} + +const STATUS_FNS = new Set(["success", "failure", "always", "cancelled"]); + +function evalNode(n: Node, ctx: ExprContext): unknown { + switch (n.k) { + case "lit": + return n.v; + case "ctx": { + if (!(n.name in ctx)) throw new ExprError(`no context named ${n.name}`); + return ctx[n.name]; + } + case "prop": { + const of = evalNode(n.of, ctx); + if (n.key === "*") return Array.isArray(of) ? of : of && typeof of === "object" ? Object.values(of) : []; + const key = evalNode(n.key, ctx); + if (Array.isArray(of) && of.length && n.of.k === "prop" && n.of.key === "*") return of.map((x) => (x && typeof x === "object" ? (x as any)[String(key)] : undefined)); + if (of === null || typeof of !== "object") return null; + // Context properties are case-insensitive on GitHub. + const obj = of as Record; + const k = String(key); + if (k in obj) return obj[k] ?? null; + const hit = Object.keys(obj).find((x) => x.toLowerCase() === k.toLowerCase()); + return hit === undefined ? null : (obj[hit] ?? null); + } + case "not": + return !truthy(evalNode(n.of, ctx)); + case "bin": { + if (n.op === "&&") { const a = evalNode(n.a, ctx); return truthy(a) ? evalNode(n.b, ctx) : a; } + if (n.op === "||") { const a = evalNode(n.a, ctx); return truthy(a) ? a : evalNode(n.b, ctx); } + const a = evalNode(n.a, ctx); + const b = evalNode(n.b, ctx); + if (n.op === "==") return looseEq(a, b); + if (n.op === "!=") return !looseEq(a, b); + const [x, y] = typeof a === "string" && typeof b === "string" ? [a.toLowerCase(), b.toLowerCase()] : [toNumber(a), toNumber(b)]; + return n.op === "<" ? x < y : n.op === ">" ? x > y : n.op === "<=" ? x <= y : x >= y; + } + case "call": { + const args = () => n.args.map((a) => evalNode(a, ctx)); + const st = ctx.status ?? { failed: false, cancelled: false }; + switch (n.fn) { + case "success": return !st.failed && !st.cancelled; + case "failure": return st.failed; + case "always": return true; + case "cancelled": return st.cancelled; + case "contains": { + const [hay, needle] = args(); + if (Array.isArray(hay)) return hay.some((x) => looseEq(x, needle)); + return exprString(hay).toLowerCase().includes(exprString(needle).toLowerCase()); + } + case "startswith": { const [s, p] = args(); return exprString(s).toLowerCase().startsWith(exprString(p).toLowerCase()); } + case "endswith": { const [s, p] = args(); return exprString(s).toLowerCase().endsWith(exprString(p).toLowerCase()); } + case "format": { + const [fmt, ...rest] = args(); + return exprString(fmt).replace(/\{\{|\}\}|\{(\d+)\}/g, (m, i) => (m === "{{" ? "{" : m === "}}" ? "}" : exprString(rest[Number(i)]))); + } + case "join": { const [arr, sep] = args(); return Array.isArray(arr) ? arr.map(exprString).join(sep === undefined ? "," : exprString(sep)) : exprString(arr); } + case "tojson": return JSON.stringify(args()[0] ?? null, null, 2); + case "fromjson": { + const text = exprString(args()[0]); + try { return JSON.parse(text); } catch { throw new ExprError(`fromJSON of text that is not JSON: ${JSON.stringify(text)}`); } + } + default: + throw new ExprError(`${n.fn}() is not something this reader evaluates`); + } + } + } +} + +function usesStatusFn(n: Node): boolean { + if (n.k === "call") return STATUS_FNS.has(n.fn) || n.args.some(usesStatusFn); + if (n.k === "bin") return usesStatusFn(n.a) || usesStatusFn(n.b); + if (n.k === "not") return usesStatusFn(n.of); + if (n.k === "prop") return usesStatusFn(n.of) || (n.key !== "*" && usesStatusFn(n.key)); + return false; +} + +const stripBraces = (s: string) => s.trim().replace(/^\$\{\{\s*([\s\S]*?)\s*\}\}$/, "$1"); + +/** One expression's value (`${{ }}` around it optional). */ +export function evaluate(expr: string, ctx: ExprContext): unknown { + return evalNode(parse(stripBraces(expr)), ctx); +} + +/** + * Whether an `if:` holds. As on GitHub, a condition without a status function means `success() && ()`, and an + * absent one means `success()`. A bare boolean (YAML `if: false`) is itself. + */ +export function condition(cond: unknown, ctx: ExprContext): boolean { + if (cond === undefined || cond === null || cond === "") return evaluate("success()", ctx) as boolean; + if (typeof cond === "boolean" || typeof cond === "number") return truthy(cond); + const node = parse(stripBraces(String(cond))); + if (!usesStatusFn(node)) return (evaluate("success()", ctx) as boolean) && truthy(evalNode(node, ctx)); + return truthy(evalNode(node, ctx)); +} + +/** Text with every `${{ }}` replaced by its value, as GitHub fills a `run:`, an env value or a name. */ +export function interpolate(text: string, ctx: ExprContext): string { + return text.replace(/\$\{\{([\s\S]*?)\}\}/g, (_m, inner: string) => exprString(evaluate(inner, ctx))); +} + +/** A value that may hold expressions: a string is interpolated, and a whole `${{ x }}` keeps x's type. */ +export function resolveValue(v: unknown, ctx: ExprContext): unknown { + if (typeof v !== "string") return v; + const whole = /^\s*\$\{\{([\s\S]*?)\}\}\s*$/.exec(v); + if (whole && !whole[1]!.includes("}}")) return evaluate(whole[1]!, ctx); + return interpolate(v, ctx); +} + +// ── matrices ──────────────────────────────────────────────────────────────── + +const subset = (row: Matrix, part: Matrix) => Object.entries(part).every(([k, v]) => looseEq(row[k], v) || JSON.stringify(row[k]) === JSON.stringify(v)); + +/** + * A job's matrix entries, one per runner GitHub starts for it ([{}] without a matrix): the product of its lists, less + * `exclude`, then `include` rows merged into the entries they extend (or added on their own), in GitHub's order. + */ +export function expandMatrix(matrix: unknown, ctx: ExprContext = {}): Matrix[] { + if (matrix === undefined || matrix === null) return [{}]; + const whole = resolveValue(matrix, ctx) as Record; + if (!whole || typeof whole !== "object") throw new ExprError(`a matrix must be a mapping, got ${JSON.stringify(whole)}`); + // Any one key, include or exclude may itself be an expression (a list picked by event, say). + const m: Record = Object.fromEntries(Object.entries(whole).map(([k, v]) => [k, resolveValue(v, ctx)])); + const include = (m.include as Matrix[] | undefined) ?? []; + const exclude = (m.exclude as Matrix[] | undefined) ?? []; + const keys = Object.keys(m).filter((k) => k !== "include" && k !== "exclude"); + for (const k of [...keys, "include", "exclude"]) { + if (m[k] !== undefined && !Array.isArray(m[k])) throw new ExprError(`matrix ${k} must be a list, got ${JSON.stringify(m[k])}`); + } + let rows: Matrix[] = keys.length + ? keys.reduce((acc, k) => acc.flatMap((row) => (m[k] as unknown[]).map((v) => ({ ...row, [k]: v }))), [{}]) + : []; + rows = rows.filter((row) => !exclude.some((ex) => subset(row, ex))); + const base = rows.map((r) => ({ ...r })); + for (const inc of include) { + let merged = false; + const original = Object.fromEntries(Object.entries(inc).filter(([k]) => keys.includes(k))); + rows.slice(0, base.length).forEach((row, i) => { + // An include row extends each original entry it does not overwrite; added rows are never extended. + if (keys.length && subset(base[i]!, original)) { + const overwrites = Object.entries(inc).some(([k, v]) => keys.includes(k) && !looseEq(base[i]![k], v)); + if (!overwrites) { Object.assign(row, inc); merged = true; } + } + }); + if (!merged) rows.push({ ...inc }); + } + return rows.length ? rows : [{}]; +} + +// ── the workflow's trigger ────────────────────────────────────────────────── + +/** A GitHub filter glob (`**`, `*`, `?`, `[...]`) as a regex over a path or a branch name. */ +export function globRegex(glob: string): RegExp { + let re = ""; + for (let i = 0; i < glob.length; i++) { + const c = glob[i]!; + if (c === "*") { + if (glob[i + 1] === "*") { i++; if (glob[i + 1] === "/") { i++; re += "(?:.*/)?"; } else re += ".*"; } + else re += "[^/]*"; + } else if (c === "?") re += "[^/]"; + else if (c === "[") { const end = glob.indexOf("]", i); re += glob.slice(i, end + 1); i = end; } + else re += c.replace(/[.+^${}()|\\]/g, "\\$&"); + } + return new RegExp(`^${re}$`); +} + +/** Whether names pass an include list with `!` negations (GitHub's order: the last matching pattern decides). */ +function filterPasses(patterns: string[], name: string): boolean { + let pass = false; + for (const p of patterns) { + if (p.startsWith("!")) { if (globRegex(p.slice(1)).test(name)) pass = false; } + else if (globRegex(p).test(name)) pass = true; + } + return pass; +} + +export type WorkflowEvent = "push" | "pull_request" | "workflow_dispatch"; + +/** + * A workflow_dispatch run's `inputs` context, as GitHub builds it from on.workflow_dispatch.inputs: each given value, + * else the input's default; a boolean input is a boolean, a choice must be one of its options, and a required input + * with no value or a name the workflow does not declare is refused (GitHub refuses the dispatch). + */ +export function dispatchInputs(workflow: Workflow, given: Record): { inputs: Record } | { problem: string } { + const f = eventFilter(workflow, "workflow_dispatch"); + if (!f) return { problem: "the workflow has no on.workflow_dispatch" }; + const declared = (f.inputs ?? {}) as Record; + const unknown = Object.keys(given).filter((k) => !(k in declared)); + if (unknown.length) return { problem: `the workflow declares no input ${unknown.join(", ")}` }; + const inputs: Record = {}; + for (const [name, d] of Object.entries(declared)) { + const raw = name in given ? given[name]! : d?.default === undefined ? undefined : String(d.default); + if (raw === undefined && d?.required === true) return { problem: `input ${name} is required` }; + const value = raw ?? ""; + if (d?.type === "boolean") { + if (!["true", "false", ""].includes(value)) return { problem: `input ${name} is a boolean, not "${value}"` }; + inputs[name] = value === "true"; + } else { + if (d?.type === "choice" && Array.isArray(d.options) && value !== "" && !d.options.map(String).includes(value)) return { problem: `input ${name} must be one of ${d.options.join(", ")}` }; + inputs[name] = value; + } + } + return { inputs }; +} + +/** The `on:` block for one event: null when the workflow does not run on it. */ +export function eventFilter(workflow: Workflow, event: WorkflowEvent): Record | null { + const on = workflow.on ?? (workflow as any)[true as any]; + if (typeof on === "string") return on === event ? {} : null; + if (Array.isArray(on)) return on.includes(event) ? {} : null; + if (on && typeof on === "object" && event in on) return ((on as any)[event] ?? {}) as Record; + return null; +} + +/** + * Whether the workflow runs for this event: `branches` (the pushed branch, or a pull request's base) and `paths` / + * `paths-ignore` over the changed files. `changed` null means unknown (a first push): GitHub runs the workflow. + */ +export function workflowTriggers(workflow: Workflow, event: WorkflowEvent, o: { branch: string; changed: string[] | null }): { runs: boolean; why: string } { + const f = eventFilter(workflow, event); + if (!f) return { runs: false, why: `the workflow has no on.${event}` }; + const list = (k: string) => (Array.isArray(f[k]) ? (f[k] as unknown[]).map(String) : null); + const branches = list("branches"); + if (branches && !filterPasses(branches, o.branch)) return { runs: false, why: `${o.branch} is not in on.${event}.branches` }; + const ignoreBranches = list("branches-ignore"); + if (ignoreBranches && ignoreBranches.some((p) => globRegex(p).test(o.branch))) return { runs: false, why: `${o.branch} is in on.${event}.branches-ignore` }; + if (o.changed) { + const paths = list("paths"); + if (paths && !o.changed.some((file) => filterPasses(paths, file))) return { runs: false, why: `no changed file matches on.${event}.paths` }; + const ignore = list("paths-ignore"); + if (ignore && o.changed.every((file) => ignore.some((p) => globRegex(p).test(file)))) return { runs: false, why: `every changed file matches on.${event}.paths-ignore` }; + } + return { runs: true, why: "" }; +} + +// ── jobs ──────────────────────────────────────────────────────────────────── + +export const needsOf = (job: WorkflowJob): string[] => (job.needs === undefined ? [] : Array.isArray(job.needs) ? job.needs.map(String) : [String(job.needs)]); + +/** The jobs in an order where each comes after everything it needs; a cycle or an unknown need throws. */ +export function jobOrder(workflow: Workflow): string[] { + const out: string[] = []; + const state = new Map(); + const visit = (id: string, from?: string) => { + if (!workflow.jobs[id]) throw new ExprError(`${from ?? "?"} needs ${id}, which ci.yml does not define`); + const s = state.get(id); + if (s === "done") return; + if (s === "visiting") throw new ExprError(`ci.yml's needs form a cycle through ${id}`); + state.set(id, "visiting"); + for (const n of needsOf(workflow.jobs[id]!)) visit(n, id); + state.set(id, "done"); + out.push(id); + }; + for (const id of Object.keys(workflow.jobs)) visit(id); + return out; +} + +export type JobOs = "linux" | "darwin" | "windows"; +const RUNNER_OS: Array<[RegExp, JobOs]> = [[/^(ubuntu|linux)/i, "linux"], [/^macos/i, "darwin"], [/^windows/i, "windows"]]; + +/** The OS family a job's `runs-on` names, or null for a label this reader does not know (self-hosted, a group). */ +export function runnerOs(runsOn: unknown): JobOs | null { + const labels = Array.isArray(runsOn) ? runsOn.map(String) : [String(runsOn ?? "")]; + for (const l of labels) for (const [re, os] of RUNNER_OS) if (re.test(l)) return os; + return null; +} + +/** GitHub's name for one matrix runner of a job: its `name:` filled in, else ` ()`. */ +export function jobDisplayName(id: string, job: WorkflowJob, matrix: Matrix, ctx: ExprContext): string { + if (job.name !== undefined) return interpolate(String(job.name), { ...ctx, matrix }); + const vals = Object.values(matrix); + if (!vals.length || !job.strategy?.matrix) return id; + const flat = (v: unknown): string => (v && typeof v === "object" ? Object.values(v).map(flat).join(", ") : exprString(v)); + return `${id} (${vals.map(flat).join(", ")})`; +} + +/** What one job's runs ended as, for `needs.`: GitHub folds a matrix into one result. */ +export type JobResult = "success" | "failure" | "cancelled" | "skipped"; +export type NeedsState = Record }>; + +/** A matrix job's result from its runners': any failure fails it, all skipped skips it. */ +export function foldResults(results: JobResult[]): JobResult { + if (results.some((r) => r === "failure")) return "failure"; + if (results.some((r) => r === "cancelled")) return "cancelled"; + if (results.length && results.every((r) => r === "skipped")) return "skipped"; + return "success"; +} + +/** The `needs` context a job sees: only its direct needs, as GitHub gives it. */ +export function needsContext(job: WorkflowJob, state: NeedsState): Record { + return Object.fromEntries(needsOf(job).map((n) => [n, state[n] ?? { result: "skipped", outputs: {} }])); +} + +/** + * Whether a job starts, given what its needs ended as. As on GitHub, success() at job level means every job it needs, + * directly or through others, succeeded; so a job whose need was skipped is skipped unless its `if:` asks otherwise. + */ +export function jobStarts(workflow: Workflow, id: string, state: NeedsState, ctx: ExprContext): boolean { + const ancestors = new Set(); + const walk = (j: string) => { for (const n of needsOf(workflow.jobs[j]!)) if (!ancestors.has(n)) { ancestors.add(n); walk(n); } }; + walk(id); + const results = [...ancestors].map((n) => state[n]?.result ?? "skipped"); + const status = { failed: results.some((r) => r === "failure"), cancelled: results.some((r) => r === "cancelled") }; + // A skipped ancestor fails success() without being a failure(). + const skipped = results.some((r) => r === "skipped"); + const job = workflow.jobs[id]!; + const c: ExprContext = { ...ctx, needs: needsContext(job, state), status }; + if (job.if === undefined || job.if === null || job.if === "") return !status.failed && !status.cancelled && !skipped; + if (typeof job.if === "boolean") return job.if && !status.failed && !skipped; + const node = parse(stripBraces(String(job.if))); + if (!usesStatusFn(node)) return !status.failed && !status.cancelled && !skipped && truthy(evalNode(node, c)); + return truthy(evalNode(node, { ...c, status: { failed: status.failed, cancelled: status.cancelled } })); +} + +/** The contexts GitHub gives every expression of a run, before job state: github, env, vars, inputs, runner. */ +export type RunFacts = { + event: WorkflowEvent; + repository: string; + sha: string; + /** The pushed branch, or a pull request's base branch. */ + branch: string; + /** A push's previous head, when there is one. */ + before?: string; + /** A pull request's base and head commits. */ + pullRequest?: { baseSha: string; headSha: string; baseRef: string; headRef: string; number?: number }; + runId?: string; + runAttempt?: number; + os?: JobOs; + /** Repository variables (`vars.X`); GitHub reads an unset one as "". */ + vars?: Record; + /** A workflow_dispatch run's inputs (dispatchInputs). */ + inputs?: Record; +}; + +export function githubContext(f: RunFacts): Record { + const ref = f.event === "pull_request" ? `refs/pull/${f.pullRequest?.number ?? 0}/merge` : `refs/heads/${f.branch}`; + const event = + f.event === "pull_request" + ? { pull_request: { number: f.pullRequest?.number ?? null, base: { sha: f.pullRequest?.baseSha, ref: f.pullRequest?.baseRef ?? f.branch }, head: { sha: f.pullRequest?.headSha ?? f.sha, ref: f.pullRequest?.headRef ?? "" }, title: "", body: "" } } + : f.event === "workflow_dispatch" + ? { inputs: f.inputs ?? {}, ref } + : { before: f.before ?? "0000000000000000000000000000000000000000", after: f.sha, ref }; + return { + event_name: f.event, + event, + repository: f.repository, + repository_owner: f.repository.split("/")[0], + sha: f.sha, + ref, + ref_name: f.event === "pull_request" ? `${f.pullRequest?.number ?? 0}/merge` : f.branch, + head_ref: f.event === "pull_request" ? (f.pullRequest?.headRef ?? "") : "", + base_ref: f.event === "pull_request" ? (f.pullRequest?.baseRef ?? f.branch) : "", + run_id: f.runId ?? "", + run_number: "1", + run_attempt: String(f.runAttempt ?? 1), + workflow: "", + actor: "codecast-ci", + server_url: "https://github.com", + }; +} + +/** The contexts a job-level expression sees before any of its steps run. */ +export function baseContext(workflow: Workflow, f: RunFacts, extra: Partial = {}): ExprContext { + const os = f.os ?? "linux"; + return { + github: githubContext(f), + env: {}, + vars: { ...(f.vars ?? {}) }, + inputs: { ...(f.inputs ?? {}) }, + secrets: {}, + matrix: {}, + needs: {}, + steps: {}, + strategy: {}, + job: {}, + runner: { os: os === "darwin" ? "macOS" : os === "windows" ? "Windows" : "Linux", arch: "X64", temp: "", tool_cache: "" }, + ...extra, + }; +} + +/** One runner of a job as a static plan sees it: which job, which matrix entry, its GitHub name and its OS. */ +export type PlannedRun = { job: string; matrix: Matrix; name: string; os: JobOs | null; counts: boolean }; +export type JobPlan = { job: string; starts: boolean; runs: PlannedRun[]; why?: string }; + +/** + * Every job's runners for a run, in dependency order, with what each job's needs end as given by `resolve`: the + * outputs a job leaves (code_paths' flags, computed by running it or by the caller standing in for it) and its result. + * A static plan takes every started job as a success unless `resolve` says otherwise. `continue-on-error` that is + * true marks a runner as not counting (its failure does not fail the run), as on GitHub. + */ +export function planWorkflow( + workflow: Workflow, + facts: RunFacts, + resolve: (job: string, runs: PlannedRun[]) => { result?: JobResult; outputs?: Record } = () => ({}), +): JobPlan[] { + const state: NeedsState = {}; + const ctx = baseContext(workflow, facts); + const plans: JobPlan[] = []; + for (const id of jobOrder(workflow)) { + const job = workflow.jobs[id]!; + if (!jobStarts(workflow, id, state, ctx)) { + state[id] = { result: "skipped", outputs: {} }; + plans.push({ job: id, starts: false, runs: [], why: job.if !== undefined ? `if: ${String(job.if)}` : "a job it needs did not succeed" }); + continue; + } + const jctx: ExprContext = { ...ctx, needs: needsContext(job, state) }; + const runs = expandMatrix(job.strategy?.matrix, jctx).map((matrix) => { + const mctx = { ...jctx, matrix }; + return { + job: id, + matrix, + name: jobDisplayName(id, job, matrix, mctx), + os: runnerOs(resolveValue(job["runs-on"], mctx)), + counts: !truthy(resolveValue(job["continue-on-error"] ?? false, mctx)), + }; + }); + const r = resolve(id, runs); + state[id] = { result: r.result ?? "success", outputs: r.outputs ?? {} }; + plans.push({ job: id, starts: true, runs }); + } + return plans; +} diff --git a/packages/shared/contracts/codeProtocol.ts b/packages/shared/contracts/codeProtocol.ts index f60311173b..466fb117c8 100644 --- a/packages/shared/contracts/codeProtocol.ts +++ b/packages/shared/contracts/codeProtocol.ts @@ -114,6 +114,11 @@ export interface CodeBlameHunk { /** The codecast session that wrote these lines, from the Codecast-Session * trailer or, for uncommitted lines, a content match against session edits. */ session?: CodeBlameSession; + /** Set when the commit is a sweep naming this many sessions in its + * Codecast-Session trailers and no single one of them could be matched to + * these lines; `session` is then absent rather than the session that ran + * the commit. */ + sweep_sessions?: number; } export interface CodeBlameResponse { diff --git a/packages/shared/contracts/shortcutCatalog.ts b/packages/shared/contracts/shortcutCatalog.ts index 6c9533689d..292a794eb1 100644 --- a/packages/shared/contracts/shortcutCatalog.ts +++ b/packages/shared/contracts/shortcutCatalog.ts @@ -325,6 +325,11 @@ export const SHORTCUTS: ShortcutDef[] = [ { key: 'ctrl+.', action: 'ui.zenToggle', skipInputCheck: true, description: 'Toggle zen mode' }, { key: 'ctrl+,', action: 'inbox.toggleFlatView', skipInputCheck: true, description: 'Cycle inbox view (grouped / time / label)' }, { key: '?', action: 'ui.toggleShortcutsHelp', description: 'Toggle shortcuts help' }, + // The same from inside a field or a focused code editor, where "?" is typed + // text (or vim's backward search). shift+slash arrives as '/' or '?' + // depending on browser/layout: both spellings. + { key: 'ctrl+shift+/', mac: 'meta+shift+/', action: 'ui.toggleShortcutsHelp', skipInputCheck: true, description: 'Toggle shortcuts help' }, + { key: 'ctrl+shift+?', mac: 'meta+shift+?', action: 'ui.toggleShortcutsHelp', skipInputCheck: true, description: 'Toggle shortcuts help' }, // meta+, is the OS settings convention on mac; ctrl+, is taken by the inbox // view cycle above, so non-mac gets the shifted variant. shift+comma arrives // as ',' or '<' depending on browser/layout — register both spellings. diff --git a/packages/shared/contracts/snippets.ts b/packages/shared/contracts/snippets.ts index 79027409eb..d08c071198 100644 --- a/packages/shared/contracts/snippets.ts +++ b/packages/shared/contracts/snippets.ts @@ -451,6 +451,8 @@ Multi-line prompts go through \`-\` and a heredoc, never \`"$(cat file)"\`, whic **Forks** branch this conversation just before the latest user message. With several directions you take the first in place and each other becomes a branch, so issue one \`cast fork\` with all of them and carry on with the first. When forking is your own idea, pass \`--tip\`. A branch receives its direction as its human's next message and reports to nobody: never message, monitor or coordinate branches. \`--cloud\` on \`spawn\` or \`fork\` runs the session on the person's cloud host, starting from this checkout as it stands, and \`cast migrate\` moves sessions between machines when the human asks. \`cast guide forks\` covers cloud hosts, folder sync, labels and migration. + +Keep scratch files out of project roots and checkouts: every folder under \`~/src\`, \`~/work\` or \`$HOME\` shows up in the person's app as a project. Output you can lose goes in \`$TMPDIR\`. A patch or backup you keep goes in \`$(git rev-parse --git-common-dir)/codecast/\` or on a branch, and your reply says where; a copy of the repo is a \`cast ws acquire\` worktree. ${FORKS_SNIPPET_END} `; @@ -839,13 +841,13 @@ export const VAULT_SNIPPET_END = ""; export const VAULT_SNIPPET = ` ## Vault -Credentials: \`cast guide vault\`. Never print one or put it in argv. +Credentials: \`cast guide vault\`. Never print one or put it in argv. One you lack comes from \`cast vault request\`, whose card a person fills; a new account's password is yours to generate. ${VAULT_SNIPPET_END} `; /** What `cast guide vault` prints after the body: the detail an install leaves out of CLAUDE.md. */ export const VAULT_REFERENCE = ` -Take credentials from the team's Vault; never ask a person to paste one. Hand a value to the command, never your context: \`cast vault run [names] -- \`, \`vault://\` in an \`--env-file\`, or stdin via \`< <(cast vault get )\`. Never put one in an argument (\`$(…)\` included: \`ps\` shows arguments to every local user), print it, or write it to a tracked file. Missing one: \`cast vault request --why "…"\`; a read that exits 3 names the decision it waits on. Either way, end the turn dormant naming it. +Take credentials from the team's Vault; never ask a person to paste one. Hand a value to the command, never your context: \`cast vault run [names] -- \`, \`vault://\` in an \`--env-file\`, or stdin via \`< <(cast vault get )\`. Never put one in an argument (\`$(…)\` included: \`ps\` shows arguments to every local user), print it, or write it to a tracked file. Missing one: \`cast vault request --why "…"\` (\`--kind login --site \` for an account) puts a form in this conversation that a person fills; never hand them a \`cast vault\` command. A new account's password is yours: generate it, store it with \`cast vault add\` from stdin, and ask only for what they alone hold (the email it uses, a birthdate) with \`cast decide --line\`. A read that exits 3 names the decision it waits on. Either way, end the turn dormant naming it. \`\`\`bash cast vault ls # what you can use, open requests first @@ -1044,6 +1046,7 @@ export const REFERENCES_SNIPPET = ` Every codecast object has a short ID. Written anywhere (a message, comment, doc or prompt), it renders as a live reference: title, state and a link. - Session \`jx7c6zk\`: \`cast feed\`, \`cast search\`, \`cast context\` +- Message \`jx7c6zk:412\` (a stretch \`jx7c6zk:412-418\`): the line numbers \`cast read\` prints; never a bare \`L412\` - Task \`ct-4102\`: \`cast task ls\`, \`cast task ready\` - Plan \`pl-88\`: \`cast plan ls\` - Trigger \`tr-42\`: \`cast trigger ls\` @@ -1546,12 +1549,12 @@ export const SNIPPET_CATALOG: SnippetDescriptor[] = [ category: "hands", desc: "Typecheck through one shared tsc watcher per project (cast check)", detail: - "Adds `cast check` so agents typecheck through one shared `tsc --watch` per tree and " + - "project instead of each running its own `tsc --noEmit`. The watcher keeps the program " + - "in memory and re-checks only what changed, so a check answers in seconds however many " + - "sessions ask, and a machine full of agents stops building the same program dozens of " + - "times over. A repo names its programs in a tracked .codecast/check.toml; without one, " + - "the tsconfig nearest the agent's directory is checked.", + "Agents typecheck with `cast check`, which shares one `tsc --watch` per tree and project " + + "instead of each agent running its own `tsc --noEmit`. The watcher keeps the program in " + + "memory and re-checks only what changed, so a check answers in seconds however many " + + "sessions ask, and a machine full of agents stops building the same program over and " + + "over. A repo names its programs in a tracked .codecast/check.toml; without one, the " + + "tsconfig nearest the agent's directory is checked. Worktrees come from `cast ws acquire`.", writesTo: "CLAUDE.md — a ## Typechecking section with the command", shipped: "2026-09-17", enabledKey: "check_enabled", @@ -1844,8 +1847,22 @@ export function guideTopics(): SnippetDescriptor[] { * 20 of 30 (./evals check decide). 37.1k: the line telling agents to record * each decision with the files it governs, which the review step's * \`cast decisions --touching\` check reads (sd-3566, raised without an eval). + * 37.8k: where a session's files go, the worktree sentence in Typechecking and + * the scratch-file rule in Forks & Sessions. On Opus 5.5, asked to park a + * patch or back up a repo before a risky rebase, 16 of 16 replies without the + * rule made a new folder in ~/src or $HOME, and 0 of 16 with it. + * 38.2k: three lines in Asking for a decision (say which product, show what is + * approved, an edit starts from the card as it stands). On the edit that left a + * launch-posts approval saying only that the date moved (decide 8f00d9f4), 0 of + * 8 cards without them kept the posts reachable and 8 of 8 with them did; the + * other 20 decide freezes went from mean 0.59 to 0.64 at 2 reps each. + * 38.6k: whatever an agent needs from a person comes as a card in the + * conversation, never a command to run (Asking for a decision, Vault). On the + * moment a Pinterest setup run needed a new account's email and password, 0 of + * 10 Opus 5.5 replies without it asked through a card and 7 of 10 with it did; + * replies offering to generate the password themselves went from 3 to 10. */ -export const GUIDANCE_MAX_CHARS = 37_100; +export const GUIDANCE_MAX_CHARS = 38_600; /** Each section body's budget, so detail stays in the reference `cast guide` serves. */ export const GUIDANCE_SECTION_MAX_CHARS = 4_000; diff --git a/packages/web/app/(marketing)/blog/agents-in-your-own-chrome/page.tsx b/packages/web/app/(marketing)/blog/agents-in-your-own-chrome/page.tsx deleted file mode 100644 index 0f6b8eb8cf..0000000000 --- a/packages/web/app/(marketing)/blog/agents-in-your-own-chrome/page.tsx +++ /dev/null @@ -1,234 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Screenshot, SOL, H2, P, Code } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Three genuine screenshots of the Codecast web app (a local dev build of this -// repo, signed in to the founder's account) in Chrome on 2026-11-11. The -// conversation pictured is session jx7ck79: a plain Claude Code session started -// in a terminal with the prompt shown, nothing else typed into it. Its findings -// (the stale service worker on codecast.sh, the HTTP 500 on the dev server) are -// quoted from its reply. The dev server failed because this post's route was -// registered in src/App.tsx a few minutes before its page file existed; the -// session found that on its own. A second run of the same prompt fifteen -// minutes later (jx7ca7t) found both pages rendering with no console errors. -// The browser card is the Agent features page on the same account. Product -// claims were checked against the "Let agents use your Chrome" guide, -// packages/cli/src/browser (handoff.ts, policy.ts, bridge/protocol.ts) and -// packages/browser-extension/background.js. Nothing was composited or retouched. - -const DIR = "/blog/agents-in-your-own-chrome"; - -export default function AgentsInYourOwnChromePost() { - const post = getPost("agents-in-your-own-chrome"); - useRouteMeta("/blog/agents-in-your-own-chrome"); - - return ( -
- - -
- - - - - Blog - - -
-

- Your coding agent can check the page in your own Chrome -

-

- {post?.dek} -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 5} min read -
-
- -

A check we ran today

-

- On November 11 we started Claude Code in a terminal and typed one request: check that - the pricing page renders on codecast.sh and on a local dev server, screenshot both, and - report any console errors. Nothing else was typed into the session. Codecast showed the - conversation as it ran, and this is the top of Claude's answer. -

- - - -

- The first load of codecast.sh/pricing showed “Pricing crashed”. Claude read - the console, found Failed to fetch dynamically imported module, and traced - it to the site's service worker: that Chrome had an older build cached, and the old - build asked for a file the server no longer has. Claude told the service worker to check - for an update, reloaded, and the page rendered with no console errors. It also pointed - out that anyone holding the same old build would see the crash until their service - worker updates. That one is a real bug on our site, found by the check. -

-

- The dev server was stuck on its loading screen, with nothing in the console but - Vite's connection messages. Claude asked the server for the app's main file - directly, got an HTTP 500, and read the compile error behind it. -

- - - -

- The missing file was this post. We had added its route a few minutes before writing the - page, and the check caught it. We ran the same request again fifteen minutes later: - both pages rendered, with no console errors. -

- -

Where the agent's tab lives

-

- The agent works in the Chrome you already have open, in the profile you paired, so your - logins come with it: staging, an admin panel, a dashboard behind single sign-on. Nothing - is copied out of Chrome. Each session gets one tab, opened in the background inside a - red tab group called Cast. It never takes focus, so you can keep typing - in your own tabs while it works. -

-

- A tab being driven wears a thin frame and a pointer follows the agent's clicks. If - you pin the Codecast icon in Chrome's toolbar, its badge reads RUN while you look at - a tab an agent is driving. Chrome also shows its own notice - that Codecast is debugging the browser. The frame and pointer are hidden while a - screenshot is taken, so they never end up in the picture. -

-

- A session can only touch tabs it opened. It cannot read, close or navigate your tabs or - another session's, and a tab you open yourself is moved out of the Cast group so - agents leave it alone. When a session finishes, its tab is closed. -

- -

What comes back to the conversation

-

- Each browser step shows up in the conversation as a row above the agent's reply, - with thumbnails of the screenshots it took. Click a thumbnail to see it full size.{" "} - open tab brings the agent's tab to the front in your Chrome,{" "} - watch live opens it in a pane beside the conversation, and if the tab - has been closed the row offers to reopen it. The count of images in the conversation - header opens all of them in one viewer. -

-

- When a page misbehaves, the agent reports the errors the page logged and the requests - that failed, as in the check above. You read the cause in the reply instead of opening - DevTools yourself. -

- -

What you do once

-

- Open Agent features from your account menu, pick the computer your - agents run on, and switch on Browser under Hands on the - machine. The card asks for two steps: Install extension adds - Codecast from the Chrome Web Store, and Pair connects it to that - computer. When both are done the card reads Chrome connected. -

- - - -

- Chrome has to run on the same computer as the agent, so you repeat this on each computer - you use. If an agent reaches for the browser before setup is done, the same steps appear - as a card under its step in the conversation, with a button to tell the agent to - continue once Chrome is connected. -

- -

Sign-ins and other steps that stay yours

-

- When a page asks for a login, a two-factor code or a payment, the agent hands that step - to you. A card appears inside the page in its tab saying what to do, with a{" "} - Continue button, and the pinned icon's badge reads WAIT on that tab. You sign - in, click Continue, and the agent carries on in the same tab. Only your own click counts; - the agent cannot press Continue for you. -

-

A few other limits are built in:

-
    -
  • - If the extension is missing or asleep, the agent waits and tells you what to fix. It - does not start a different browser instead. -
  • -
  • - Chrome does not let any extension drive its own pages, such as{" "} - chrome:// settings or the Chrome Web Store. The agent gives you the link - and the steps and carries on with the rest. -
  • -
  • - Agents read and click through pages freely. Submitting a form, sending a message, - buying something or changing account settings happens only when you asked for it. -
  • -
  • - A project can list the sites its agents may visit. Local addresses like a dev server - are reachable only when the list names them exactly. -
  • -
- -

What you need

-

- Desktop Chrome, the Codecast app on the computer where your agents run, and the - extension paired from Agent features. You don't need a team for any of it. Ask in plain words - (“open the settings page and show me a screenshot”), and agents that change - a web app also use it to check their own work. The{" "} - - browser guide - {" "} - has the full setup and a troubleshooting table. -

-

- For people who script: agents drive the tab with cast browser commands - (open, shot, console, handoff), and - you can run them yourself from a terminal. -

- -
- Codecast records every coding agent session you run, on any machine, and gives you one - place to see them, steer them and answer them, on your own or with your team. -
- -
- - - - - - -
- -

- All three screenshots are the Codecast web app in Chrome on 2026-11-11, signed in to - the founder's account, from a local build of the app. The first two are crops of - one conversation, a Claude Code session started in a terminal with the request shown; - its findings are quoted as it wrote them. The third is the Browser card on the Agent - features page. Each image is cropped to the conversation or the card, leaving out the - sidebars and other sessions. Nothing was composited or retouched. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/claude-code-cursor-codex/page.tsx b/packages/web/app/(marketing)/blog/claude-code-cursor-codex/page.tsx deleted file mode 100644 index c11aff4dfd..0000000000 --- a/packages/web/app/(marketing)/blog/claude-code-cursor-codex/page.tsx +++ /dev/null @@ -1,237 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Screenshot, SOL, H2, P, Code, CardShot, Prompt } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Seven genuine screenshots of the codecast web app on a local build of this -// checkout, in Chrome on 2026-10-30. The sessions in them were run for this post -// in a throwaway repository (/tmp/slugs): one Cursor CLI session and one Claude -// Code session, each started by hand in a terminal, one after the other. The -// Claude Code session was then switched to Codex from the app, and the two -// follow-ups pictured were sent from the app's composer. Every image is cropped -// to one part of the screen; the rest of the account (other sessions, people, -// projects) is outside every crop. Nothing was composited or retouched. - -const DIR = "/blog/claude-code-cursor-codex"; - -export default function AgentsTogetherPost() { - const post = getPost("claude-code-cursor-codex"); - useRouteMeta("/blog/claude-code-cursor-codex"); - - return ( -
- - -
- - - - - Blog - - -
-

- Claude Code, Cursor and Codex on the same project -

-

- Plenty of people run more than one coding agent on a project: Cursor for one piece, - Claude Code for another, Codex for a second look. Each keeps its own sessions in its - own place. Codecast puts them in one list, shows what each one said and did, and can - move a conversation from Claude Code to Codex so the second agent picks up with the - whole history. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 5} min read -
-
- -

One project, two agents

-

- For this post we made a small repository with one script in it, slugify.py, - which turns titles like Hello, World into URL slugs like{" "} - hello-world. Then we did what a lot of people do: gave one job to Cursor and the - next to Claude Code. First, in a terminal, Cursor's command line agent got this: -

- - Write unit tests for slugify() in slugify.py in a new file test_slugify.py using - unittest. Cover punctuation, repeated separators, leading and trailing spaces, and - accented letters. Run them and report what passes. - -

When it was done, Claude Code got the next job in another terminal:

- - Add a --max-length N option to slugify.py that cuts each slug to at most N characters - without ending on a hyphen or splitting a word when possible. Standard library only. - Add tests for it to the existing test_slugify.py and update the README. - -

- Neither was started from Codecast. Both showed up in the list on their own, because the - Codecast app on the laptop picks up sessions from Claude Code, Codex, Cursor and other - agents as they run. Each card carries the agent's mark, so you can tell them apart - at a glance, and clicking the project's chip at the top of the list narrows it to - that repository. We renamed both sessions in the app to keep the titles short: -

- - - -

What each one did

-

- Opening a session shows its conversation as it happened, whichever agent ran it. Here is - Cursor's, below the prompt. Its tool calls are folded into small rows ( - read 1 file, wrote 1 file) that open to show what it ran, and its - report comes through as written, table included: -

- - - -

- That last line matters later: the script throws accented letters away, so{" "} - café becomes caf. -

-

- Next to a Claude Code session is the code it changed. The panel lists each file with - the lines added and removed, and has tabs for the whole session, the branch and a - commit. Claude edited the README and added 32 lines of tests to the file Cursor had - written: -

- - - -

- For the Cursor session that panel stayed empty on our run. Its transcript names the - file it wrote, and the tests themselves were in the repository, but the line by line - diff is something we saw for Claude Code, not for Cursor. -

- -

Handing the conversation to Codex

-

- To fix the accents, we wanted a different model on it, with everything that had - happened so far. In a session's header, next to the agent's mark, is the - model it is running. Clicking it opens the session's controls, and{" "} - Switch agent lists the agents to move to: -

- - - -

- Cursor and Muse Spark are greyed out because they can't take over a conversation - another agent started. The other agents can, so we picked Codex. Codecast stopped the - Claude Code process that was still open in the terminal, and a divider landed in the - conversation: -

- - - -

We typed the next request in the app's message box:

- - The accented letters test from earlier shows café becomes caf. Turn accented letters - into plain ones instead, so café becomes cafe. Standard library only, and update that - test. - - - - -

- Codex made the change with Python's unicodedata, updated - Cursor's test, and ran all ten tests, which pass. To check that it had the - conversation and not only the files, we asked it something only the history could - answer: -

- - Before you answer from the files: what was my first request in this session, and which - test file did you add to then? - - - - -

- It answered without opening a file. The request it describes was sent to Claude Code, - and the work it calls its own was Claude's, because Codecast rewrote the whole - conversation in Codex's format before starting it. Our field manual chapter on{" "} - - switching agents - {" "} - explains how that works, what carries over and what doesn't, and the other ways to - move work between agents, including the ones that work for Cursor. -

- -

What you need

-

- An account and the Codecast app on each computer you code on; your empty inbox shows - the one-line install command. Keep starting Claude Code, Cursor and Codex the way you - already do, and their sessions arrive in the same list. You do not need a team for - any of this. -

- -
- Codecast records every coding agent session you run, on any machine, and gives you - one place to see them, steer them and answer them, on your own or with your team. -
- -
- - - - - - -
- -

- All seven screenshots are the Codecast web app on a local build in Chrome on - 2026-10-30. The sessions were run for this post in a throwaway repository, Cursor - first and then Claude Code, each started by hand in a terminal; the follow-ups were - sent from the app. The account's other sessions, people and projects are outside - every crop. Prompts are quoted in the text rather than pictured, the Cursor transcript - starts below its prompt, and the diff is cut off at the edges shown. Nothing was - composited or retouched. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/claude-code-from-your-phone/page.tsx b/packages/web/app/(marketing)/blog/claude-code-from-your-phone/page.tsx deleted file mode 100644 index 6a68b9d62f..0000000000 --- a/packages/web/app/(marketing)/blog/claude-code-from-your-phone/page.tsx +++ /dev/null @@ -1,289 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, CardShot, CardShots, Prompt, SOL, H2, P, Code, Terminal } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Eight genuine screenshots of the Codecast iPhone app, run in the iOS simulator -// against this checkout on 2026-11-02 and signed in to a real account. The -// sessions in them were run for this post in a throwaway repository -// (/tmp/tidebook): a Claude Code session and a Codex session, each started by hand -// in a terminal on the laptop, and a second Claude Code session started from the -// phone. Every tap pictured was a real tap in the app, and the terminal excerpt is -// copied from the laptop's terminal. The inbox is narrowed to the demo project and -// cropped below the account's header; the new session sheet is cropped above its -// folder list. Nothing was composited or retouched. - -const DIR = "/blog/claude-code-from-your-phone"; -const PHONE = 300; -/** Two phones side by side fit the text column's figure at this width. */ -const PHONE_PAIR = 272; - -export default function ClaudeCodeFromYourPhonePost() { - const post = getPost("claude-code-from-your-phone"); - useRouteMeta("/blog/claude-code-from-your-phone"); - - return ( -
- - -
- - - - - Blog - - -
-

- Answering Claude Code from your phone -

-

- You start Claude Code in a terminal on your laptop, give it a job, and walk away. Ten - minutes later it has a question, or it wants permission to write a file, and it waits. - Codecast's iPhone app shows you that session, lets you answer the question or - approve the edit, and sends your next message to the same terminal, as if you had typed - it there. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 5} min read -
-
- -

A job on the laptop

-

- For this post we made a small repository, tidebook, with one script in it,{" "} - tides.py, that prints the next high and low tide from a CSV of predictions. - In a terminal on the laptop we started Claude Code the usual way, in its default mode, - where it asks before it edits a file or runs a command. It got this: -

- - Add a --days N option to tides.py that lists every high and low tide in the next N days, - one per line. Before you write any code, ask me one question: should times print in local - time or UTC? - -

- Then we put the laptop down and picked up the phone. Everything below happened in the - Codecast app on an iPhone, while Claude Code kept running in that terminal. -

- -

The session list

-

- The app opens on the same inbox as the Codecast web and desktop apps. Sessions sit under - who acts next: Needs You when the agent is waiting on you,{" "} - Working while it runs. We had also started Codex in a second terminal on the - same project, asking it to check the README, so the list had two. The menu at the top - left narrows the list to one project: -

- - - -

- Neither session was started from Codecast. The Codecast app on the laptop picks up - Claude Code and Codex sessions as they run and keeps the list current on every device - you sign in on. -

- -

Answering its question

-

- Claude read the script and the CSV, then asked its question with two choices. Opening the - session on the phone shows the conversation as it happened: our prompt, Claude's - note, a folded row for the commands it ran, and the question with its choices as buttons. - The status under the message box reads Needs You. -

- - - -

- We tapped Local time (Recommended). The choice reached the terminal on the - laptop within a few seconds, and Claude carried on and wrote the code. -

- -

Approving a file edit or a command

-

- Because Claude Code was in its default mode, it stopped before overwriting{" "} - tides.py, again before editing the README, and again before running the - script to check its work. Each time, a card showed up in the conversation on the phone - with the tool and what it wanted to do: -

- - - -

- Tapping Approve answered the prompt in the terminal; Claude's output there - marks each one Allowed by PermissionRequest hook. In the build we used, the card - appears at the top of the conversation, above the first message, so if a session reads{" "} - Needs You and you see no question at the bottom, scroll up. -

- -

Reading the result and sending the next message

-

- When Claude finished, its reply came through on the phone as written, with the command it - ran and its output in a code block. It also pointed out something we hadn't asked - about: the sample CSV only covers two days, so its own run didn't prove the cutoff - works. So we typed the next request into the message box at the bottom: -

- - Add a unit test for the cutoff: a high tide three days out must not show up in a two day - listing. - - - - -

On the laptop, the message landed in the terminal as Claude Code's next turn:

- - -{`❯ Add a unit test for the cutoff: a high tide three days out must not show up in a two day listing. - -⏺ No test setup exists in the repo, so I'll add a stdlib unittest file that calls tides_within with a fixed now. That way it doesn't depend on the CSV or the clock. - -⏺ Write(test_tides.py) - ⎿ Wrote 16 lines to test_tides.py - … - ⎿ Allowed by PermissionRequest hook - -⏺ Running it, then breaking the cutoff on purpose to confirm the test catches it: - Ran 1 shell command - ⎿ Allowed by PermissionRequest hook - -⏺ I added the test in test_tides.py, and it passes.`} - - -

- Both Allowed lines are taps on the phone. If you come back to the laptop, the - terminal holds the whole session, and you can keep typing there; the phone is a second - way into the same conversation. -

- -

Codex in the same list

-

- The Codex session reads the same way. Its header carries the Codex mark and the model it - runs, its commands fold into rows, and its report comes through in full: -

- - - -

- We read this one on the phone and sent our follow-ups in this post to the Claude Code - session. -

- -

Starting a session from the phone

-

- The pencil at the top right of the inbox starts a new session without going near the - laptop. You write the first message, pick the agent (Claude, Codex, Cursor, Grok and - others), pick the folder and the machine to run it on. We typed the path to our demo - repository into the folder search and picked the laptop: -

- - - - - -

- The session ran on the laptop, in the demo folder, and noticed the uncommitted work the - first session had left there. Sessions Codecast starts run in Claude Code's bypass - permissions mode by default, so this one didn't stop to ask before editing or - running anything. -

- -

What you need

-

- A Codecast account, the Codecast app on the laptop (your empty inbox shows the one-line - install command), and the Codecast app for iPhone from the{" "} - - App Store - - , signed in to the same account. Android isn't out yet. Keep starting Claude Code and - Codex the way you already do. The agent still runs on the laptop, so the laptop has to be - awake and online for your answers to reach it. You don't need a team for any of - this. If you were looking for Anthropic's own ways to reach Claude Code remotely, - their documentation covers those; this post covers only what Codecast does. -

- -
- Codecast records every coding agent session you run, on any machine, and gives you one - place to see them, steer them and answer them, on your own or with your team. -
- -
- - - - - - -
- -

- All eight screenshots are the Codecast iPhone app, running in the iOS simulator on a - local build on 2026-11-02 and signed in to a real account. The sessions were run for this - post in a throwaway repository: Claude Code and Codex were each started by hand in a - terminal on the laptop, and the third session was started from the phone. Every answer, - approval and message pictured was sent from the phone. The inbox is narrowed to the demo - project and cropped below the account's header, and the new session sheet is cropped - above its folder and machine. The terminal excerpt is copied from the laptop, with the - test file's contents and the end of Claude's last reply left out. Nothing was - composited or retouched. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/claude-code-history-on-day-one/page.tsx b/packages/web/app/(marketing)/blog/claude-code-history-on-day-one/page.tsx deleted file mode 100644 index bac6ede6b0..0000000000 --- a/packages/web/app/(marketing)/blog/claude-code-history-on-day-one/page.tsx +++ /dev/null @@ -1,189 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Screenshot, SOL, H2, P, Code } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Three genuine screenshots of the Codecast web app at codecast.sh, in Chrome on -// 2026-11-08, signed in to the founder's account. The sessions pictured were -// synced as they ran over the past months, not by the history import; search and -// the transcript look the same either way. The search is narrowed to the -// account's own sessions and every result in frame is from the codecast project. -// The search image is two crops of the same results page (its top, and further -// down the list). The transcript image starts at Claude's first reply, below a -// prompt whose attached screenshot showed other people's photos. Nothing was -// composited or retouched. The import numbers come from the test run in session -// jx71jtq (ct-57303) and were rechecked against packages/cli/src/daemon.ts, -// packages/convex/convex/conversations.ts and -// packages/shared/contracts/inboxProjection.ts. - -const DIR = "/blog/claude-code-history-on-day-one"; - -export default function ClaudeCodeHistoryOnDayOnePost() { - const post = getPost("claude-code-history-on-day-one"); - useRouteMeta("/blog/claude-code-history-on-day-one"); - - return ( -
- - -
- - - - - Blog - - -
-

- Your old Claude Code sessions, on the day you install Codecast -

-

- By the time most people try Codecast, they have months of Claude Code sessions sitting - in files on their laptop. When you sign in on a machine, Codecast now uploads all of - them in the background. The ones from the past week go in your inbox. The rest are in - search and open in full, from the first day. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 4} min read -
-
- -

What happens when you sign in

-

- Claude Code writes every session to a file under ~/.claude/projects, one - folder per project. Until this month, a new Codecast install uploaded only the files - touched in the last week, so an account started out holding a week of history and grew - from there. Anything older stayed on the laptop. -

-

- Now, after you install the Codecast app on a machine and sign in, it does two passes. - The first uploads the last week, as before, so your inbox fills in first. The second goes through every Claude Code session file on the machine, however old, - and uploads the ones Codecast doesn't have yet. -

-

- The second pass is slow on purpose. It sends one file at a time and waits a quarter of a - second between files, which caps it at about 14,000 sessions an hour, so it doesn't - compete with the sessions you are running while it works. If you close the lid or restart halfway through, it carries - on the next time the app starts and skips everything already uploaded. Folders you have - excluded from syncing are skipped here too. -

-

- This pass reads Claude Code's session files. Sessions from Codex, Cursor and the - other agents Codecast supports are picked up as they run, the same as before. Version - 1.1.213 of the Codecast app, released November 5, is the first with the history pass; - machines that were already signed in don't run it on upgrade, only when they sign in - again. -

- -

Your inbox stays on this week

-

- The inbox is where you see what your agents are doing now and which of them is waiting - on you. Three hundred sessions from last spring don't belong there, so the server - treats a session differently when it started more than seven days before it was - uploaded. It keeps that session out of the inbox unless something happened in it during - the last seven days. Everything else about it is the same as any other session. -

-

- We checked this on a fresh account and a clean Mac user with 30 test sessions spread - over 14 days. All 30 arrived; the history pass handled the 16 older ones in about 13 - seconds. The 14 sessions from the past week were the ones the inbox could show, and none - of the 16 older ones appeared there. -

- -

Finding an older session

-

- The older sessions are where you would look for them anyway. Search for a word and the - results run back through your history. The note under the result count says how far - the full text goes: messages from the last 30 days are searched word for word, and older - sessions match on their title and summary. -

- - - -

- Further down the same results are sessions from six and seven weeks earlier. One matched - on its title, Hibernated badge placement; another on its summary, which shows - under it with the word highlighted. -

- - - -

- Opening one shows the whole transcript as it happened, with the dates it happened on: - the prompt, Claude's replies, folded rows for the files it read and the commands it - ran, and the files it changed. From there you can send it a new message, and it picks - up where it stopped. -

- - - -

What you need

-

- A Codecast account and the Codecast app on the machine where you run Claude Code. Your - empty inbox shows the one-line install command; it opens the browser so you can sign in, - and the history pass starts on its own after that. There is nothing to turn on. You - don't need a team for any of this. The history is yours, in your own workspace, - and works the same whether you use Codecast alone or with other people. -

-

- For people who script their setup: signing in from a terminal with{" "} - cast login starts the same pass, and the Codecast app's log shows{" "} - History import: done when it finishes. -

- -
- Codecast records every coding agent session you run, on any machine, and gives you one - place to see them, steer them and answer them, on your own or with your team. -
- -
- - - - - - -
- -

- All three screenshots are the Codecast web app at codecast.sh in Chrome on 2026-11-08, - signed in to the founder's account. The sessions in them were synced as they ran - over the past months rather than by the history pass; search and the transcript look the - same either way. The search is narrowed to the account's own sessions, and every - result in frame is from the Codecast project. The first two images are the top of one - results page and a part further down it. The transcript starts at Claude's first - reply, below a prompt whose attached screenshot showed other people's photos. - Nothing was composited or retouched. The 30-session check ran on a separate test account - on a Mac mini. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/claude-code-sessions/page.tsx b/packages/web/app/(marketing)/blog/claude-code-sessions/page.tsx deleted file mode 100644 index b78e460d98..0000000000 --- a/packages/web/app/(marketing)/blog/claude-code-sessions/page.tsx +++ /dev/null @@ -1,217 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Screenshot, SOL, H2, P, Code, CardShot } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Six genuine screenshots of the codecast web app on a local build of this -// checkout, in Chrome on 2026-10-27. The two sessions in them were run for this -// post in a throwaway repository (/tmp/wordcount): one Claude Code session and -// one Codex session, each started by hand in a terminal. The Claude Code -// session was renamed in the app, its process was ended, and the follow-up -// pictured was sent from the app's composer, which resumed it. Every image is -// cropped to one part of the screen; the rest of the account (other sessions, -// people, projects) is outside every crop. Nothing was composited or retouched. - -const DIR = "/blog/claude-code-sessions"; - -export default function ClaudeCodeSessionsPost() { - const post = getPost("claude-code-sessions"); - useRouteMeta("/blog/claude-code-sessions"); - - return ( -
- - -
- - - - - Blog - - -
-

- Finding, naming and reopening your Claude Code sessions -

-

- Claude Code keeps every session as a file on the machine that ran it, named by a - random id. Codecast collects those sessions, and the ones from Codex, Cursor and - Gemini, from every computer you use into one list. You can search what was said in - them, give them names, read the whole transcript with the code it changed, and send - the next message to any of them. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 6} min read -
-
- -

Two sessions

-

- To show this on something you can read, we ran two small sessions for this post in - a throwaway repository with one script in it, wc.py, which counts the - words in a file. In one terminal, Claude Code got this: -

-
- Add a --top N option to wc.py that prints the N most common words with their counts - after the total. Standard library only, and update the README. -
-

- In another, Codex was asked to write unit tests for the same script. Neither was - started from Codecast. Both were plain terminal sessions, and both showed up in the - inbox while they ran, because the Codecast background app on the laptop picks up - every session as it happens. Clicking the wordcount project chip at the top - of the list narrows it to that repository: -

- - - -

- Each card shows which agent ran it, its title, its last message and its project. The - same list holds sessions from every computer where you have installed Codecast, so a - session you ran on a desktop last week sits next to the one you started on a laptop - this morning. -

- -

Naming a session

-

- A session starts out titled with the start of its first message. That is often good - enough, and often it is not: Add a --top N option to wc.py that prints the N - mo... is long and says nothing you would search for later. To rename one, open - it and press Ctrl+Shift+E: -

- - - -

- The new name is saved to your account, so it is the name in the inbox, in search, - on your phone and in every other window, as the card above shows. -

- -

Finding an old one

-

- The search box at the top of the app shows matching sessions as you type. For more - control, the search page takes the same query with filters: Only mine{" "} - (leave out teammates' sessions, if you have a team), My prompts (match - only what you typed, not what the agent wrote), a time range, and a choice between - most recent and most relevant first. Here, looking for the session where we asked - about standard input: -

- - - -

- Search reads the messages themselves from the last 30 days, and the title and - summary of every session before that, which is one more reason to give the sessions - you will want again a name. -

- -

The whole transcript, and the code it changed

-

- Opening a session shows the conversation as it happened. The agent's tool calls - are folded into small rows (ran ls, wrote 2 files,{" "} - 1 edit, ran 2 commands) that open to show the command and its output: -

- - - -

- Next to the conversation is the code. The panel has a tab for the whole session, the - branch, a commit, and the last turn, each as a diff of the files involved. This is - the Turn tab after the follow-up below, two files, eight lines added and four removed: -

- - - -

Picking it back up

-

- By the time we came back to the Claude Code session, its terminal was closed and the - process was gone. In Codecast the conversation still ends in a message box. We typed - the next request there: -

- - - -

- Codecast started Claude Code again on the laptop with --resume and that - session's id, so it carried on with its full history, and the answer was back - in about twenty seconds. You do not need to find the id, the folder it ran in or the - machine it was on. The diff panel and the inbox card updated with the new turn. -

- -

What you need

-

- An account and the Codecast app on each computer you code on; your empty inbox shows - the one-line install command. Sessions start arriving from then on, from Claude - Code, Codex, Cursor and Gemini CLI. You do not need a team for any of this. If you - have one, the same inbox can show their sessions too, and the Only mine{" "} - filter takes them back out. -

- -
- Codecast records every coding agent session you run, on any machine, and gives you - one place to see them, steer them and answer them, on your own or with your team. -
- -
- - - - - - -
- -

- All six screenshots are the Codecast web app on a local build in Chrome on - 2026-10-27. The two sessions were run for this post in a throwaway repository, each - started by hand in a terminal. The account's other sessions, people and - projects are outside every crop. The transcript image starts below the first prompt, - which is quoted in the text instead, and the diff is cut off below the lines shown. - Nothing was composited or retouched. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/codecast-in-the-cloud/page.tsx b/packages/web/app/(marketing)/blog/codecast-in-the-cloud/page.tsx deleted file mode 100644 index d8dd624476..0000000000 --- a/packages/web/app/(marketing)/blog/codecast-in-the-cloud/page.tsx +++ /dev/null @@ -1,476 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, SOL, H2, P, Code, Figure, Screenshot } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; -import { ArrivalFigure, CloudsTable, FigureStyles, GitFigure, MapFigure, MigrateFigure, SleepFigure, SyncFigure, TravelFigure } from "./figures"; - -// Screenshots are single elements of the real app (Settings → Devices, -// Settings → Migration, the conversation header's machine menu), captured -// with scripts/app-element-shot.ts from the codecast team's own workspace on -// 2026-10-09. Nothing else from that workspace is in frame. - -const IMG = "/blog/codecast-in-the-cloud"; - -const MOVE_NOTICE = `[codecast] This session just moved to a different machine. It now runs on -Linux - ip-172-31-40-243 in /home/ubuntu/work/codecast (previously -macOS - MacBook-Pro-182). Processes, ports, and any files outside the working -tree from the previous machine are not here.`; - -const LIMITS: [string, string][] = [ - ["Waking a sleeping machine needs your laptop online.", "Work sent to an asleep machine wakes it through the laptop that manages it. If that laptop is closed, the work waits."], - ["Only Linux machines sleep on their own.", "A cloud Mac stays up, and AWS bills its dedicated host for at least 24 hours either way."], - ["Only Claude Code sessions move.", "Any agent can start on a cloud machine, but moving a running session between machines works for Claude Code, and never straight from one cloud machine to another."], - ["Most tool sign-ins travel when they exist.", "Claude, Codex, Gemini and a few others travel only while their sign-in is valid. Sign-ins for tools like GitHub, AWS and npm travel whenever your laptop has them. Your Anthropic API key and your Google logins never do."], - ["Adding a machine runs one command on your laptop.", "The Add a cloud machine dialog builds it for you, because your AWS credentials and SSH key live on your laptop, not in a browser."], - ["A cloud Mac only applies part of a repository's setup.", "System packages and services are set up on Linux machines; on a Mac, setup commands and iOS simulators apply."], -]; - -export default function CodecastInTheCloudPost() { - const post = getPost("codecast-in-the-cloud"); - useRouteMeta("/blog/codecast-in-the-cloud"); - - return ( -
- - - -
- - - - - Blog - - -
-

- Codecast in the cloud -

-

- {post?.dek} -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 14} min read -
-
- -

- Most cloud agent products give you a fresh clone of main in somebody - else's sandbox. Your uncommitted change is not there, your .env.local{" "} - is not there, your agent instructions and your logins are not there, and the agent - spends its first ten minutes rebuilding a world you already had. Codecast went the - other way. A cloud machine is a computer in your own AWS account that codecast sets - up to look like your laptop, and a session you send there starts from the folder you - are working in. -

-

- This post walks through all of it, in the order you meet it in the app: adding a - machine, starting a session there, what the machine is given, how it pushes code, - keeping the agent's edits on your laptop as they happen, moving running sessions - between machines, watching a cloud session's browser and screen, cloud Macs with - iOS simulators, sleep and wake, and the other companies' clouds codecast also - shows in your inbox. The limits are at the end, stated plainly. -

- -
- -
- -

- One idea runs through the whole design: your laptop is the source of - truth, and the cloud machine is a second pair of hands. Files and sign-ins go - from the laptop to the machine directly. When the machine needs something only the - laptop has, such as a site's login, it asks, and the laptop does the work. - Codecast's servers carry instructions and short-lived tokens, never your source. -

- -

Add a machine

-

- Open Settings → Devices. It lists every machine connected to - codecast and whether it is online; under Machines, Add a - cloud machine sets up a Linux or Mac machine in your own AWS account. Pick - Linux for general development (it sleeps when idle) or Mac for Xcode and iOS work, - connect an instance you already run or create a new one, and fill in the AWS details. -

- - - -

- The dialog builds one setup command, which you copy and run once in a terminal on - your laptop, from your project. That step stays on the laptop on purpose: it is - where your AWS credentials and SSH key live. Setup installs what a session needs, - copies your agent configuration over, and waits for the machine to come online. -

-

- From then on the machine has its own panel in Settings → Devices. It shows whether - the machine is Awake, Waking, Going to - sleep or Asleep, its size and region, what it costs per - hour awake and per month for its disk, and when it next sleeps. The buttons wake it, - put it to sleep, apply the repository's setup again, or Save - image, which snapshots a ready machine so the next one starts ready. Rows - for your setup, sign-ins and tools say what is in step, and which sign-ins were held - back and why, before an agent finds out the hard way. -

- -

Start a session from your screen, not from main

-

- Once a cloud machine exists, the composer grows a run in the cloud{" "} - switch. Turn it on and the new session runs on the machine in a worktree of its own. - Two more choices sit beside it. start from is my - checkout (your exact working state) or origin/main (a clean - start). isolated worktree, on by default, can be turned off to run in - the machine's main checkout, for a job like a data migration that must run where - everything else is; that is refused if the checkout has changes or another session - is using it. An asleep machine wakes when the session starts, and the header reads{" "} - preparing cloud host while its checkout is made. -

- - -

- “My checkout” is the part that took the longest to get right. Your laptop - takes one snapshot of your folder, ignored files included, without moving anything in - your checkout. The machine restores it so your uncommitted edits show up as - uncommitted again, and checks that its folder matches yours before the agent starts. - Any agent works there: Claude Code, Codex, Cursor, Gemini, opencode, pi or Grok. -

- - - -

- Not everything should travel. Dependency folders are rebuilt on the machine, because - a node_modules built on a Mac is wrong on Linux anyway, and big untracked - media and binaries stay home. Each file left behind is listed under the reason it - stayed, so you can see the decision rather than discover it. -

- -
- -
- -

- Agents can start cloud sessions too. One that fans out five tasks gets five worktrees - from a single snapshot, so all five start from the same instant of your work (for an - agent, that is cast spawn --cloud). -

- -

The machine is set up like your laptop

-

- An agent is only as good as its context, and most of the context lives outside the - repository: your agent settings, your CLAUDE.md, the skills and hooks you - wrote, the shell setup your hooks assume, the sign-ins for the tools your agents call. - You never set a cloud machine up by hand. Before a session starts, and whenever the - machine wakes for one, your laptop brings it into step: -

- -
- -
- -

- Your agent setup travels: agent settings, instruction files, skills, - hooks, your shell setup and your agents' memory, with laptop paths rewritten to - the machine's. Memory comes back the other way too, so what a cloud session learns - is not stranded there. Credentials, transcripts, caches, SSH keys and browser profiles - never travel. -

-

- Sign-ins go one way, from your laptop to the machine. The Claude - sign-in is the delicate one: refreshing it on the machine would log you out at home, - so the machine is never allowed to refresh it, and your laptop sends a fresh one when - its own renews. Your Anthropic API key deliberately stays home, because its presence - would move every Claude on the machine off your subscription and onto metered API - billing. Tools arrive at your laptop's versions, installed for - your user without admin rights. -

-

- When a repository needs more on the machine, a database or a system package, ask an - agent to add it to the repository's codecast setup. Every machine applies it before - the next session starts, and skips it when it is already in step. -

- -

Pushing code without leaving a key on the machine

-

- A machine that runs agents unattended should not hold a long-lived GitHub token. With - the codecast GitHub app installed for a repository, the machine asks for a token each - time it pushes, and codecast hands back one scoped to that one repository, after - checking that you are allowed to push. It expires within the hour and is never written - to disk. -

- -
- -
- -

- Where the app cannot help, Settings → Devices marks the repository needs - access and shows the machine's own public key with a Copy{" "} - button. Add it on GitHub as a deploy key with write access, and pushing starts working - within minutes. -

- -

The agent's edits, on your laptop, as they happen

-

- A cloud session is only half useful if its work is stuck there. Click the machine name - in a cloud session's header and choose Sync with your laptop. The - session's folder is then kept in step with a copy on your laptop, both ways, a few - seconds behind. Open it in your editor, run the tests locally, or fix a line yourself - and let the agent see it. A chip in the header shows the state: syncing,{" "} - in step with the time of the last sync, or sync paused while the - session is idle, so the machine can still sleep. Its menu opens the copy in Cursor or - VS Code. -

-

- When only one side changed, its changes land on the other. When both changed, the - files that merge cleanly land, and a file changed on both sides is held as it is on - each side while everything else keeps flowing. Only files that actually changed are - written, so your editor and your dev server do not see a storm of rewrites. -

- -
- -
- -

- A held file never gets conflict markers written into it: the chip lists it with{" "} - Keep the laptop's and Keep the cloud's.{" "} - Cloud to laptop only turns the copy into a mirror you read rather - than edit, and if you edit it anyway, the sync stops and asks whether to send your - edits or take the cloud's. -

- - - -

Move running sessions before you close the lid

-

- The most common reason to want a cloud machine is the moment you need your laptop - back: a flight, a meeting, a laptop pinned at full load. Click the machine name in a - conversation's header for Run on device · which machine, and pick - where the session should run. An asleep cloud machine is marked{" "} - asleep, wakes on move. -

- - - -

- For many sessions at once, select them in the inbox and choose Move - to…, or open Settings → Migration. Migration lists your - sessions with filters, and you pick a destination: each card says whether the machine - is online and how many sessions already run there. -

- - - -

- Then you decide how to treat a session that is in the middle of a turn. It finishes - the turn first, up to the wait you choose, or is interrupted at once. Anything you send - it meanwhile is held and delivered on the other side. A session waiting on a - permission prompt moves at once and asks again on the new machine. -

- - - -

- Each session walks through the same steps, shown live under Migrations{" "} - on the same page: new turns are held, the turn finishes, the agent stops, its work - and conversation transfer, and it resumes on the other side. Coming home, the cloud - machine's work lands in your checkout as uncommitted changes. If it does not apply - cleanly, that session fails with the reason, nothing in your folder changes, and the - session keeps running where it was. -

- -
- -
- -

- The conversation marks the move with a rule reading now running on …, and the - agent is told, so it does not go looking for a dev server it left behind: -

- -
-
{MOVE_NOTICE}
-
- -

- Run here, on any laptop, brings a cloud session home without - interrupting a turn in progress. And when your laptop is under sustained pressure - (memory, CPU, or load for a minute or more), the Resources page offers - to offload sessions to a cloud machine, spreads them for you, and waits for you to - confirm. On the iPhone app, tap the machine in a session's header to move it. -

- - - -

Watch the cloud machine work

-

- A cloud machine has its own Chrome, so agents there verify UI and read behind sign-ins - without touching yours. watch live on a browser step shows the - agent's tab beside the conversation. Take the wheel gives you the - mouse and keyboard, for example to sign in where the agent cannot, and{" "} - Hand back returns it. When an agent needs a site you are already - signed in to, your laptop copies that one site's login across. Google logins are - never copied. -

-

- For anything outside the tab, a popup, a file picker or a native dialog, the screen - button opens the machine's whole display in a Host screen pane. - The tmux pill in the header opens the agent's terminal; typing - works there, a moment behind. Agents on the machine can also drive native Linux apps - the same way they do on a Mac. -

-

- One capability is command-line only today: mounting a folder from your laptop on the - cloud machine at the same path, with no copy (cast hosts reach ~/notes). The - laptop serves just that folder from a locked-down sandbox, and the folder is there only - while your laptop is. -

- -

Cloud Macs and iOS simulators

-

- A cloud Mac is for work that needs Xcode. Add iOS simulators to the repository's - codecast setup (or ask an agent to), and the Mac gets a copy of your laptop's - Xcode, the iOS runtime and the tools agents use to drive a simulator. From then on an - agent on the Mac installs its build in a simulator, taps through it and puts - screenshots in the conversation, exactly as it would on your laptop. The first Xcode - copy is slow, close to an hour for us; it happens once. -

- -

It sleeps when nothing is happening

-

- A machine that runs all night for nothing is the fastest way to stop trusting the - feature, so a Linux machine watches for real work and stops itself without it. Real - work means an agent mid-turn, a background job, someone watching its screen, or a - process using CPU. An agent idling at a prompt is not work. After twenty idle minutes - the machine powers off, and a stopped machine costs only its disk. Its panel in - Settings → Devices says when it will sleep. -

- -
- -
- -

- Waking is automatic. Work for an asleep machine, a message, a moved session or a - scheduled trigger, wakes it through your laptop, and the work starts once it is up. - You can also press Wake in its panel. A Mac is different: its AWS - host bills while allocated, awake or asleep, so it does not sleep on its own. -

- -

When something breaks

-

- Machines fail in boring ways, and most of the work here went into making the failures - boring too. If an agent's process dies in the middle of work, on a cloud machine - or a laptop, codecast restarts the session with a note explaining what happened, at - most three times in six hours, and never one you stopped yourself. A move that stops - reporting for thirty minutes is failed, and the session stays where it was. The - machine's panel shows which sign-ins and tools are missing before an agent trips - over them. -

- -

The other clouds

-

- Your cloud machine is not the only cloud your agents run in. Codecast also shows, and - mostly drives, the cloud agents other companies run, in the same inbox and the same - search as everything else. Add a Cursor key and your Cursor Cloud agents appear as - sessions; the composer's run in Cursor Cloud starts one, and your - messages become its follow-ups. Turn on Codex Cloud tasks and run in - OpenAI's cloud starts one with up to four attempts, then Create - draft PR or Apply locally. Claude Code sessions you started on - the web show up with their full transcripts, and you can reply from codecast. -

- -
- -
- -

- The difference is the starting point. A vendor's cloud starts from what is on - GitHub. Your machine starts from what is on your screen, which is why we built it. -

- -

What it needs, and where it stops

-
    - {LIMITS.map(([q, a]) => ( -
  • - {q} {a} -
  • - ))} -
- -
- Codecast is where your team sees, steers, and remembers every coding agent session, on - any agent and any machine, including the ones you rent. -
- -
- - - - - - -
- -

- The screenshots of Add a cloud machine, the machine menu and Settings → Migration are - single elements of the real app, captured from the codecast team's own workspace - on 2026-10-09 with nothing else in frame; two unrelated offline machines are hidden - from the menu and the destination list. The 60 second wake was measured on 2026-09-05. - The figures are drawn from the code's own constants (tick rates, timeouts, idle - minutes); the migration batch and the sync timeline are schematic. Three illustrations - come from the field manual's cloud chapter. If you script codecast, every action - here also has a cast command; cast --help lists them. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/fewer-bigger-jumps/page.tsx b/packages/web/app/(marketing)/blog/fewer-bigger-jumps/page.tsx deleted file mode 100644 index a324f8ad02..0000000000 --- a/packages/web/app/(marketing)/blog/fewer-bigger-jumps/page.tsx +++ /dev/null @@ -1,210 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, SOL, H2, P, Figure } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; -import { AttentionFigure, FigureStyles, JumpsFigure, PromptFigure, TraceFigure } from "./figures"; - -export default function FewerBiggerJumpsPost() { - const post = getPost("fewer-bigger-jumps"); - useRouteMeta("/blog/fewer-bigger-jumps"); - - return ( -
- - - -
- - - - - Blog - - -
-

- {post?.title ?? "Fewer, bigger jumps"} -

-

- {post?.dek} -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 7} min read -
-
- -

- Most advice about prompting coding agents is about getting each answer right. Be - specific, give context, ask for one thing at a time. That advice optimizes the - wrong number. It treats the model's output as the scarce thing, when the - scarce thing is you: the minutes you spend reading what came back, deciding what - is wrong with it, and writing the next prompt. -

-

- Call each of those cycles a jump. Every feature is a distance from where the code - is to where you want it, and every jump costs a slice of your attention whether it - moves you an inch or a mile. Tokens are cheap and getting cheaper every quarter. - Your attention is fixed at a few good hours a day. So the thing to minimize is the - number of jumps, and the way to do that is to make the first one enormous. -

- -
- -
- -

Two ways across

-

- The familiar way is small hops. You ask for one safe, well specified step, check - it, ask for the next. Each hop lands roughly where you aimed, which feels like - control. But a feature of any size is fifteen or twenty of them, and every one - waits on you. Worse, you are doing the planning, the sequencing and most of the - verification in your head, which is exactly the work the agent could have done. -

-

- The other way is one leap. You describe the destination, what done looks like and - how to check it, and then you tell the agent to keep going on its own: plan, build, - run it, look at it, find what is wrong, fix it, and go around again. In the figure, - those coils inside the first orange arc are that loop. They cost tokens and - wall clock time. They cost you nothing. -

-

- The leap will not land on the target. It will land somewhere near it, built on a - few guesses you would have made differently. That is fine, and it is the part - people underrate. -

- -

Why missing is useful

-

- A working artifact that is wrong in specific ways is the cheapest thing in the - world to steer. Before the leap you would have had to specify everything up front, - including dozens of choices you had no opinion on until you saw one. After it, you - only have to name the handful you disagree with, and you can name them by pointing. -

-

- Here is what that looks like in practice, from a session in our own repository this - week. One prompt asked for a page that tells the story of everything the team is - shipping. The agent worked through more than 750 messages on that prompt alone, building a - per-day timeline, wiring it to real data, screenshotting it and fixing what it saw. - Then came the second real prompt: the correction. -

- -
- -
- -

- The correction is a big jump of its own: a single timeline instead of one page per - day, plainer copy, fewer features on the surface. It moves a long way, but it moves - from a place that was already close, so it lands much closer still. The jumps after - it get smaller: a spacing fix, a label, a tweak to the default zoom. Each one is - cheaper to write than the one before, because the remaining error is smaller and - easier to see. The docs audit below it is the same shape at a smaller size: one - prompt to rewrite the docs with diagrams and screenshots, about 270 messages of - work, and a three word correction. -

- -

What a leap prompt asks for

-

- A leap prompt is not a longer hop prompt. It asks for different things. It names - where you are going rather than the next step. It says how the agent will know it - has arrived, in terms it can check itself: tests, a browser, a screenshot. It - explicitly invites the agent to spend more: plan first, fan work out to subagents, - run a workflow that builds and reviews in parallel, and keep iterating on polish - after the thing works. And it says when to stop and ask, which should be rarely. -

- -
- -
- -

- The most important line is the definition of done. Without one, an agent stops at - the first plausible result, and you become the test suite. With one, the agent - does the looking for you: it opens the page, notices the overlapping labels, and - fixes them before you ever see them. Every problem it catches on its own is a jump - you did not have to make. -

-

- This deliberately spends more compute per prompt, often a lot more. A leap can run - for an hour and burn through more tokens than a day of hops. That is the trade, and - it is a good one. You are buying back the only resource in the loop that does not - scale. -

- -

Fill the time the leap buys

-

- A leap that runs for forty minutes is forty minutes in which you are not needed. - The mistake is to spend them watching. The point of making each session need you - less is that you can run several, and spend your attention moving between them: - write the leap for one, launch it, write the leap for the next, then come back to - the first when it lands and send its correction. -

- -
- -
- -

- Throughput here means the share of your attention spent on decisions rather than - waiting. With small hops it is low no matter how fast the model is, because every - hop ends in a wait. With leaps it can approach all of it, and the corrections shrink - as each session converges, so the later rounds go by quickly. Five sessions moving - in big jumps finish more in an afternoon than one session moving in small ones - finishes in a week. -

-

- Running like this needs a place to see who is waiting on you. That is what - codecast's inbox{" "} - is for: every session on every machine, sorted by who acts next, so the next jump - you make is always the one that is ready for it. An agent on a long leap can hand - pieces of it to worker sessions that nest under its own card, and a trigger on the - Triggers page can wake a session later instead of a reminder in your head. -

- -

The rule

-

- Before you send a prompt, ask whether it could carry the next three prompts too. - Usually it can: say where you are going, say how to check, say keep going. Expect - the result to be wrong, and be glad it is wrong somewhere you can point at. Then - make the big correction, then the smaller ones, and spend the gaps on the next - leap. -

- -
- Count your jumps, not your tokens. -
- -
- - - - - - -
- -

- The session traces are real: message counts and prompt positions from two codecast - sessions in this repository, read on 2026-10-04, with the quoted prompts trimmed - where marked. Bare "continue" messages after a pause are drawn separately - because they carry no direction. The jump paths and the attention schedule are - illustrations, not measurements. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/one-repository-twenty-checkouts/page.tsx b/packages/web/app/(marketing)/blog/one-repository-twenty-checkouts/page.tsx deleted file mode 100644 index af9412499c..0000000000 --- a/packages/web/app/(marketing)/blog/one-repository-twenty-checkouts/page.tsx +++ /dev/null @@ -1,204 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Terminal, SOL, H2, P, Code, Screenshot } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// The workspace config is the codecast repository's own file. The Worktrees -// screenshot is the repository's Worktrees tab in the codecast web app on -// 2026-10-09; the counts in the prose are from `cast ws` on 2026-10-04. - -const WS_TOML = `[setup] -copy = [ - ".env", - ".env.local", - "packages/convex/.env.local", - "packages/web/.env.local", - "packages/cli/.env.local", -] -install = ["bun install"] - -[ports.web] -base = 3201 -range = 20 -`; - -export default function OneRepositoryTwentyCheckoutsPost() { - const post = getPost("one-repository-twenty-checkouts"); - useRouteMeta("/blog/one-repository-twenty-checkouts"); - - return ( -
- - -
- - - - - Blog - - -
-

- One repository, twenty checkouts -

-

- Running several agents at once is easy until two of them edit the same file. - Codecast gives each one its own worktree, with the env files, dependencies and a - port of its own, from one switch when you start the session. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 5} min read -
-
- -

The shared checkout problem

-

- Three weeks ago on this blog, a Codex agent and a Claude Code agent coordinated a - repair by messaging each other, because both were editing one working tree and one - of them had to stay out of the other's files. That was the right thing to do in - a shared checkout, and it is also a cost: two agents spending turns negotiating who - may touch which file. The cheaper answer, when the work allows it, is to not share - the checkout at all. -

-

- Git has had worktrees for years: extra checkouts of the same repository, each on its - own branch, sharing one object store. What stops people using them for agents is - everything around the checkout. The ignored files that hold secrets are not copied. - Dependencies are not installed. The dev server wants port 3200, which the main - checkout already holds. By the time an agent has fixed all that, it has spent its - first ten minutes on plumbing. So codecast made the plumbing part of starting a - session. -

- -

One switch

-

- When you start a session from codecast, the new session screen has a switch - labelled isolated worktree. Leave it off and the agent works in the - checkout you picked, alongside everyone else. Turn it on and the agent gets a - checkout of its own: a worktree on a new branch, the secret files copied in, the - install run, and a port nobody else holds. The session's card in the inbox - carries the worktree's name (hover it for Worktree <name> - (<branch>)), and the session header shows the same pill, so you can tell - at a glance which branch a conversation is editing. -

- -

Every checkout in one list

-

- Each repository in codecast has a Worktrees tab: every checkout of it on - every machine, grouped into the main checkout, codecast's worktrees, worktrees - other agents made, and the rest. Each row says what branch it is on, how far it is - from main, which port it was given, and which sessions are working in it: -

- - - -

- On the morning this post was drafted that list held nineteen codecast worktrees: - seventeen ready, one being torn down, one broken. By the time we took the screenshot - most had been finished and removed, which is what they are for. The broken one was - the interesting row. A workspace carries a contract, and codecast checks it rather - than assuming it: the worktree exists, the branch is right, dependencies are - installed, the secret files are present, the port is assigned and nothing else is - listening on it. When a clause fails, the row says setup is broken, and - rerunning the setup makes it true again. -

- -

What a workspace promises

-

- The contract comes from one file in the repository, which codecast generates by - looking at the project and which the team then edits and commits. Ours is short: -

- - {WS_TOML} - -

- Three things: which ignored files to copy from the main checkout, what to run after - the copy, and which ports to hand out. Each workspace gets an index, and its web - port is the base plus twenty times that index, probed free before it is handed - out. The worktree in the screenshot is index zero, so its row says{" "} - web :3201. - Two agents can each run a dev server without reading each other's pages. -

- -

Made, used, removed

-

- For this post we asked for a worktree that did not exist, watched it come up, and - took it down again. It came up on a new branch with the secret files copied and the - install run, and with a port. That last part was the honest surprise: the pool of - ten port indices was already spent on the worktrees in the list, so codecast - extended it and gave this one index ten, port 3401. A session that restarts lands - back in the worktree it had, rather than getting a second one. Teardown runs any - teardown hooks, removes the worktree, and drops its state, so the port goes back to - the pool and the name is free. -

-

- Agents can do all of this themselves from a terminal, which is how most of those - nineteen were made: cast ws acquire <name> to get one,{" "} - cast ws destroy <name> to give it back, cast ws ls{" "} - for the same list the tab shows. Agents turn out to be better at acquiring than - destroying, which is why the list ran long. -

- -

Where this fits

-

- A workspace is a checkout, not a sandbox. The agent in it still runs on your - machine, with your logins and your tools, and its session lands in your inbox like - any other, with its worktree named on the card and in the header. Two agents in two workspaces cannot - overwrite each other's files, and they still share everything else codecast - gives a team: the inbox, search across both sessions, and messages between them - when the work does need a word. -

-

- The rule we have settled on is simple. Work that can live on a branch gets a - workspace. Work that must land in the main checkout, because the human is in it - too, stays shared and the agents talk. Both are one switch away, and the Worktrees - tab tells you which is which. -

- -
- Codecast is where your team sees, steers, and remembers every coding agent session — any - agent, any machine. -
- -
- - - - - - -
- -

- The counts of nineteen worktrees, the broken row and the port allocation are from{" "} - cast ws on the codecast checkout on 2026-10-04; the demo worktree was - created and removed for this post and nothing else on the machine changed. On a - machine carrying 183 registered worktrees and a full load of agents, creating it - took about twenty minutes and removing it about ten, nearly all of it waiting on git. - The config file is the repository's own. The screenshot is the repository's - Worktrees tab in the codecast web app on 2026-10-09, cropped to the content column. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/the-chart-in-the-reply/page.tsx b/packages/web/app/(marketing)/blog/the-chart-in-the-reply/page.tsx deleted file mode 100644 index 33817af09e..0000000000 --- a/packages/web/app/(marketing)/blog/the-chart-in-the-reply/page.tsx +++ /dev/null @@ -1,229 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Terminal, Cmd, SOL, H2, P, Code, Screenshot } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Five genuine screenshots of the codecast web app on 2026-10-18, from two of -// codecast's own sessions: jx7afyf ("Agent fleet CPU scheduling", Oct 5; the -// canvas is message 47 and the reply message 48) and jx743jq ("Character -// subject rendering", Oct 1; the canvas is message 18, the reply message 30). -// Each is cropped to the conversation column: the sidebar, top bar, session -// header and right rail are outside every crop, as is the sticky header that -// repeats the user's last message. Nothing was composited or retouched. The -// fullscreen view and the phone app are described, not pictured. - -export default function ChartInTheReplyPost() { - const post = getPost("the-chart-in-the-reply"); - useRouteMeta("/blog/the-chart-in-the-reply"); - - return ( -
- - -
- - - - - Blog - - -
-

- The chart in the reply -

-

- Some findings are a shape: sixteen numbers where four stand out, five versions of - one line of UI. In Codecast an agent can put that shape in its reply as a chart, a - table or a mockup, drawn right in the conversation, so you see it before you read - the paragraph explaining it. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 5} min read -
-
- -

Sixteen cores in one picture

-

- On October 5th the machine we build Codecast on was overloaded again, and we asked - an agent to investigate and talk through the root cause with us. The session's - first pass, run by Codex, put it down to too much independently launched work with - no machine-wide budget. A session the Thursday before had blamed a low battery. - Claude, which took over in the same session, measured the load on each core - separately, and its reply led with this: -

- - - -

- You do not need the paragraph to get it. Four blue bars at 100 percent, twelve green - bars well under half. The agent's reading: every agent on the machine was running - at a throttled priority that macOS keeps on the four efficiency cores, so all the work queued there while - the twelve performance cores sat mostly idle. The text under the chart carried the - rest of the evidence: 680 processes at the clamped priority shared 2.6 cores, and - the same busy loop got 0.44 seconds of CPU from an agent shell against 9.43 seconds - as an unthrottled job, about twenty times more. The cause was one missing setting - in the launch file of Codecast's background process. -

-

- The chart has one flaw, and we left it in. The agent wrote the core numbers as text, - so the axis sorts them as text: 0, 1, 10, 11 and on to 15, then 2, 3. That is why two - of the blue bars sit in the middle. The small warning sign in the corner is the chart - library noticing the same thing: the values look like numbers but arrived as strings. -

- -

What the reply was for

-

- The agent ended that reply with three choices about rollout and asked how to handle - the restart. The answer came back in one line: -

- - - -

- The fix shipped: the background process now launches at interactive priority, and - existing installs rewrite their launch file automatically. Once it was live, the - agent measured again and reported all sixteen cores busy instead of four. It also - found that the fix removed only one of two causes, and the second became more work - in the same session. The chart did its job either way. It turned a disputed diagnosis into something you - could check at a glance, and the decision came right after it. -

- -

Five versions of one line

-

- A canvas is just as useful when the question is how something should look. On - October 1st we told an agent that the way Codecast prints a session's character - name and title, as in Whisker : Team huddle observation, was subtly off. - The usual move would be to change the component and check it in a browser, but the - machine was at a load average of 275 and the agent's browser connection kept - stalling. So it wrote: "Instead I'll lay the variants out side by side in a - canvas." -

- - - -

- The rows are drawn with the app's own font and colors, so they look the way the - real line would. The agent applied B, the smallest fix, and recommended E if that - still felt flat. It also pointed out a cost of D: the app already uses a middle dot - between pieces of metadata. We picked D anyway: -

- - - -

- Two words were enough because every option had a letter and a picture. The agent - made the swap, updated the three test assertions that checked the old colon, and - the middle dot is what the app shows today. -

- -

How a canvas behaves

-

- A canvas sits in the conversation like any other part of the reply, with its title - on a header strip and three controls. Show source flips it to the HTML the - agent wrote, Copy HTML copies that, and Fullscreen opens it on its - own over the app; Esc closes it. A tall canvas folds behind a fade - with a control to show the rest. -

- - - -

- The source shows how little the agent writes for a chart: a title, a caption, and a - description of the bars as data. Codecast draws the chart itself, so it uses the - app's font, follows light and dark mode, and can show each value on hover. The same goes for - tabs, sortable tables and tooltips. You can also see the cause of the odd axis order - here: "c":"0" is a string. -

-

- Canvases are safe to show to anyone who can read the session. No script the agent - writes ever runs: Codecast strips scripts and event handlers before drawing. A - canvas also cannot load anything from outside. An image has to be embedded in the - canvas or stored in Codecast, so viewing one never tells a third party you looked. The desktop app - draws canvases the same way as the web app, and the phone app draws them too; an - older phone build that predates the feature shows the source as a code block - instead. -

-

- Agents do not need prompting to use this. The instructions Codecast installs for - your agents tell them to reach for a canvas when structure or size carries the - meaning (comparisons, flows, timelines, metrics) and to keep ordinary prose in - markdown. The same applies to the questions agents put in your decision queue, - where a canvas can lay the options side by side. -

- -

From a script

-

- A canvas is a fenced block in the agent's markdown, so any agent that writes - markdown can draw one, and so can you: -

- - - ```cast-canvas - <div data-canvas-title="Shown in the header"> … </div> - ``` - - -
- Codecast records every coding agent session you run, on any machine, and gives you - one place to see them, steer them and answer them. -
- -
- - - - - - -
- -

- All five screenshots are the codecast web app on 2026-10-18, of two of codecast's - own sessions from October 1 and October 5. Each is cropped to the conversation - column: the sidebar, the top bar, the session header and the right rail are outside - every crop, as is the strip that keeps the last user message pinned at the top while - you scroll. The fourth screenshot starts at the canvas, below the agent's one-line - lead-in quoted above it. Nothing was composited or retouched, and the chart's - axis order and warning sign are as the agent drew them. The fullscreen view and the - phone app are described, not pictured. No message was sent and no session was - changed for this post. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/the-questions-your-agents-save-for-you/page.tsx b/packages/web/app/(marketing)/blog/the-questions-your-agents-save-for-you/page.tsx deleted file mode 100644 index 363227cbba..0000000000 --- a/packages/web/app/(marketing)/blog/the-questions-your-agents-save-for-you/page.tsx +++ /dev/null @@ -1,232 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Terminal, Cmd, SOL, H2, P, Code, Screenshot } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Five genuine screenshots of the codecast web app on 2026-10-15, of two real -// answered decisions about codecast's own work: sd-25 (the ads check cadence, -// asked and answered on Sep 13) and sd-177 (how to fix messages arriving as -// pasted text). Each is cropped to the content column. The sidebar, top bar -// and right rail are outside every crop. The open queue itself is not -// pictured: on the day of capture it held only other projects' questions. -// sd-25's last context paragraph and the agent's status line under the card -// are outside the crops because they carry dollar figures; sd-177's third -// option is below its crop because it names another project. - -export default function QuestionsYourAgentsSaveForYouPost() { - const post = getPost("the-questions-your-agents-save-for-you"); - useRouteMeta("/blog/the-questions-your-agents-save-for-you"); - - return ( -
- - -
- - - - - Blog - - -
-

- The questions your agents save for you -

-

- Run several agents and each one will, sooner or later, need you to choose. Codecast - lets an agent write that choice up as a card, put it in one queue with every - other agent's, and wait. You answer the lot in one sitting, and each agent picks up - from your answer. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 6} min read -
-
- -

Asking without interrupting

-

- An agent that stops to ask you something has two bad options. It can ask in its own - chat and hope you look, so the question sits in one of six terminals while the agent - idles. Or it can guess, and you find the guess a day later, built on. Neither is what - you want when you are running several agents at once and your attention is the thing - in short supply. -

-

- Codecast gives the agent a third option. It writes the choice up as a decision: one - question, the options with what each one costs, and the reasoning you need to pick - without opening its session. The decision goes into your queue, the agent ends its - turn, and by default nothing more happens in that session until you answer. Your other agents - keep working. -

- -

What the card carries

-

- Here is a real one. On September 13th the agent that runs our Google Ads check had - been checking a campaign that was not serving for ten days. It had run out of useful - work, and rather than keep reporting the same three facts every day, it asked: -

- - - -

- The question is a question, not a status report. Under it, the page names the - session that asked and the person it was asked of. Then the context, written for - someone who was not there: why the campaign is dark, what the earlier checks found - (Google was serving the bare query "claude code" off one of our keywords), - why a daily check still has some value, and what the agent will do either way. You - can decide from this page without opening the session. If you would rather talk it - over first, Discuss opens a thread with that agent about this decision. -

-

- Below the context are the options, and each one says what happens if you pick it: -

- - - -

- The costs cut both ways. Checking every three days saves about a dozen empty runs, - and it means a restarted campaign could go unnoticed for up to three days instead of - one. Keeping it daily catches a restart within a day and spends about eighteen more - runs saying nothing new. Neither option is padding. Each one is something the agent - would actually do. -

-

- When the agent has a preference, it says so. Here is another decision from the same - month, about how to fix a delivery problem in codecast itself. The agent marked its - pick, and the card shows the mark as Suggested at the end of that row: -

- - - -

Answering in one sitting

-

- Every open decision from every agent lands in one queue, Questions in the - sidebar, with a count of how many are waiting on you. The order is deliberate. - Questions whose agent is stopped and still reachable come first, because answering - one restarts work right away. Questions whose session has gone away come next. - Advisory questions, where the agent named a default and kept working, come last. - Within each group the oldest comes first, so the queue does not reshuffle while you - work through it. -

-

- You can read the queue as a list or step through it one decision at a time. In the - one-at-a-time view the keyboard does the work: a number key picks that option and - moves on to the next decision, T lets you answer in your own words,{" "} - P passes a decision to someone else, X dismisses one that no - longer matters, and Esc takes you back to the inbox. When an option does - not fit, the answer you type goes to the agent as a message. The desktop app shows - the same queue, and the phone app has a Decisions screen with the same order: - tap an option and it moves to the next one. -

-

- The queue is not pictured here. On the day we wrote this it held five open - questions, all from other projects, and this blog only shows codecast's own - work. The decisions in this post were answered weeks ago, so they have left it. -

- -

What happens after you answer

-

- The decision also lives in the conversation that asked it. In the agent's - transcript the card sits inside the turn where it was posted, collapsed, with its - status and your answer in the header: -

- - - -

- Your answer reaches the agent as your next message, Check every 3 days while - dark, with a link back to the ask. The agent was parked on exactly that, so it - starts its next turn from the answer: -

- - - -

- It did what option 1 promised. The trigger's history shows the schedule moving - from every day to every three days seventeen seconds after the answer was recorded. - Then it took care of the part that is easy to lose: option 1 included - a promise to go back to daily the day the campaign served again, and a scheduled - agent does not remember a promise between runs. So it wrote the condition into the - task its runs report to, where the next run would read it: the first check that sees - the campaign serving again puts the schedule back to daily. -

-

- That is the loop. The agent asks once, with everything you need. You answer when you - are ready, alongside every other question waiting on you. The agent carries on from - your answer without you having to say more. -

- -

From a script

-

- Agents post decisions with a command, and the card is what that command produces. - You never need to type it, but if you script your own agents, this is how one asks: -

- - - cast decide "Should the daily check keep running every day?" -o "Check every 3 days :: what happens if chosen" -o "Keep it daily :: what happens instead" --context - - - -
- Codecast records every coding agent session you run, on any machine, and gives you - one place to see them, steer them and answer them. -
- -
- - - - - - -
- -

- All five screenshots are the codecast web app on 2026-10-15, of two real decisions - about codecast's own work, both asked and answered in September. Each is cropped - to the content column: the sidebar, the top bar and the right rail are outside every - crop. On the ads decision, the context's last paragraph and the agent's - status line under the card are cropped out because they carry the campaign's - dollar figures. On the second decision, the third option is cropped because it names - another project. The open queue is described from the app, not pictured, because it - held only other projects' questions that day. No decision was posted, answered - or edited for this post. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/the-task-your-agent-reports-to/page.tsx b/packages/web/app/(marketing)/blog/the-task-your-agent-reports-to/page.tsx deleted file mode 100644 index 1a41e30b62..0000000000 --- a/packages/web/app/(marketing)/blog/the-task-your-agent-reports-to/page.tsx +++ /dev/null @@ -1,193 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Terminal, Cmd, SOL, H2, P, Code, Screenshot } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Four genuine screenshots of the codecast web app on 2026-10-10: the task -// this blog's own trigger reports to, and the plan it belongs to. Each is -// cropped to the page's content column; the sidebar, the top bar and the -// right rail are outside every crop, and one strip of evidence thumbnails is -// trimmed because it previewed another team's page. - -export default function TaskYourAgentReportsToPost() { - const post = getPost("the-task-your-agent-reports-to"); - useRouteMeta("/blog/the-task-your-agent-reports-to"); - - return ( -
- - -
- - - - - Blog - - -
-

- The task your agent reports to -

-

- A chat thread is a bad place to keep track of work. Codecast gives every piece of - work a page of its own, where the agents working on it leave their notes, their - evidence and their status, and where a plan gathers the tasks that belong together. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 6} min read -
-
- -

Where does the work live?

-

- Ask three agents to do three things and you have three conversations. Ask them - again next week and you have six, and the question that matters, what is the - state of this piece of work, has no page you can open. It lives scattered across - transcripts, each of which knows only its own part. Codecast keeps the conversations, - and it also keeps something above them: a task, with a page, that every agent and - person working on the same thing reports into. -

-

- The example in this post is the task that runs this blog. Every three days a trigger - wakes an agent to write a post, and that agent's first move is to open this task - and read what the last run left there. Here is the page: -

- - - -

- Read it top to bottom. The chips say what it is and where it belongs: a task id, the - team, the project. The links under them go to the repository, the task's history - and its pull requests. The status track is the task's life, Backlog to Done or - Dropped, and the current step is lit. The Created row names who made it, and - here that is an agent: the growth pack's review session set up this ledger on - September 3rd. The Session box is the handle for getting work started: - Hand to an agent starts an agent on the task and binds its session to it, so - the page shows who is working on it without anyone typing a status update. -

- -

The notes the runs leave

-

- Below the description sits the part that makes a task more than a title. The - activity timeline holds every comment and every change, from people and from agents - alike, with the dates between them. Ours reads like a logbook kept by two agents over - five weeks: -

- - - -

- Two things to notice. First, who is writing. The review agent leaves standing - instructions (prefer the feature you can capture with genuine team usage), - and the writing agent leaves a run entry after each post: what shipped, what was - verified, what to avoid next time. Neither is a human, and a human can read the - whole history of the channel in one scroll. Second, the pills. A trigger named in a - comment renders as the trigger, with its state; a session named renders as the - session, with its title, and opens on a click. The notes are not prose about the - work, they are wired to it. -

- -

Plans: the tasks that belong together

-

- A task is one piece of work. A plan is the shape of several: a charter that says - what the whole thing is for, and the tasks that serve it. This task belongs to the - growth program plan, and the plan page opens with its charter: -

- - - -

- Scroll down and the plan shows its progress and its tasks. Seven here: a ledger like - the one above for each growth channel, plus two pieces of follow-up work the program - filed, each with its status and how many sessions have worked it: -

- - - -

- The tabs above the list are the other ways to look at the same plan. Board{" "} - lays the tasks out in columns, Graph draws them as a graph, and{" "} - Orchestration is where a plan is run by agents as a whole: a worker on each - task, reviewers, and the gates where a person approves before the next wave starts. -

- -

Why agents need this more than people do

-

- People remember what they were doing. An agent session does not outlive its - conversation, and the next one starts cold. A task page is the memory that survives - the session: the next agent reads the last entry, the standing instructions and the - evidence, and carries on as if it had been there. The same page is what a person - opens to find out where things stand without reading a transcript, and what a - teammate opens to pick up work someone else's agent started. One page, three - readers, no status meeting. -

-

- For people who script, and for the agents themselves, every part of this is also a - command. A run opens its task with cast task start, leaves its notes - with cast task comment and closes it with cast task done; - the page in the screenshots is what those commands write to: -

- - - cast task show ct-48701 - cast task comment ct-48701 "Run entry: what shipped, what was verified" -t progress - - -
- Codecast is where your team sees, steers, and remembers every coding agent session — any - agent, any machine. -
- -
- - - - - - -
- -

- All four screenshots are the codecast web app on 2026-10-10, taken by the run that - wrote this post, of the task and plan that run belongs to. Each is cropped to the - page's content column: the sidebar, the top bar and the right rail are outside - every crop, and the task page is trimmed above its evidence strip because one - thumbnail previewed another team's page. The two commands at the end are shown - as commands only. No capture was staged; the task and plan were in this state when - the run opened them. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/the-tree-at-the-end-of-every-turn/page.tsx b/packages/web/app/(marketing)/blog/the-tree-at-the-end-of-every-turn/page.tsx deleted file mode 100644 index af9ec31f4a..0000000000 --- a/packages/web/app/(marketing)/blog/the-tree-at-the-end-of-every-turn/page.tsx +++ /dev/null @@ -1,271 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, Terminal, Cmd, SOL, H2, P, Code } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Genuine output from the codecast checkout on 2026-10-07: `cast diff --turns` -// and `--turn` on a real session in this repository, and `git log` on the -// snapshot chain the daemon keeps. The turn list is trimmed; every omission is -// marked with an editorial "…". No command here changed anything. - -const TURNS = `64 turn snapshots (the working tree at each turn's end; shell and hand edits included) - - 1 15e2558bca 19 hours ago 700 files .codecast/check.toml, bun.lock, docs/SELF-HOSTING.md, +697 - #1 I want to build a systematized, deterministic, iterable graph like proc… - 2 ed5a07e711 19 hours ago 1 file packages/convex/convex/_generated/api.d.ts - turn with no ask on record - checkout shared with 4 other sessions; the changes may be theirs - 3 231a21b8eb 18 hours ago 5 files packages/playground/convex/_generated/api.d.ts, packages/web/components/SubagentFleetChip.tsx, packages/web/components/__tests__/publishedPageEmbed.test.tsx, +2 - sweep, no new turn -… 58 more rows … - 62 69aabfe9d3 12 hours ago 3 files packages/web/components/line/map/LineMap.tsx, packages/web/components/line/map/LineMapView.tsx, packages/web/components/line/map/lineMap.css - sweep, no new turn - checkout shared with 36 other sessions; the changes may be theirs - 63 1c29ec70ee 12 hours ago 6 files packages/web/components/line/map/LineMap.tsx, packages/web/components/line/trace/LineTracePage.tsx, packages/web/components/line/trace/TraceStory.tsx, +3 - sweep, no new turn - checkout shared with 37 other sessions; the changes may be theirs - 64 af34c25782 11 hours ago 11 files packages/convex/convex/agentTasks.cadence.test.ts, packages/convex/convex/assistant/tools/workspace.test.ts, packages/convex/convex/assistant/turns.test.ts, +8 - sweep, no new turn - checkout shared with 42 other sessions; the changes may be theirs - -cast diff --turn N shows what turn N changed; --turn last for the newest -`; - -const TURN_STAT = `turn 62 69aabfe9d3 -47505f457b → 69aabfe9d3, 3 files, taken 12 hours ago; checkout shared with 36 other sessions - - packages/web/components/line/map/LineMap.tsx | 67 ++++++++- - packages/web/components/line/map/LineMapView.tsx | 165 +++++++++++++++++++---- - packages/web/components/line/map/lineMap.css | 28 +++- - 3 files changed, 225 insertions(+), 35 deletions(-) -`; - -const TURN_PATCH = `diff --git a/packages/web/components/line/map/LineMap.tsx b/packages/web/components/line/map/LineMap.tsx -@@ -103,7 +103,8 @@ - const cut = new Set(); -- for (const b of layout.boxes.values()) if (Math.min(b.x + b.w, x1) - Math.max(b.x, x0) < b.w / 2) cut.add(b.id); -+ // Less than half in view either way: a loop's label over the stage, tied to a node out of sight below, hides with it. -+ for (const b of layout.boxes.values()) if (Math.min(b.x + b.w, x1) - Math.max(b.x, x0) < b.w / 2 || Math.min(b.y + b.h, y1) - Math.max(b.y, y0) < b.h / 2) cut.add(b.id); -… the rest of the patch … -`; - -const GIT_CHAIN = `af34c2578 12 hours ago parents: 033e34473 d85f2d78e -d85f2d78e 12 hours ago parents: 033e34473 1c29ec70e -1c29ec70e 12 hours ago parents: 033e34473 69aabfe9d -69aabfe9d 12 hours ago parents: 033e34473 47505f457 -`; - -const GIT_TRAILERS = `codecast wip snapshot - -codecast-branch: main -codecast-depth: 179 -codecast-taken-at: 2026-10-07T03:59:50.786Z -`; - -export default function TreeAtTheEndOfEveryTurnPost() { - const post = getPost("the-tree-at-the-end-of-every-turn"); - useRouteMeta("/blog/the-tree-at-the-end-of-every-turn"); - - return ( -
- - -
- - - - - Blog - - -
-

- The tree at the end of every turn -

-

- A transcript shows the edits an agent made with its editing tools. It never sees - what a shell command, a formatter or a person changed. Codecast now records the - whole working tree at the end of every turn, as git commits you can diff and - rewind to. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 6} min read -
-
- -

The edits the transcript cannot see

-

- Ask an agent what it changed and it will tell you what it changed with its editing - tools, because that is what its transcript holds. The transcript does not hold the - sed command it ran, the formatter the test suite invoked, the fixture a test - rewrote, or the line you fixed yourself in your editor while it worked. Those edits - reach the diff only when somebody commits, and by then the question of which turn - introduced the thing that broke is unanswerable from the record. -

-

- The working tree is the only ground truth. So codecast now records the tree - itself, at the end of every turn, as a git commit of the checkout. The idea is taken - whole from Zed's Delta, which records every edit from every source; codecast - gets the same history from git, for a fraction of the cost, and the objects never - leave your own repository. -

- -

Sixty-four snapshots of one session

-

- Here is a session from this repository, yesterday, that set out to produce a design - document and touched a lot of files on the way. Its turn history, trimmed to the first three - rows and the last three: -

- - - cast diff jx7e4fy --turns - {TURNS} - - -

- Each row is one snapshot: a short hash, when it was taken, how many files changed - since the previous one, and the first few of them. Under a row sits the ask that - opened the turn, when there was one; turn with no ask on record marks a - turn whose opening ask is not on record, and sweep, no new turn marks a snapshot - the daemon took on its five minute pass while nothing was finishing. The line that - matters most is the third one: checkout shared with 36 other sessions; the - changes may be theirs. A snapshot describes a checkout, not a session, and - this machine runs dozens of agents in one working tree. The listing says so rather - than pretending each row belongs to the session you asked about. -

- -

Any turn, as a diff

-

- A row is a question you can ask. What did turn 62 change? The answer is a diff - between that snapshot and the one before it, as a file list or as a patch: -

- - - cast diff jx7e4fy --turn 62 --stat - {TURN_STAT} - - - - cast diff jx7e4fy --turn 62 - {TURN_PATCH} - - -

- That is an ordinary unified diff, so everything you already do with diffs applies. - And because every turn has one, finding the turn that broke something is a walk, - not an archaeology: --turn last for the newest, then back one at a - time until the breakage disappears. -

- -

It is git underneath

-

- A snapshot is a dangling git commit of the working tree, made against a private - index the daemon keeps beside the repository's own, so your real index, HEAD - and branch are never touched and a file git ignores never enters one. The commits - chain. Here are the newest four on this checkout, with their parents: -

- - - git log --format='%h %ar parents: %p' -4 $(cut -d' ' -f1 .git/codecast/wip.head) - {GIT_CHAIN} - - -

- Read the parents column. The first parent of every snapshot is the same commit, - the HEAD the tree is based on, so any tool that expects a snapshot's parent to - be its base keeps working. The second parent is the previous snapshot, which is - what turns a pile of commits into a history: push the tip and the whole chain - travels with it. The commit message carries the facts a reader needs: -

- - - {GIT_TRAILERS} - - -

- Depth 179 on this checkout. The chain restarts every four hundred so that an - abandoned tail becomes unreachable and git's own garbage collection reclaims - it. -

- -

What it costs

-

- The reason this was not done before is that a snapshot of a large tree looked - expensive, and the measurement showed why: the cost was never the tree, it was - rebuilding the index from scratch and rehashing every tracked file. On this - repository, with 7,798 tracked files, that took under two seconds on a quiet - machine and three minutes under heavy load. A persistent index seeded from the - real one turns a pass into a stat walk: a fifth of a second at rest, twenty-four - seconds under the same load. Nothing runs on the hook path itself; the agent's - turn ends, the daemon is told, and the snapshot runs from a timer. Turns that end - within a second and a half of each other share one pass. If a pass ever takes more - than five seconds, turn snapshots pause on that checkout for ten minutes and the - five minute sweep carries on. Under load a snapshot can lag its turn by seconds, so - a rewind is accurate to the turn, not to the keystroke, and each row records how - long its pass took. -

- -

Rewind

-

- A history you can read is good. A history you can stand in is better. The - workspace command from the last post takes a session and a message line (the - numbering cast read uses, not a turn number) and gives you a fresh - checkout with the files exactly as they stood at that turn, on a new - branch at that snapshot's base commit, with the turn's edits left - uncommitted: -

- - - cast ws acquire before-the-map-change --rewind jx7e4fy@61 - - -

- Pair it with cast fork --at 61 and you have the conversation and the - files as they were, side by side with the present, and an agent that can carry on - from there. That is the whole point of recording the tree: not a log to admire, but - a place you can go back to. -

- -
- Codecast is where your team sees, steers, and remembers every coding agent session — any - agent, any machine. -
- -
- - - - - - -
- -

- The five terminal captures are genuine output from the codecast checkout on - 2026-10-07: cast diff --turns and --turn on a real session - in this repository, and git log on the snapshot chain the daemon keeps. - The turn list keeps six of sixty-four rows, the patch keeps its first hunk, and the - git log drops nothing; each omission is marked …. The rewind command is - shown as a command only and was not run: the previous post measured an acquire on - this machine at twenty minutes. The timings in the cost section are from the - feature's own design document, measured on 2026-10-06 on this repository. No - screenshot: the feature lives in the terminal and in git. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/blog/undo-with-a-history/page.tsx b/packages/web/app/(marketing)/blog/undo-with-a-history/page.tsx deleted file mode 100644 index 84b0115d2d..0000000000 --- a/packages/web/app/(marketing)/blog/undo-with-a-history/page.tsx +++ /dev/null @@ -1,226 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { BlogNav, SOL, H2, P, Code, CardShot } from "../blogChrome"; -import { useRouteMeta } from "../../pageMeta"; -import { getPost } from "../posts"; - -// Five genuine screenshots of the codecast web app (codecast.sh) in Chrome on -// 2026-10-21. The three changes in them were made for this post, from the -// command palette, on the session that wrote it (jx7d5m0, then titled "CMO -// content pipeline run"), and all three were taken back in the same window; -// the store read back unpinned, the original title and not a favorite -// afterwards. Each image is cropped to the undo card or to one toast. The -// sessions list behind them belongs to another workspace and is outside every -// crop. Nothing was composited or retouched. - -const DIR = "/blog/undo-with-a-history"; - -export default function UndoWithAHistoryPost() { - const post = getPost("undo-with-a-history"); - useRouteMeta("/blog/undo-with-a-history"); - - return ( -
- - -
- - - - - Blog - - -
-

- Undo, with a history you can see -

-

- Running several agents means a lot of small moves: pin this one, file that one as - done, rename a third, stash a fourth. In Codecast every one of them can be taken - back with ⌘Z, and ⌘⌥Z opens the list of what you did in this window, with a button - to go back to any point in it. -

-
- {post?.author ?? "the codecast team"} - · - - · - {post?.readingMinutes ?? 5} min read -
-
- -

Three changes

-

- The session that wrote this post made three changes to itself before writing a - word, in a Codecast window in Chrome, all from the command palette (⌘K). It pinned - itself, renamed itself from CMO content pipeline run to Blog post on - undo, and added itself to favorites. Each change happened at once, and the - pin left a small toast in the corner: -

- - - -

- That toast is the quickest way back, and it is tied to the change it announces: - if you have made other changes since, its Undo still takes back only the pin and - leaves the rest. For anything further back there is the history. ⌘⌥Z (Ctrl+Alt+Z - on Windows and Linux) opens it in the same corner: -

- - - -

- Each row names the change and the thing it changed, in words you would use - yourself. The line marked NOW is where you are; everything below it is - done, and the dim Start row at the bottom is the state before any of it. - The card takes the keyboard while it is open: the arrows move between rows, the - right arrow unfolds one to show what it changed, O opens the session - or task the row is about, and Esc closes it. -

- -

Back to here

-

- Moving the selection down to the rename and unfolding it shows the change in full. - The button on the row now reads Back 2, because going back to just before - the rename takes two steps, the favorite and then the rename: -

- - - -

- Enter pressed the button. The title went back to CMO content pipeline run{" "} - and the session left favorites, and the card kept both rows: -

- - - -

- Undone rows move above the line and stay there, marked undone just now. - Selecting one offers Forward to here, and ⌘⇧Z steps forward one at a - time, so going back too far costs nothing. Making a new change after an undo sets - the undone rows aside, the way an editor drops its redo stack, and the card says - so in one struck line under the change that replaced them. -

- -

One key

-

- Most of the time you never open the card. With it closed, one ⌘Z took back the - last change left, the pin: -

- - - -

- The toast says what was undone, and its History button appears when - there is more history than that one step. Holding ⌘ for a moment after a ⌘Z also - opens the card as a peek that follows each further Z, so you can watch the steps go - by and let go when you reach the right one. Holding ⌘Z down undoes once, not once - per key repeat, so a long press never empties the history. -

-

- After that one key the session was back exactly as it started: unpinned, its old - title, not a favorite. Every undo is a real change, sent to the server like the - original, so the session reads the same in your other windows, on the desktop app - and on your phone. -

- -

What it takes back, and what it leaves

-

- Undo covers the moves you make on your work. On sessions that means pin, favorite, - rename, label, snooze, defer, filing as done, stash and kill; undoing a kill brings - the card back, but the agent stays stopped until you restart it. On tasks, plans - and docs it covers edits to their fields, and archiving a doc. It also covers - pausing a trigger, resolving a comment and changing who can see a session. -

-

- It leaves alone what cannot honestly be unsaid: a message you sent, something you - created, something you deleted, your settings, and switching a session's agent - or model. Text boxes keep their own undo, so ⌘Z in a composer with words in it - edits the words. -

-

- Two rules keep it from doing damage. First, it never writes over a later change. - If a teammate or an agent has changed the same field since, that row is skipped, - and the toast says how much it could take back ("2 of 3; 1 changed - since"). Second, an undo that would let more people see a session never - happens from a bare ⌘Z; you take it back from the toast or the card, where you can - see what it is. -

- -

Where it works

-

- The history belongs to the window you made the changes in, and it lives in that - window's memory: a reload starts it fresh, and a second window has its own. - ⌘Z reaches the last five minutes, which is what the card's subtitle says. Older - rows stay in the card, and you can still take most of them back by choosing them there, - because you can see exactly what you are undoing. It works the same in the - desktop app, where the Edit menu's Undo and Redo reach it whenever the cursor - is outside a text box. The phone app does not have it yet. -

-

- To find the card without the shortcut, search the command palette for{" "} - Undo history. -

- -
- Codecast records every coding agent session you run, on any machine, and gives you - one place to see them, steer them and answer them, on your own or with your team. -
- -
- - - - - - -
- -

- All five screenshots are the Codecast web app at codecast.sh in Chrome on - 2026-10-21, shown at their own size. The three changes were made for this post, on - the session that wrote it, and all three were taken back in the same window, so - nothing changed for good. Each image is cropped to the undo card or to a single - toast; the sessions list behind them, which belongs to another workspace, is - outside every crop. Nothing was composited or retouched. The held peek, the desktop - app and the conflict message are described, not pictured. -

-
-
- ); -} diff --git a/packages/web/app/(marketing)/documentation/guides/content/decisions.md b/packages/web/app/(marketing)/documentation/guides/content/decisions.md index 68481d9948..1c46ad1e53 100644 --- a/packages/web/app/(marketing)/documentation/guides/content/decisions.md +++ b/packages/web/app/(marketing)/documentation/guides/content/decisions.md @@ -22,22 +22,14 @@ Agents ask on their own once it is on. You can also tell them when to: ![The Decisions page: a list of open questions from Acme's sessions, with Mine selected and counts on each tab](/documentation/decisions/decisions-page.webp "The Decisions page, with three questions waiting on you.") -Click a row to open the decision's own page: the question, the agent's full reasoning or the report it attached, a page per option when the agent made one, a discussion, and the answer controls. The arrows at the top, or the arrow keys, flip to the next and previous decision. - -## Answer one at a time - -**One at a time** walks the queue as full cards, each on the asking session's pane, so you can clear it in one sitting. - -![One decision shown full screen, with its options numbered and the key hints for skip, dismiss and open the session](/documentation/decisions/one-at-a-time.webp "Working through the queue one decision at a time.") +Click a row, or a decision under **Decisions** at the top of the inbox, to open the decision's own page beside the list: the question, the agent's full reasoning or the report it attached, a page per option when the agent made one, a discussion, and the answer controls. After you answer, the page stays put and shows what you chose, with **Next decision** at the bottom when you are ready to move on. The arrows at the top, or the arrow keys, flip to the next and previous decision. | Key | What it does | |-----|--------------| | `1` to `9` | Answer with that option | | `t` | **Or answer in your own words**: your text goes to the agent as a message | -| `s` | Skip for now | | `x` | Dismiss. The question leaves the queue and the agent is not told | -| `o` | Open the session | -| `esc` | Leave the queue | +| `←` `→` | Previous and next decision | The order follows a rule. Questions holding an agent up come first, then questions from sessions that have stopped, then questions the agent is already working around. Inside each group the oldest comes first. Each card shows its age in time and in messages since it was asked, so a question the thread has moved past is easy to spot. diff --git a/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx b/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx index 014903044d..884b662bab 100644 --- a/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx +++ b/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx @@ -27,6 +27,7 @@ import { CodeMenuItem, CodeShareMenu } from "../../../../../components/menus/Cod import { copyText } from "../../../../../lib/copyText"; import { CommitRail } from "../../../../../components/repo/CommitRail"; import { RepoPageShell } from "../../../../../components/repo/RepoPageShell"; +import { useLocalEditAction } from "../../../../../hooks/useLocalEdit"; import { RepoWindowControl } from "../../../../../components/repo/RepoWindowControl"; import { useRepoFamily } from "../../../../../components/repo/useRepoFamily"; import { FileDiffLayout, type DiffFile, type FileLineThreads } from "../../../../../components/FileDiffLayout"; @@ -35,6 +36,7 @@ import { useFollowScroll } from "../../../../../hooks/useFollowSurface"; import { LoadingSkeleton } from "../../../../../components/LoadingSkeleton"; import { PRLineThread } from "../../../../../components/pr/PRThread"; import { CommitLinks } from "../../../../../components/repo/CommitLinks"; +import { CiMark } from "../../../../../components/ci/CiMark"; import { Button } from "../../../../../components/ui/button"; import { useCodeComments, useSyncRefCodeComments } from "../../../../../hooks/useSyncCodeComments"; import { useAttributedSession, useLineComments } from "../../../../../hooks/useLineComments"; @@ -204,6 +206,7 @@ function CommitHeader({ style={{ ["--d" as string]: "120ms" }} > + repoBlobHref(repository, sha, path, family), [repository, sha, family], ); + // Each file's "Edit": the file in this machine's checkout, with the + // editor's diff against the commit's parent when the checkout sits on this + // commit (anywhere else that diff would mix in other commits' changes). + const editAction = useLocalEditAction(repository, "", (c) => + c.head && c.head === commit?.sha ? { ref: `${commit.sha}^`, label: "Parent" } : null, + ); const jumpToThread = useCallback( (path: string, line?: number) => goTo(path, line ? { side: "RIGHT", lineNumber: line } : undefined), [goTo], @@ -574,7 +583,7 @@ function CommitContent({ )} - + )} diff --git a/packages/web/app/tasks/[id]/page.tsx b/packages/web/app/tasks/[id]/page.tsx index 7ddf45a341..83826760b5 100644 --- a/packages/web/app/tasks/[id]/page.tsx +++ b/packages/web/app/tasks/[id]/page.tsx @@ -77,6 +77,7 @@ import { useNavClose } from "../../../hooks/useNavTrail"; import { useIsModernStyle } from "../../../hooks/useVisualStyle"; import { TaskHeadIdRow, TaskHeadTitle, TaskModernHeader, TaskParentLine, type TaskTitleEdit } from "./TaskHead"; import { modernPill, modernPillShape } from "../../../components/ui/modernLook"; +import { FilePathContext, useFolderPathContext } from "../../../lib/filePathLinks"; const PRIORITY_OPTIONS = [ { key: "urgent", icon: AlertTriangle, label: "Urgent", color: "text-sol-red" }, @@ -287,6 +288,7 @@ export function TaskDetailContent({ taskId, variant = "page", onClose, onOpen, c // writes the thread to the store, and a task opened before paints it from // the cache. const comments = useTaskComments(data?._id); + const taskFileCtx = useFolderPathContext(data?.project_path); const taskTeamId = data?.team_id as string | undefined; // A blocking question outranks the description: nothing in the body can be // acted on until it is answered, so the body folds and the card comes up @@ -818,7 +820,10 @@ export function TaskDetailContent({ taskId, variant = "page", onClose, onOpen, c )} - + {/* A path a comment cites (`lib/x.ts:38`) is relative to the task's project. */} + + + {/* Comment input */} diff --git a/packages/web/components/InlineDiff.tsx b/packages/web/components/InlineDiff.tsx index a9ef10ebd6..c23a1e4f50 100644 --- a/packages/web/components/InlineDiff.tsx +++ b/packages/web/components/InlineDiff.tsx @@ -1,7 +1,9 @@ import { useContext, useMemo, useState, memo } from "react"; import type { ReactNode } from "react"; import { getFileStatus } from "../lib/patchParser"; -import { DIFF_FENCE, parseCastDiff, type DiffFileSection } from "../lib/castDiff"; +import { DIFF_FENCE, firstChangedNewLine, parseCastDiff, type DiffFileSection } from "../lib/castDiff"; +import { FilePathContext } from "../lib/filePathLinks"; +import { OpenInEditorButton } from "./OpenInEditorButton"; import { DiffView } from "./DiffView"; import { CodeBlock } from "./CodeBlock"; import { MessageIdentity } from "../lib/conversationBlockContexts"; @@ -86,6 +88,9 @@ function DiffFileCard({ identity: { conversationId: string; messageId: string; live?: boolean } | null; }) { const [expanded, setExpanded] = useState(false); + // A git diff names files from the checkout's root, not the session's cwd. + const fileCtx = useContext(FilePathContext); + const editCtx = useMemo(() => (fileCtx?.gitRoot ? { ...fileCtx, base: fileCtx.gitRoot } : fileCtx), [fileCtx]); const statusMeta = getFileStatus(file.status); const language = languageFromPath(file.path); const commentContext = identity && !identity.live @@ -104,6 +109,7 @@ function DiffFileCard({ {file.path} + {editCtx && file.status !== "deleted" && } {file.additions > 0 && +{file.additions}} {file.deletions > 0 && −{file.deletions}} {file.fullContext && ( diff --git a/packages/web/components/OpenInEditorButton.tsx b/packages/web/components/OpenInEditorButton.tsx index 111e7a7aa1..476690627a 100644 --- a/packages/web/components/OpenInEditorButton.tsx +++ b/packages/web/components/OpenInEditorButton.tsx @@ -22,6 +22,7 @@ import { cn } from "../lib/utils"; export function OpenInEditorButton({ target, diffAgainst, + peek, label, editorOnly, className, @@ -29,6 +30,8 @@ export function OpenInEditorButton({ /** `ctx` resolves a relative path; the conversation's own when absent. */ target: EditorTarget; diffAgainst?: OpenInEditorOptions["diffAgainst"]; + /** Peek the change at the landed line once the file shows (an edit card). */ + peek?: boolean; /** Shown beside the icon; icon only when absent. */ label?: string; /** Not drawn when the editor cannot reach the file (a surface that already @@ -59,7 +62,7 @@ export function OpenInEditorButton({ aria-label={label ? undefined : reachable ? "Open in editor" : "Open in session changes"} onClick={(e) => { e.stopPropagation(); - openConversationPath({ ...target, ctx }, { fromLeaf, diffAgainst }); + openConversationPath({ ...target, ctx }, { fromLeaf, diffAgainst, peek }); }} className={cn( "inline-flex items-center gap-1 shrink-0 rounded px-0.5 text-sol-text-dim hover:text-sol-text hover:bg-sol-bg-alt transition-colors", diff --git a/packages/web/components/PaletteRows.tsx b/packages/web/components/PaletteRows.tsx index 6e14b1cd7d..a7f4401f6b 100644 --- a/packages/web/components/PaletteRows.tsx +++ b/packages/web/components/PaletteRows.tsx @@ -24,6 +24,7 @@ import { DeviceIcon, deviceDisplayName, type Device } from "./DeviceBadge"; import { type SessionStanding } from "../lib/instantSessionSearch"; import { SESSION_STATUS, statusOfStanding, type StatusRow } from "../lib/sessionStatus"; import { SessionStatusMark } from "./inbox/SessionStatusMark"; +import { paletteNamedValue } from "../lib/paletteActions"; // Presentational rows of the Cmd+K palette. CommandPalette owns the data and // the select handlers; these draw a row from plain props, so the marketing @@ -345,7 +346,7 @@ export function PaletteTaskRow({ task, status, onSelect, valuePrefix = "__entity return ( diff --git a/packages/web/components/PlanDetailPanel.tsx b/packages/web/components/PlanDetailPanel.tsx index 27fa10c495..abc2c375d1 100644 --- a/packages/web/components/PlanDetailPanel.tsx +++ b/packages/web/components/PlanDetailPanel.tsx @@ -63,6 +63,7 @@ import { useRunCost } from "./consequential/useRunCost"; import { workflowAgentSteps, workflowRunLedger, workflowSteps } from "./work/startLedgers"; import { useWorkflow } from "../hooks/useSyncWorkflows"; import { teamMembersOf } from "../lib/activeTeam"; +import { FilePathContext, useFolderPathContext } from "../lib/filePathLinks"; const api = _api as any; @@ -220,8 +221,10 @@ export function DriveRoundIndicator({ driveState }: { driveState: { current_roun ); } -function CollapsibleDoc({ content }: { content: string }) { +function CollapsibleDoc({ content, projectPath }: { content: string; projectPath?: string }) { const [expanded, setExpanded] = useState(false); + // A path the doc cites (`lib/x.ts:38`) is relative to the plan's project. + const fileCtx = useFolderPathContext(projectPath); const MAX_HEIGHT = 200; return ( @@ -234,7 +237,9 @@ function CollapsibleDoc({ content }: { content: string }) { prose-code:text-sol-cyan prose-code:bg-sol-bg-highlight prose-code:px-1 prose-code:rounded prose-code:text-xs prose-strong:text-sol-text prose-a:text-sol-cyan [&_pre]:overflow-x-auto [&_pre]:max-w-full"> - {content} + + {content} + + + + )} + {segments.map((seg, i) => + i < hide ? null : ( + // The nearest folder alone may truncate, when even it has no room. + 0 || segments.length === 1) ? "min-w-0" : "shrink-0"}`}> + + + + ), + )} + + {(n) => ( + <> + {segments.slice(0, n).map((seg, i) => ( + + {seg} + + ))} + + )} + + + ); +} + export const CodeFileBar = memo(function CodeFileBar({ path, actions }: { path: string; actions?: ReactNode }) { const canReveal = useVaultStore((s) => !!s.endpoint && !s.isRemote); const group = useCodeGroup(); + const navRef = useRef(null); const symbolsRef = useRef(null); useWatchEffect(() => { const el = symbolsRef.current; if (!el || !group) return; return bindGroupCrumbs(group.key, el); }, [group?.key]); - const segments = path.split("/"); - const name = segments[segments.length - 1]; + const name = path.slice(path.lastIndexOf("/") + 1); return ( -
- diff --git a/packages/web/components/code/CodeFileView.tsx b/packages/web/components/code/CodeFileView.tsx index cf6b1604ae..5fb8f25d5d 100644 --- a/packages/web/components/code/CodeFileView.tsx +++ b/packages/web/components/code/CodeFileView.tsx @@ -4,75 +4,151 @@ // bundle. Above the editor sits the strip for the one state that needs a // person: disk and the buffer disagree. -import { useMemo, useRef, useState } from "react"; +import { useMemo, useRef, useState, type ReactNode } from "react"; +import type { EditorView } from "@codemirror/view"; import { useWatchEffect } from "../../hooks/useWatchEffect"; import { useVaultStore } from "../../store/vaultStore"; import { useCodeStore, type CodeConflict } from "../../store/codeStore"; -import { bufferKey, codeBuffers } from "../../lib/code/buffers"; +import { bufferKey, codeBuffers, currentState, diskLockField, type CodeBuffer } from "../../lib/code/buffers"; +import { registerCodeCommands, runCodeCommand, type CodeCommandContext, type CodeCommandId } from "../../lib/code/commands"; +import { featureContext, focusedEditorView } from "../../lib/code/features"; +import { formatAcceleratorParts } from "../../shortcuts"; +import { KeyCap } from "../KeyCap"; import { parseCursorTarget, type EditorHost } from "../../lib/code/editorHost"; -import { diskRemoved, mergeWithDisk, recreateFile, saveBuffer, takeDisk } from "../../lib/code/fileSync"; -import { loadMergeKit } from "../../lib/code/merge"; +import { diskRemoved, keepMine, mergeWithDisk, overwriteLocked, recreateFile, saveBuffer, takeDisk } from "../../lib/code/fileSync"; +import { loadMergeKit, stepMerge } from "../../lib/code/merge"; import { loadHotExit } from "../../lib/code/hotExit"; import { useIsNewFile } from "../../lib/code/newFiles"; import { CodeEditor } from "./CodeEditor"; import { BlameCardHost } from "./blame/BlameCardHost"; import { modernButton } from "../ui/modernLook"; import { ConflictWriter } from "./agent/ConflictWriter"; +import { DaemonReconnecting } from "../vault/FileUnavailable"; +import { useStalled } from "../../hooks/useStalled"; +import { LoadingBar } from "../ui/LoadingBar"; +import { Lock, WifiOff } from "lucide-react"; +import { OverwriteReview } from "./OverwriteReview"; const stripButton = modernButton({ variant: "outline", size: "xs" }); -function ConflictStrip({ conflict, bufferId, hostRef }: { conflict: CodeConflict; bufferId: string; hostRef: React.MutableRefObject }) { - const buffer = () => codeBuffers.get(bufferId); - const run = (fn: (b: NonNullable>) => unknown) => () => { - const b = buffer(); +// The strip's verbs as commands, so the palette and the keys reach them with +// focus in the editor: each acts on the buffer of the editor the person was +// in (contract 9) and declines when that buffer has no change to settle. +registerCodeCommands( + Object.fromEntries( + ( + [ + ["merge.withDisk", ["stale"], (b) => b.stale && mergeWithDisk(b, b.stale)], + ["merge.takeDisk", ["stale", "merge"], (b) => takeDisk(b)], + ["merge.keepMine", ["stale", "merge"], (b) => keepMine(b)], + ["merge.next", ["merge"], (_b, view) => loadMergeKit().then((kit) => stepMerge(kit, view, 1))], + ["merge.prev", ["merge"], (_b, view) => loadMergeKit().then((kit) => stepMerge(kit, view, -1))], + ] as [CodeCommandId, CodeConflict["kind"][], (b: CodeBuffer, view: EditorView) => unknown][] + ).map(([id, kinds, verb]) => [ + id, + (_args: unknown, ctx: CodeCommandContext) => { + const view = ctx.view ?? focusedEditorView(); + const at = view?.state.facet(featureContext); + if (!view || !at) return false; + const key = bufferKey(at.vaultId, at.path); + const b = codeBuffers.get(key); + const kind = useCodeStore.getState().conflicts[key]?.kind; + if (!b || !kind || !kinds.includes(kind)) return false; + void verb(b, view); + view.focus(); + }, + ]), + ), +); + +/** A strip button that runs its command, and shows the key when it has one. */ +function StripAction({ id, label, keys, name, view }: { id: CodeCommandId; label: ReactNode; keys?: string; name?: string; view: () => EditorView | undefined }) { + const parts = keys ? formatAcceleratorParts(keys) : null; + return ( + + ); +} + +const STRIP_TITLE: Record = { + error: "Save failed", + deleted: "Deleted on disk", + stale: "Changed on disk", + merge: "Changed on disk", + readonly: "Read-only on disk", + offline: "Not saved", +}; + +function ConflictStrip({ conflict, bufferId, hostRef, onOverwrite }: { conflict: CodeConflict; bufferId: string; hostRef: React.MutableRefObject; onOverwrite: () => void }) { + const run = (fn: (b: NonNullable>) => unknown) => () => { + const b = codeBuffers.get(bufferId); if (b) void fn(b); hostRef.current?.view.focus(); }; - const step = (dir: 1 | -1) => () => { - const view = hostRef.current?.view; - if (!view) return; - void loadMergeKit().then((kit) => (dir === 1 ? kit.goToNextChunk : kit.goToPreviousChunk)(view)); - view.focus(); - }; + const view = () => hostRef.current?.view; const alarm = conflict.kind === "error" || conflict.kind === "deleted"; const tone = alarm ? "border-sol-red/40 bg-sol-red/10" : "border-sol-yellow/40 bg-sol-yellow/10"; - const title = { error: "Save failed", deleted: "Deleted on disk", stale: "Changed on disk", merge: "Changed on disk" }[conflict.kind]; return ( -
- {title} +
+ {conflict.kind === "readonly" && } + {conflict.kind === "offline" && } + {STRIP_TITLE[conflict.kind]} + {conflict.kind === "readonly" && {conflict.mode}} + {conflict.kind === "offline" && ( + + + Reconnecting + + )} {(conflict.kind === "stale" || conflict.kind === "merge") && } {conflict.kind === "merge" && ( - - {conflict.remaining} {conflict.remaining === 1 ? "difference" : "differences"} - {conflict.conflicts > 0 && ` · ${conflict.conflicts} ${conflict.conflicts === 1 ? "conflict" : "conflicts"}`} + + {conflict.conflicts > 0 && ( + + {conflict.conflicts} {conflict.conflicts === 1 ? "conflict" : "conflicts"} + + )} + {conflict.conflicts > 0 && ·} + + {conflict.remaining} {conflict.remaining === 1 ? "difference" : "differences"} + + + )} + {conflict.kind === "error" && ( + + {conflict.message} )} - {conflict.kind === "error" && {conflict.message}} {conflict.kind === "merge" && ( <> - - + 0 ? "Previous conflict" : "Previous difference"} /> + 0 ? "Next conflict" : "Next difference"} /> )} - {conflict.kind === "stale" && ( - )} - {(conflict.kind === "stale" || conflict.kind === "merge") && ( - )} - {conflict.kind === "deleted" ? ( - - ) : ( + {(conflict.kind === "merge" || conflict.kind === "error") && ( )} @@ -121,15 +197,66 @@ export function CodeFileView({ path, line, missing = false, newFile: noFile = fa }, [waiting, key]); const preview = waiting && held?.key === key ? held.text : null; + // A cached boot reads the file once the daemon answers. When that takes + // longer than a beat, the wait turns into the read-failure state, with a + // Retry that reconnects, rather than an empty editor with no end. + const reconnecting = useVaultStore((s) => s.connection === "cached" && !s.endpoint && !s.isRemote); + const [stalled, retryStalled] = useStalled(waiting && preview === null && reconnecting, key); + + // Writing a file its mode refuses asks first: the strip's Overwrite, and + // vim's `:w!` (file.overwrite) from this editor. On a writable file `:w!` is + // a plain save. + const [overwriting, setOverwriting] = useState(null); + const askOverwrite = () => { + const b = codeBuffers.get(key); + if (!b) return; + const mode = conflict?.kind === "readonly" ? conflict.mode : currentState(b).field(diskLockField); + if (mode) setOverwriting(mode); + else void saveBuffer(b); + }; + const askRef = useRef(askOverwrite); + askRef.current = askOverwrite; + useWatchEffect(() => { + if (!key) return; + return registerCodeCommands({ + "file.overwrite": (_args, ctx) => { + const view = ctx.view ?? focusedEditorView(); + if (!view || view !== hostRef.current?.view) return false; + askRef.current(); + }, + }); + }, [key]); + if (!vaultId) return null; // While the file's text is on its way the editor stays mounted, empty, so // opening a file never rebuilds the view or jumps the layout. return (
- {conflict && } + {conflict && } + {overwriting && ( + { + setOverwriting(null); + hostRef.current?.view.focus(); + }} + onConfirm={() => { + setOverwriting(null); + const b = codeBuffers.get(key); + if (b) void overwriteLocked(b); + hostRef.current?.view.focus(); + }} + /> + )}
{waiting && !preview && ( -
Loading…
+ + )} + {stalled && ( +
+ +
)} >) { test("a cached boot waits for the daemon instead of claiming the read failed", async () => { setVault({ endpoint: null, isRemote: false, connection: "cached" }); const host = await render(); - expect(host.textContent).not.toContain("Couldn't read this file."); + expect(host.textContent).not.toContain("Couldn't read"); expect(host.querySelector(".cm-editor")).not.toBeNull(); expect(host.textContent).toContain("Loading"); }); @@ -53,7 +53,7 @@ test("a cached boot waits for the daemon instead of claiming the read failed", a test("no daemon at all says the file could not be read", async () => { setVault({ endpoint: null, isRemote: false, connection: "no-daemon" }); const host = await render(); - expect(host.textContent).toContain("Couldn't read this file."); + expect(host.textContent).toContain("Couldn't read"); }); test("a cached boot shows unsaved text held for hot exit, read-only, then loads the file", async () => { @@ -219,7 +219,7 @@ test("a clean file removed and restored on disk comes back in its editor", async await settle(); }); // The editor stays, saying so, with a way to write the file back. - expect(host.textContent).not.toContain("This file does not exist."); + expect(host.textContent).not.toContain("Not on disk"); expect(host.textContent).toContain("Deleted on disk"); expect(host.textContent).toContain("Recreate"); await act(async () => { @@ -240,14 +240,14 @@ test("a clean file removed and restored on disk comes back in its editor", async test("while discovery runs it waits for the read instead", async () => { setVault({ endpoint: null, isRemote: false, connection: "discovering" }); const host = await render(); - expect(host.textContent).not.toContain("Couldn't read this file."); + expect(host.textContent).not.toContain("Couldn't read"); }); test("a remote vault without the file's text says it could not be read", async () => { // No Convex client: the remote read returns without a body. setVault({ endpoint: null, isRemote: true, connection: "connected" }); const host = await render(); - expect(host.textContent).toContain("Couldn't read this file."); + expect(host.textContent).toContain("Couldn't read"); }); test("unsaved edits outlive their file leaving disk and see it come back", async () => { @@ -288,3 +288,65 @@ test("unsaved edits outlive their file leaving disk and see it come back", async expect(host.textContent).toContain("Changed on disk"); expect(view.state.doc.toString()).toBe(`// mine\n${text}`); }); + +test("a failed read names why, keeps the file bar, and Retry reads again", async () => { + const { EditorView } = await import("@codemirror/view"); + const file = "src/denied.ts"; + const text = "export const d = 1;\n"; + const realFetch = globalThis.fetch; + let reads = 0; + globalThis.fetch = (async (url: string) => { + if (!String(url).includes("/vault/file")) return new Response("{}", { status: 404 }); + if (reads++ === 0) return new Response("no", { status: 403 }); + return new Response(text, { status: 200, headers: { "X-Vault-Mtime": "1", "X-Vault-Size": String(text.length), ETag: "e1" } }); + }) as any; + try { + setVault({ endpoint: { port: 1, token: "t" } as any, isRemote: false, connection: "connected", files: { [file]: { path: file, mtime: 1, size: text.length } } as any }); + const host = await render(file); + for (let i = 0; i < 20 && !host.textContent?.includes("Couldn't read"); i++) await act(() => settle()); + expect(host.textContent).toContain("Couldn't read"); + expect(host.textContent).toContain("No permission"); + // The breadcrumbs row stays: the file's name is still on screen. + expect(host.querySelector("nav")?.textContent).toContain("denied.ts"); + const retry = [...host.querySelectorAll("button")].find((b) => b.textContent?.includes("Retry"))!; + await act(async () => { + retry.click(); + await settle(); + }); + for (let i = 0; i < 20 && !host.querySelector(".cm-editor"); i++) await act(() => settle()); + const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!; + for (let i = 0; i < 20 && view.state.doc.toString() !== text; i++) await act(() => settle()); + expect(view.state.doc.toString()).toBe(text); + expect(reads).toBe(2); + } finally { + globalThis.fetch = realFetch; + } +}); + +test("a cached boot that waits past a beat offers Retry, which reconnects", async () => { + setVault({ endpoint: null, isRemote: false, connection: "cached", files: { "src/slow.ts": { path: "src/slow.ts", mtime: 1, size: 9 } } as any }); + let reconnects = 0; + const realReconnect = useVaultStore.getState().reconnect; + useVaultStore.setState({ reconnect: async () => void reconnects++ }); + try { + const host = await render("src/slow.ts"); + expect(host.querySelector('[role="progressbar"]')).not.toBeNull(); + expect(host.textContent).not.toContain("Couldn't read"); + await act(() => new Promise((r) => setTimeout(r, 4100))); + expect(host.textContent).toContain("Daemon reconnecting"); + const retry = [...host.querySelectorAll("button")].find((b) => b.textContent?.includes("Retry"))!; + await act(async () => retry.click()); + expect(reconnects).toBe(1); + expect(host.textContent).not.toContain("Daemon reconnecting"); + } finally { + useVaultStore.setState({ reconnect: realReconnect }); + } +}, 10000); + +test("a text file past the editor's limit says its size and the limit", async () => { + setVault({ endpoint: null, isRemote: false, connection: "connected", files: { "big.log": { path: "big.log", mtime: 1, size: 40 * 1024 * 1024 } } as any }); + const host = await render("big.log"); + expect(host.textContent).toContain("Too large"); + expect(host.textContent).toContain("40 MB · limit"); + expect(host.querySelector("nav")?.textContent).toContain("big.log"); +}); diff --git a/packages/web/components/code/agent/AgentLayer.tsx b/packages/web/components/code/agent/AgentLayer.tsx index 5c9cebf95e..dfc53b5ad3 100644 --- a/packages/web/components/code/agent/AgentLayer.tsx +++ b/packages/web/components/code/agent/AgentLayer.tsx @@ -15,6 +15,8 @@ import { Link2Off } from "lucide-react"; import { useInboxStore } from "../../../store/inboxStore"; import { useWatchEffect } from "../../../hooks/useWatchEffect"; import { useAgentStore } from "../../../lib/code/agent/agentStore"; +import { openBeside, sessionPanePath } from "../../../lib/stage"; +import { openConversationHere } from "../../../lib/code/blame/actions"; import { computeVaultAgentState, vaultAgentSig, vaultMachineOf } from "../../../lib/code/agent/live"; import { InlineInstruction } from "./InlineInstruction"; import { SessionMark } from "./SessionMark"; @@ -30,6 +32,7 @@ function useAgentLinking(vaultId: string, root: string | null): void { useAgentStore.getState().setLink(vaultId, { sessionId: null, source: "none" }); return; } + useAgentStore.getState().restoreOverride(vaultId); let lastSig = ""; let lastOverride: unknown = undefined; const recompute = (force: boolean) => { @@ -62,38 +65,61 @@ function useAgentLinking(vaultId: string, root: string | null): void { }, [vaultId, root]); } -/** The status bar chip: the linked session, and how many quotes wait in its - * composer. A press opens the picker. */ +/** Open the linked session's composer beside the editor, where its queued + * quotes wait in the tray. A pane that opens takes focus into its composer; + * one already beside is focused and its composer focused after. Where the + * stage has no room the conversation opens in the main view. */ +function openComposerBeside(sessionId: string): void { + if (!openBeside(sessionPanePath(sessionId))) { + openConversationHere(sessionId); + return; + } + requestAnimationFrame(() => document.querySelector(".stage-cell--focused [data-chat-input]")?.focus()); +} + +/** The status bar chip: the linked session, drawn dim while it is only the + * folder's latest (no pick, nothing beside), and how many quotes wait in its + * composer, which opens it. A press on the session opens the picker. */ const AgentChip = memo(function AgentChip({ vaultId, host, newSession }: { vaultId: string; host: HTMLElement; newSession?: () => boolean }) { const link = useAgentStore((s) => s.links[vaultId]); const id = link?.sessionId ?? null; const queued = useInboxStore((s) => (id ? (s.reviewComments[id]?.length ?? 0) : 0)); - const how = link?.source === "picked" ? "picked" : link?.source === "beside" ? "open beside" : "latest in this folder"; + const guessed = link?.source === "folder"; + const how = link?.source === "picked" ? "Picked" : link?.source === "beside" ? "Open beside" : "Latest in this folder"; return ( - + {id && queued > 0 && ( + )} - + ); }); diff --git a/packages/web/components/code/agent/SessionPicker.tsx b/packages/web/components/code/agent/SessionPicker.tsx index decadb27f8..4c9d05bfff 100644 --- a/packages/web/components/code/agent/SessionPicker.tsx +++ b/packages/web/components/code/agent/SessionPicker.tsx @@ -1,6 +1,8 @@ // The linked-session picker: the sessions working in this folder (title, // agent, state, last activity) plus None. Picking one links it to the folder // and runs whatever action was waiting on a session (Cmd-L with no link). +// The filter on top is focused on open: empty, it lists the most recent; +// typed, it searches every session in the folder by title. import { memo, useMemo, useRef, useState } from "react"; import { Ban, Plus } from "lucide-react"; @@ -12,8 +14,9 @@ import { modernDialog } from "../../ui/modernLook"; import { formatRelativeTime } from "../../../lib/conversationFormat"; import { useAgentStore, type PickerRequest } from "../../../lib/code/agent/agentStore"; import { composeInVault, placeCandidates, steerableRow, vaultAgentSig, vaultMachineOf } from "../../../lib/code/agent/live"; -import type { AgentSessionRow } from "../../../lib/code/agent/sessions"; +import { matchesSessionQuery, type AgentSessionRow } from "../../../lib/code/agent/sessions"; import { SessionMark } from "./SessionMark"; +import { usePickerAria } from "../workspace/pickerAria"; const STATE_COLOR: Record = { working: "var(--sol-green)", @@ -25,6 +28,8 @@ const STATE_COLOR: Record = { const STATE_LABEL: Record = { working: "Working", needs_input: "Needs input", done: "Done", dormant: "Dormant", idle: "Idle" }; const WIDTH = 380; +/** Sessions listed while the filter is empty, most recent first. */ +const RECENT = 12; /** The option keys of the "New session here" and "None" rows; a session row's * key is its id. */ const NEW = "\u0000new"; @@ -34,17 +39,20 @@ export const SessionPicker = memo(function SessionPicker({ request, root }: { re const { vaultId } = request; const sig = useInboxStore((s) => (root ? vaultAgentSig(s, { root, machine: vaultMachineOf(vaultId, s) }) : "")); const linked = useAgentStore((s) => s.links[vaultId]?.sessionId ?? null); + const [query, setQuery] = useState(""); + const searching = query.trim().length > 0; const rows = useMemo(() => { const s = useInboxStore.getState(); - const list: AgentSessionRow[] = root ? placeCandidates(s, { root, machine: vaultMachineOf(vaultId, s) }) : []; + const all: AgentSessionRow[] = root ? placeCandidates(s, { root, machine: vaultMachineOf(vaultId, s) }, searching ? Infinity : RECENT) : []; + const list = searching ? all.filter((r) => matchesSessionQuery(r, query)) : all; // The linked session stays listed even when it works elsewhere (beside). if (linked && !list.some((r) => r._id === linked)) { const row = steerableRow(s, linked); - if (row) list.unshift(row); + if (row && matchesSessionQuery(row, query)) list.unshift(row); } return list; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [sig, root, linked, vaultId]); + }, [sig, root, linked, vaultId, query]); const now = Date.now(); // Sessions, then "New session here", then None. Rows re-sort by activity while // the picker is open, so the selection is held by key, never by position: @@ -54,12 +62,35 @@ export const SessionPicker = memo(function SessionPicker({ request, root }: { re // A selected session that left the list highlights nothing and Enter does // nothing until an arrow picks a row again. const selected = options.indexOf(selectedKey); + const aria = usePickerAria(selected >= 0 ? selectedKey : null); const move = (by: number) => setSelectedKey(options[selected < 0 ? 0 : Math.max(0, Math.min(options.length - 1, selected + by))]); - const listRef = useRef(null); + const inputRef = useRef(null); useWatchEffect(() => { - requestAnimationFrame(() => listRef.current?.focus()); + requestAnimationFrame(() => inputRef.current?.focus()); }, []); + // A typed query puts the best match under Enter. + useWatchEffect(() => { + if (searching) setSelectedKey(rows[0]?._id ?? NEW); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [query]); + + const onKeyDown = (e: React.KeyboardEvent) => { + e.stopPropagation(); + if (e.key === "Escape") { + e.preventDefault(); + close(); + } else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n")) { + e.preventDefault(); + move(1); + } else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p")) { + e.preventDefault(); + move(-1); + } else if (e.key === "Enter" && !e.nativeEvent.isComposing) { + e.preventDefault(); + if (selected >= 0) pick(selectedKey); + } + }; const close = () => useAgentStore.getState().closePicker(); const pick = (key: string) => { @@ -85,37 +116,29 @@ export const SessionPicker = memo(function SessionPicker({ request, root }: { re return (
e.stopPropagation()}> -
{title}
-
{ - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - close(); - } else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n") || e.key === "j") { - e.preventDefault(); - move(1); - } else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p") || e.key === "k") { - e.preventDefault(); - move(-1); - } else if (e.key === "Enter") { - e.preventDefault(); - if (selected >= 0) pick(selectedKey); - } - }} - > +
+ {title} + setQuery(e.target.value)} + onKeyDown={onKeyDown} + placeholder="Filter" + aria-label="Filter sessions" + {...aria.field} + spellCheck={false} + className="min-w-0 flex-1 bg-transparent text-[13px] text-sol-text outline-none placeholder:text-sol-text-dim" + /> +
+
{rows.map((r) => { const state = sessionWorkState(r as InboxSession, now); return ( ); })} - {rows.length === 0 &&
No sessions in this folder
} + {rows.length === 0 &&
{searching ? "No match" : "No sessions in this folder"}
}
+ + ↑ + ↓ move + ↵ {verb} diff --git a/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx b/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx index 09519f9592..e41e1e373d 100644 --- a/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx +++ b/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx @@ -46,11 +46,17 @@ async function render() { const root = createRoot(host); roots.push(root); await act(async () => root.render()); - const list = host.querySelector("[role=listbox]") as HTMLElement; - const press = (key: string) => act(() => void list.dispatchEvent(new window.KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }))); + // Keys go to the filter, which has focus while the picker is open. + const input = host.querySelector("input[aria-label='Filter sessions']") as HTMLInputElement; + const press = (key: string, opts: KeyboardEventInit = {}) => act(() => void input.dispatchEvent(new window.KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...opts }))); + const type = (text: string) => + act(() => { + Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(input, text); + input.dispatchEvent(new window.Event("input", { bubbles: true })); + }); const titles = () => [...host.querySelectorAll("[role=option]")].map((o) => o.textContent ?? ""); const highlighted = () => host.querySelector("[aria-selected=true]")?.textContent ?? ""; - return { press, titles, highlighted }; + return { press, type, titles, highlighted }; } describe("the session picker", () => { @@ -85,4 +91,23 @@ describe("the session picker", () => { expect(picked).toEqual([]); expect(useAgentStore.getState().picker).not.toBeNull(); }); + + it("typing filters every session in the folder by title, past the recent cap, and Enter takes the best match", async () => { + const many = Object.fromEntries(Array.from({ length: 20 }, (_, i) => [`s${i}`, row(`s${i}`, `Session ${i}`, 100 + i)])); + useInboxStore.setState((s) => ({ sessions: { ...s.sessions, ...many } }) as never); + const { press, type, titles, highlighted } = await render(); + // Alpha (updated 20) is past the twelve most recent. + expect(titles().some((t) => t.includes("Alpha"))).toBe(false); + type("alp"); + expect(titles().filter((t) => !/New session|None/.test(t)).map((t) => t.includes("Alpha"))).toEqual([true]); + expect(highlighted()).toContain("Alpha"); + // j and k are letters of the query, never moves. + press("j"); + expect(highlighted()).toContain("Alpha"); + press("n", { ctrlKey: true }); + expect(highlighted()).toContain("New session"); + press("p", { ctrlKey: true }); + press("Enter"); + expect(picked).toEqual(["a"]); + }); }); diff --git a/packages/web/components/code/blame/BlameHoverCard.tsx b/packages/web/components/code/blame/BlameHoverCard.tsx index 8b65d3a3b1..b2fcc4575b 100644 --- a/packages/web/components/code/blame/BlameHoverCard.tsx +++ b/packages/web/components/code/blame/BlameHoverCard.tsx @@ -2,14 +2,14 @@ // agent, when, the commit, the lines, and the ways into it. import { useState } from "react"; -import { Check, Columns2, Copy, CornerDownRight, GitCommitHorizontal } from "lucide-react"; +import { Check, Columns2, Copy, GitCommitHorizontal } from "lucide-react"; import { EntityIdPill } from "../../EntityIdPill"; import { AgentTypeIcon, formatAgentType } from "../../AgentTypeIcon"; import { Button } from "../../ui/button"; import { useInboxStore } from "../../../store/inboxStore"; import { blameViaLabel, isBlameVia } from "../../../lib/repoView"; import { copyToClipboard, formatDateFull, formatRelative } from "../../../lib/utils"; -import { openBlameMessage, openBlameSession } from "../../../lib/code/blame/actions"; +import { openBlameSession } from "../../../lib/code/blame/actions"; import { closeBlameHover, type BlameHover } from "../../../lib/code/blame/hover"; import { runName } from "../../../lib/code/blame/model"; @@ -92,19 +92,6 @@ export function BlameHoverCard({ hover }: { hover: BlameHover }) { > Open beside - {session?.message_id && ( - - )}
)}
diff --git a/packages/web/components/code/workspace/CodeWorkspace.tsx b/packages/web/components/code/workspace/CodeWorkspace.tsx index 0df1fa75a1..9fc2453614 100644 --- a/packages/web/components/code/workspace/CodeWorkspace.tsx +++ b/packages/web/components/code/workspace/CodeWorkspace.tsx @@ -1,5 +1,5 @@ -// The Files content area as a code workspace: up to three editor groups side -// by side (or stacked), each with its own tabs, plus quick open, the tab +// The Files content area as a code workspace: up to three editor groups in a +// two-level split (columns that stack, or rows that divide), each with its own tabs, plus quick open, the tab // switcher and the line prompt. The workspace lives in codeStore per vault // and persists across reloads; the URL's ?f= stays the address of the file in // the focused group, so links, history, Share and the app's own tabs work as @@ -11,29 +11,52 @@ import { memo, useCallback, useMemo, useRef, useState, type ReactNode } from "react"; import { useConvex } from "convex/react"; -import { Group, Panel, Separator } from "react-resizable-panels"; import type { EditorView } from "@codemirror/view"; import { useCodeStore, workspaceFor } from "../../../store/codeStore"; import { useInboxStore } from "../../../store/inboxStore"; import { useVaultStore } from "../../../store/vaultStore"; import { useMountEffect } from "../../../hooks/useMountEffect"; +import { useDerivedSize } from "../../../hooks/useDerivedSize"; import { useWatchEffect } from "../../../hooks/useWatchEffect"; import { useTabActive } from "../../../hooks/usePagePresence"; import { usePaneShortcutAction } from "../../../shortcuts"; -import { registerCodeCommands, type CodeCommandContext } from "../../../lib/code/commands"; +import { registerCodeCommands, runCodeCommand, type CodeCommandContext, type CodeCommandId } from "../../../lib/code/commands"; import { isVirtualTab, SEARCH_RESULTS_TAB } from "../../../lib/code/workspace/virtualTabs"; import { workspaceActions as A } from "../../../lib/code/workspace/controller"; -import { groupKeyOfView, viewOfGroup } from "../../../lib/code/workspace/groupRegistry"; +import { focusGroup, groupKeyOfView, viewOfGroup } from "../../../lib/code/workspace/groupRegistry"; import { followVaultFiles, forgetFile, isFolderPath } from "../../../lib/code/workspace/followFiles"; import { peekHistory, stepHistory } from "../../../lib/code/workspace/navHistory"; import { persistWorkspaces } from "../../../lib/code/workspace/persist"; -import { MAX_GROUPS, activeGroup, groupById, mruTabs, neighborGroup, type FocusDirection, type MruEntry } from "../../../lib/code/workspace/model"; +import { registerExCompletionSource } from "../../../lib/code/vim/completionSource"; +import { + MIN_GROUP_SIZE, + activeGroup, + alternateTab, + canSplitMore, + cycleGroup, + groupById, + groupRects, + laneGroups, + lanesOf, + mruTabs, + neighborGroup, + previousGroup, + type FocusDirection, + type GroupEdge, + type MruEntry, + type SplitDirection, + type Workspace, + type WsGroup, +} from "../../../lib/code/workspace/model"; import { EditorGroup } from "./EditorGroup"; +import { SplitRun } from "./SplitRun"; +import { MIN_GROUP_PX, SIZE_QUANTUM, minShare, roomToSplit } from "../../../lib/code/workspace/splitRoom"; import { QuickOpen } from "./QuickOpen"; import { TabSwitcher } from "./TabSwitcher"; import { GotoLine } from "./GotoLine"; import type { TabMenuAction } from "./TabBar"; import { resolveVaultPath } from "../../../lib/code/vaultPath"; +import { filesHref, navigateToFiles } from "../../../lib/vault/vaultHref"; import { AgentLayer } from "../agent/AgentLayer"; let persisting = false; @@ -45,6 +68,16 @@ function startPersistence(): void { let instances = 0; +/** What a group with tabs gets for its recent list: the same empty array + * every render, so a tab change elsewhere leaves it alone. */ +const NO_RECENT: readonly string[] = []; + +/** The real file the focused group shows, if any. */ +const activeOf = (ws: Parameters[0]): string | null => { + const path = activeGroup(ws).active; + return path && !isVirtualTab(path) ? path : null; +}; + // A hairline between groups with a wider grab area, lit while dragged. // One status bar for the workspace: every group keeps the bar's row, so the // editors end on one line, but only the focused group draws its items. A @@ -52,16 +85,23 @@ let instances = 0; const STATUS_CSS = ` [data-code-workspace] [data-code-group][data-group-idle] .cm-code-status > * { visibility: hidden; }`; -const separatorClass = { - horizontal: - "relative z-10 w-px bg-sol-border/50 before:absolute before:inset-y-0 before:-left-[2px] before:-right-[2px] before:content-[''] before:transition-colors before:duration-150 hover:before:bg-sol-cyan data-[resize-handle-active]:before:bg-sol-cyan", - vertical: - "relative z-10 h-px bg-sol-border/50 before:absolute before:inset-x-0 before:-top-[2px] before:-bottom-[2px] before:content-[''] before:transition-colors before:duration-150 hover:before:bg-sol-cyan data-[resize-handle-active]:before:bg-sol-cyan", +/** What each item of a tab's menu runs. */ +const TAB_MENU_COMMANDS: Record?]> = { + close: ["file.close"], + closeOthers: ["file.closeOthers"], + closeRight: ["tabs.closeRight"], + pin: ["tabs.pin"], + keep: ["tabs.keep"], + splitRight: ["split.right"], + copyPath: ["file.copyPath"], + copyRelative: ["file.copyPath", { relative: true }], + reveal: ["file.reveal"], }; type Overlay = | { kind: "quickOpen"; query?: string } | { kind: "switcher"; held: boolean } + | { kind: "groupTabs"; groupId: string } | { kind: "gotoLine"; line: number; lines: number } | null; @@ -90,8 +130,17 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro const rootRef = useRef(null); const [overlay, setOverlay] = useState(null); const tabActive = useTabActive(); - const live = useRef({ props, ws, tabActive, convex }); - live.current = { props, ws, tabActive, convex }; + const sizeKey = useDerivedSize( + rootRef, + (w, h) => `${Math.round(w / SIZE_QUANTUM) * SIZE_QUANTUM}x${Math.round(h / SIZE_QUANTUM) * SIZE_QUANTUM}`, + () => "0x0", + ); + const size = useMemo(() => { + const [w, h] = sizeKey.split("x").map(Number); + return { w, h }; + }, [sizeKey]); + const live = useRef({ props, ws, tabActive, convex, size }); + live.current = { props, ws, tabActive, convex, size }; // page.tsx keys this component by vault, so `vaultId` is fixed for its life // and every verb below may close over it. @@ -184,6 +233,24 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro [instance], ); + /** The tab a tab verb acts on: the one a tab's menu names (args.group is + * the group's key, `:`), else the active tab of the + * command's group. Null when the command belongs to another workspace. */ + const tabFor = (args: Record | undefined, ctx: CodeCommandContext | undefined): { group: WsGroup; path: string } | null => { + const key = typeof args?.group === "string" ? args.group : null; + if (key && !key.startsWith(`${instance}:`)) return null; + const group = groupById(live.current.ws, key ? key.slice(instance.length + 1) : groupFor(ctx)); + const path = typeof args?.path === "string" ? args.path : group?.active; + return group && path && group.tabs.some((t) => t.path === path) ? { group, path } : null; + }; + + /** Split a group, when it has room; false (vim's E36) when it has none. */ + const split = (groupId: string, path: string, dir: SplitDirection, opts?: { at?: string; preview?: boolean }) => { + if (!roomToSplit(live.current.ws, groupId, dir, live.current.size)) return false; + A.split(vaultId, groupId, path, dir, opts); + return true; + }; + const copy = (text: string) => void navigator.clipboard?.writeText(text).catch(() => {}); const absolute = (path: string) => (live.current.props.vaultRoot ? `${live.current.props.vaultRoot.replace(/\/$/, "")}/${path}` : path); @@ -209,6 +276,16 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro return !!target; }; + /** Run a layout verb with the command's group focused; false when the + * command came from another workspace. */ + const onGroup = (ctx: CodeCommandContext | undefined, verb: () => void) => { + const g = groupFor(ctx); + if (!g) return false; + A.focusGroup(vaultId, g); + verb(); + }; + const axisOf = (args: Record | undefined) => (args?.axis === "height" ? "height" : "width"); + const showGotoLine = () => { const key = `${instance}:${live.current.ws.activeGroup}`; const view = viewOfGroup(key) as EditorView | null; @@ -235,6 +312,17 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro else terms.openTerminal({ endpoint, kind: "shell", cwd: root }); }; + // The `:` line's Tab completion reads this folder's files and tabs. + useMountEffect(() => + registerExCompletionSource((view) => { + if (!groupKeyOfView(view)?.startsWith(`${instance}:`)) return null; + return { + files: () => useVaultStore.getState().files, + tabs: () => [...new Set(mruTabs(live.current.ws).map((e) => e.path))].filter((p) => !isVirtualTab(p)), + }; + }), + ); + useMountEffect(() => registerCodeCommands({ // The results editor is a tab: brought forward where it is open, else @@ -252,35 +340,57 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro const { path } = resolved; const line = typeof args?.line === "number" ? args.line : undefined; const at = line ? (typeof args?.column === "number" ? `${line}:${args.column}` : `${line}`) : undefined; - const split = args?.split === "right" || args?.split === "down" ? args.split : null; - if (split) A.split(vaultId, g, path, split, { at }); - else A.open(vaultId, path, { groupId: g, at }); + const splitDir = args?.split === "right" || args?.split === "down" ? args.split : null; + if (splitDir) return split(g, path, splitDir, { at }); + A.open(vaultId, path, { groupId: g, at }); }, - "file.close": (_a, ctx) => { - const g = groupFor(ctx); - const group = groupById(live.current.ws, g); - if (!group?.active) return false; - A.close(vaultId, group.id, group.active); + "file.close": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.close(vaultId, t.group.id, t.path); }, - "file.closeOthers": (_a, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; - A.closeOthers(vaultId, group.id, group.active); + "file.closeOthers": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.closeOthers(vaultId, t.group.id, t.path); + }, + "tabs.closeRight": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.closeToRight(vaultId, t.group.id, t.path); + }, + "tabs.pin": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.pin(vaultId, t.group.id, t.path); + }, + "tabs.keep": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.keepOpen(vaultId, t.group.id, t.path); }, "file.reopenClosed": (_a, ctx) => { if (!groupFor(ctx) || !live.current.ws.closed.length) return false; A.reopen(vaultId); }, "file.copyPath": (args, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; - copy(args?.relative ? group.active : absolute(group.active)); + const t = tabFor(args, ctx); + if (!t || isVirtualTab(t.path)) return false; + copy(args?.relative ? t.path : absolute(t.path)); }, - "file.reveal": (_a, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; + "file.reveal": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t || isVirtualTab(t.path)) return false; live.current.props.onToggleTree(true); - useVaultStore.getState().requestReveal(group.active); + useVaultStore.getState().requestReveal(t.path); + }, + // The breadcrumbs take focus at the file's own crumb; arrows walk them + // and Escape comes back (CodeFileBar). + "breadcrumbs.focus": (_a, ctx) => { + const g = groupFor(ctx); + const crumb = g && rootRef.current?.querySelector(`[data-code-group="${g}"] [data-crumbs] [aria-current]`); + if (!crumb) return false; + crumb.focus(); }, quickOpen: (args, ctx) => { if (!groupFor(ctx)) return false; @@ -316,15 +426,15 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro }, "nav.back": (_a, ctx) => navStep(ctx, -1), "nav.forward": (_a, ctx) => navStep(ctx, 1), - "split.right": (_a, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; - A.split(vaultId, group.id, group.active, "right"); + "split.right": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + return split(t.group.id, t.path, "right"); }, "split.down": (_a, ctx) => { const group = groupById(live.current.ws, groupFor(ctx)); if (!group?.active) return false; - A.split(vaultId, group.id, group.active, "down"); + return split(group.id, group.active, "down"); }, "split.close": (_a, ctx) => { const g = groupFor(ctx); @@ -336,6 +446,36 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro if (!g) return false; A.only(vaultId, g); }, + "tabs.alternate": (_a, ctx) => { + const g = groupFor(ctx); + if (!g) return false; + A.focusGroup(vaultId, g); + const alt = alternateTab(live.current.ws); + if (!alt) return false; + A.activate(vaultId, alt.groupId, alt.path); + }, + // Window commands act on the group the command came from. + "split.equalize": (_a, ctx) => onGroup(ctx, () => A.equalize(vaultId)), + "split.maximize": (args, ctx) => onGroup(ctx, () => A.maximize(vaultId, axisOf(args))), + "split.resize": (args, ctx) => onGroup(ctx, () => A.resize(vaultId, axisOf(args), typeof args?.by === "number" ? args.by : 1)), + "split.exchange": (_a, ctx) => onGroup(ctx, () => A.exchange(vaultId)), + "split.rotate": (args, ctx) => onGroup(ctx, () => A.rotate(vaultId, args?.delta === -1 ? -1 : 1)), + "split.moveToEdge": (args, ctx) => onGroup(ctx, () => A.moveToEdge(vaultId, (args?.edge as GroupEdge) ?? "left")), + "focus.previous": (_a, ctx) => { + if (!groupFor(ctx)) return false; + const target = previousGroup(live.current.ws); + if (target) A.focusGroup(vaultId, target); + return !!target; + }, + "focus.cycle": (args, ctx) => { + const g = groupFor(ctx); + if (!g) return false; + A.focusGroup(vaultId, g); + const w = live.current.ws; + const target = args?.to === "first" ? w.groups[0].id : args?.to === "last" ? w.groups[w.groups.length - 1].id : cycleGroup(w, args?.delta === -1 ? -1 : 1); + if (target) A.focusGroup(vaultId, target); + return !!target; + }, "focus.left": (_a, ctx) => !!groupFor(ctx) && focusDir("left"), "focus.right": (_a, ctx) => !!groupFor(ctx) && focusDir("right"), "focus.up": (_a, ctx) => !!groupFor(ctx) && focusDir("up"), @@ -376,8 +516,16 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro return !!surface && !!rootRef.current && surface.contains(rootRef.current); }; usePaneShortcutAction("code.closeTab", () => { - const group = activeGroup(live.current.ws); - if (!surfaceHasFocus() || !group.active) return false; + const w = live.current.ws; + const group = activeGroup(w); + if (!surfaceHasFocus()) return false; + // An empty group in a split closes, as in Zed; the last one leaves the + // press to the app. + if (!group.active) { + if (w.groups.length < 2) return false; + A.closeGroup(vaultId, group.id); + return true; + } A.close(vaultId, group.id, group.active); return true; }); @@ -388,39 +536,19 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro }); usePaneShortcutAction("code.splitRight", () => { const group = activeGroup(live.current.ws); - if (!group.active || live.current.ws.groups.length >= MAX_GROUPS) return false; - A.split(vaultId, group.id, group.active, "right"); - return true; + return !!group.active && split(group.id, group.active, "right"); }); // ── render ──────────────────────────────────────────────────────────────── + // A tab's menu runs the same commands the palette and the keys do, on the + // tab it was opened on. const onMenu = useCallback( (groupId: string, action: TabMenuAction, path: string) => { - switch (action) { - case "close": - return A.close(vaultId, groupId, path); - case "closeOthers": - return A.closeOthers(vaultId, groupId, path); - case "closeRight": - return A.closeToRight(vaultId, groupId, path); - case "pin": - return A.pin(vaultId, groupId, path); - case "keep": - return A.keepOpen(vaultId, groupId, path); - case "splitRight": - return A.split(vaultId, groupId, path, "right"); - case "copyPath": - return copy(absolute(path)); - case "copyRelative": - return copy(path); - case "reveal": - live.current.props.onToggleTree(true); - return useVaultStore.getState().requestReveal(path); - } + const [id, extra] = TAB_MENU_COMMANDS[action]; + runCodeCommand(id, { ...extra, group: `${instance}:${groupId}`, path }, { source: "menu" }); }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [vaultId], + [instance], ); const handlers = useMemo( () => ({ @@ -428,11 +556,13 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro onActivate: (g: string, p: string) => A.activate(vaultId, g, p), onClose: (g: string, p: string) => A.close(vaultId, g, p), onKeep: (g: string, p: string) => A.keepOpen(vaultId, g, p), + onOpen: (g: string, p: string) => A.open(vaultId, p, { groupId: g, preview: true }), onMove: (from: string, p: string, to: string, i: number) => A.move(vaultId, from, p, to, i), onSplit: (g: string) => { const group = groupById(live.current.ws, g); - if (group?.active) A.split(vaultId, g, group.active, "right"); + if (group?.active) split(g, group.active, "right"); }, + onListTabs: (g: string) => setOverlay({ kind: "groupTabs", groupId: g }), }), [vaultId], ); @@ -446,21 +576,79 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro return out; }, [ws]); - const closeOverlay = useCallback(() => { - setOverlay(null); - const view = viewOfGroup(`${instance}:${live.current.ws.activeGroup}`) as EditorView | null; - requestAnimationFrame(() => view?.focus()); - }, [instance]); + const closeOverlay = useCallback(() => setOverlay(null), []); + + // Focus that was in the workspace stays in it when what held it goes away: + // a tab or a group closing by any route (Cmd-W, :q, the close button, a + // file deleted on disk), or a dialog closing. It lands on the focused + // group's editor, else on the group's body, never on , where the + // next Cmd-W would close the app tab. + const lastFocus = useRef(null); + useMountEffect(() => { + const root = rootRef.current; + if (!root) return; + const onIn = (e: FocusEvent) => void (lastFocus.current = e.target as Element); + // Focus the person moved out (a click elsewhere) is theirs; only focus + // whose element was removed comes back. + const onOut = (e: FocusEvent) => { + const el = e.target as Element; + queueMicrotask(() => { + if (el.isConnected && lastFocus.current === el && !root.contains(document.activeElement)) lastFocus.current = null; + }); + }; + root.addEventListener("focusin", onIn); + root.addEventListener("focusout", onOut); + return () => { + root.removeEventListener("focusin", onIn); + root.removeEventListener("focusout", onOut); + }; + }); + useWatchEffect(() => { + const raf = requestAnimationFrame(() => { + const was = lastFocus.current; + const now = document.activeElement; + if (!was || was.isConnected || (now && now !== document.body)) return; + focusGroup(`${instance}:${live.current.ws.activeGroup}`); + }); + return () => cancelAnimationFrame(raf); + }, [ws, overlay]); const horizontal = ws.orientation === "horizontal"; const groups = ws.groups; const multi = groups.length > 1; - const canSplit = groups.length < MAX_GROUPS; - const layout = useMemo(() => { - const sizes = ws.sizes && ws.sizes.length === groups.length ? ws.sizes : groups.map(() => 100 / groups.length); - return Object.fromEntries(groups.map((g, i) => [g.id, sizes[i]])); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [groups.map((g) => g.id).join(","), ws.orientation]); + const lanes = lanesOf(ws); + const blocks = useMemo(() => laneGroups(ws), [ws]); + const rects = useMemo(() => groupRects(ws), [ws]); + // Each split's minimum share: its pixel floor over its own length. Lanes + // run along the outer axis; the groups in a lane across it. + const outerPx = horizontal ? size.w : size.h; + const innerPx = horizontal ? size.h : size.w; + const outerFloor = horizontal ? MIN_GROUP_PX.width : MIN_GROUP_PX.height; + const innerFloor = horizontal ? MIN_GROUP_PX.height : MIN_GROUP_PX.width; + const outerOrientation = horizontal ? "horizontal" : "vertical"; + const innerOrientation = horizontal ? "vertical" : "horizontal"; + + const renderGroup = (g: WsGroup) => { + const r = rects.get(g.id); + const top = !r || r.y < 1e-6; + return ( + 1 - 1e-6)} + canSplit={roomToSplit(ws, g.id, "right", size)} + groupNumber={groupNumbers?.get(g.id)} + recent={g.tabs.length ? NO_RECENT : recent} + deepLinking={!!props.deepLinking} + renderNote={renderNote} + onMenu={onMenu} + {...handlers} + /> + ); + }; const groupNumbers = useMemo(() => (multi ? new Map(groups.map((g, i) => [g.id, i + 1])) : null), [groups, multi]); @@ -482,35 +670,31 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro > - { - if (multi) A.sizes(vaultId, groups.map((g) => l[g.id] ?? 0)); - }} + `lane:${b[0].id}`)} + sizes={ws.sizes} + minSize={minShare(outerPx, blocks.length, outerFloor)} + onSizes={(sizes) => A.sizes(vaultId, null, sizes)} > - {groups.map((g, i) => ( - 0 ? (horizontal ? "horizontal" : "vertical") : null}> - - - ))} - + {(laneId, li) => ( + g.id)} + sizes={lanes[li]?.sizes ?? null} + minSize={minShare(innerPx, blocks[li].length, innerFloor)} + onSizes={(sizes) => A.sizes(vaultId, li, sizes)} + > + {(_id, gi) => renderGroup(blocks[li][gi])} + + )} + {overlay?.kind === "quickOpen" && ( { + onOpen={(path, at, toSide) => { setOverlay(null); const group = activeGroup(live.current.ws); - if (split) A.split(vaultId, group.id, path, "right", { at, preview: true }); - else A.open(vaultId, path, { preview: true, at }); + // No room beside it: the file opens here. + if (!(toSide && split(group.id, path, "right", { at, preview: true }))) A.open(vaultId, path, { preview: true, at }); + }} + onSymbols={(scope, query) => { + setOverlay(null); + // Once the dialog is gone and focus is back in the editor (contract 9). + setTimeout(() => runCodeCommand(scope === "file" ? "goto.symbol" : "goto.workspaceSymbol", { query }, { source: "palette" }), 0); + }} + onOpenLocal={(localPath, at) => { + setOverlay(null); + navigateToFiles(filesHref({ localPath, line: at })); }} /> )} @@ -540,6 +733,17 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro }} /> )} + {overlay?.kind === "groupTabs" && ( + { + setOverlay(null); + A.activate(vaultId, e.groupId, e.path); + }} + /> + )} {overlay?.kind === "gotoLine" && ( (group ? group.tabs.map((t) => ({ groupId: group.id, path: t.path })) : []), [group]); + const pinned = useMemo(() => new Set(group?.tabs.filter((t) => t.pinned).map((t) => t.path)), [group]); + if (!group || !entries.length) return null; return ( - <> - {separator && } - {/* A percentage minimum can always be met; a pixel one in a pane too - narrow for it livelocks the panel library (see app/files/page.tsx). */} - - {children} - - + e.path === group.active))} + pinned={pinned} + onClose={onClose} + onPick={onPick} + /> ); } diff --git a/packages/web/components/code/workspace/EditorGroup.tsx b/packages/web/components/code/workspace/EditorGroup.tsx index 5a48f9149c..ec79d7203d 100644 --- a/packages/web/components/code/workspace/EditorGroup.tsx +++ b/packages/web/components/code/workspace/EditorGroup.tsx @@ -5,11 +5,14 @@ // editor (docs/architecture/code-editor.md, contract 2). import { memo, useMemo, useRef, useState, type ReactNode } from "react"; -import { FolderTree } from "lucide-react"; +import { File, FileText } from "lucide-react"; import { isVaultMarkdownPath } from "@codecast/shared/contracts"; import { VaultFileView } from "../../vault/VaultFileView"; import { KeyCap } from "../../KeyCap"; import { useShortcutParts } from "../../../shortcuts"; +import type { ShortcutAction } from "../../../shortcuts/registry"; +import { useVaultStore } from "../../../store/vaultStore"; +import { runCodeCommand } from "../../../lib/code/commands"; import { CodeGroupContext } from "./groupContext"; import { TabBar, type TabMenuAction } from "./TabBar"; import { isDraggingTab, takeTabDrag } from "../../../lib/code/workspace/tabDrag"; @@ -20,6 +23,9 @@ import { SearchResultsTab } from "../search/SearchResultsEditorHost"; /** Tabs whose saved cursor was already put back this page load. */ const restored = new Set(); +/** How many recent files an empty group lists. */ +const EMPTY_RECENT = 8; + export interface EditorGroupProps { instance: string; vaultId: string; @@ -28,33 +34,76 @@ export interface EditorGroupProps { leftInset: boolean; rightInset: boolean; canSplit: boolean; + /** Its number among the groups, when there are several. */ + groupNumber?: number; + /** Files opened lately, for the group while it has no tab. */ + recent: readonly string[]; + /** A deep link is resolving into this workspace: an empty group stays blank + * rather than flash its choices before the file lands. */ + deepLinking: boolean; renderNote(path: string, line: string | null): ReactNode; onFocusGroup(groupId: string): void; onActivate(groupId: string, path: string): void; + onOpen(groupId: string, path: string): void; onClose(groupId: string, path: string): void; onKeep(groupId: string, path: string): void; onMove(fromGroupId: string, path: string, toGroupId: string, toIndex: number): void; onMenu(groupId: string, action: TabMenuAction, path: string): void; onSplit(groupId: string): void; + onListTabs(groupId: string): void; } -function EmptyGroup() { - const keys = useShortcutParts("code.quickOpen"); +/** A key hint that is also the button: name, then its keys. */ +function KeyAction({ label, action, onClick }: { label: string; action: ShortcutAction; onClick(): void }) { + const keys = useShortcutParts(action); return ( -
- + + ); +} + +/** A group with no tab: the files opened lately, one click each, and the two + * ways to find another. */ +function EmptyGroup({ recent, onOpen }: { recent: readonly string[]; onOpen(path: string): void }) { + // Only files still on disk; a string, so a watcher event re-renders nothing. + const present = useVaultStore((s) => recent.filter((p) => s.files[p]).slice(0, EMPTY_RECENT).join("\n")); + const rows = present ? present.split("\n") : []; + return ( +
+ {rows.length > 0 && ( +
+ {rows.map((p) => { + const slash = p.lastIndexOf("/"); + const Icon = isVaultMarkdownPath(p) ? FileText : File; + return ( + + ); + })}
)} +
+ runCodeCommand("quickOpen")} /> + runCodeCommand("search.project", {})} /> +
); } @@ -67,14 +116,19 @@ export const EditorGroup = memo(function EditorGroup({ leftInset, rightInset, canSplit, + groupNumber, + recent, + deepLinking, renderNote, onFocusGroup, onActivate, + onOpen, onClose, onKeep, onMove, onMenu, onSplit, + onListTabs, }: EditorGroupProps) { const ctx = useMemo(() => ({ key: `${instance}:${group.id}`, groupId: group.id, active: focused }), [instance, group.id, focused]); const [dropping, setDropping] = useState(false); @@ -87,7 +141,8 @@ export const EditorGroup = memo(function EditorGroup({ const restore = useRef<{ path: string | null; at: string | null }>({ path: null, at: null }); if (restore.current.path !== path) { const key = `${vaultId}\u0000${path}`; - const saved = path && tab?.cursor && !restored.has(key) ? `${tab.cursor.line}:${tab.cursor.col}` : null; + const c = tab?.cursor; + const saved = path && c && !restored.has(key) ? `${c.line}:${c.col}${c.top ? `@${c.top}` : ""}` : null; if (path) restored.add(key); restore.current = { path, at: saved }; } @@ -111,19 +166,23 @@ export const EditorGroup = memo(function EditorGroup({ leftInset={leftInset} rightInset={rightInset} canSplit={canSplit} + groupNumber={groupNumber} onActivate={onActivate} onClose={onClose} onKeep={onKeep} onMove={onMove} onMenu={onMenu} onSplit={onSplit} + onListTabs={onListTabs} /> {/* Focusable, so a press on a group with no editor in it (a missing file, an empty group) keeps focus in the workspace and Cmd-W closes the editor tab, not the app tab. */}
{ if (!isDraggingTab()) return; @@ -142,7 +201,7 @@ export const EditorGroup = memo(function EditorGroup({ }} > {!path ? ( - + deepLinking ? null : onOpen(group.id, p)} /> ) : path === SEARCH_RESULTS_TAB ? ( onClose(group.id, path)} /> ) : isVaultMarkdownPath(path) ? ( diff --git a/packages/web/components/code/workspace/TabBar.tsx b/packages/web/components/code/workspace/TabBar.tsx index e7b5ea344b..9c8461d258 100644 --- a/packages/web/components/code/workspace/TabBar.tsx +++ b/packages/web/components/code/workspace/TabBar.tsx @@ -3,8 +3,11 @@ // at the left with a pin and no close button. A dirty tab shows a dot where // its close button is, and the button on hover. Middle click closes; tabs drag // to reorder and between groups; the strip scrolls sideways with the active -// tab kept in view. +// tab kept in view. Pinned tabs stay put at the left, outside the scroll, and +// a count of the tabs scrolled out of view opens the group's tab list. +import { FileStateMark } from "./FileStateMark"; +import { deletedNameClass, fileStateWords } from "../../../lib/code/workspace/fileState"; import { memo, useMemo, useRef, useState } from "react"; import { File, FileStack, FileText, Image as ImageIcon, Pin, SquareSplitHorizontal, X } from "lucide-react"; import { isVaultAssetPath, isVaultMarkdownPath } from "@codecast/shared/contracts"; @@ -16,6 +19,8 @@ import { ContextMenu, CtxItem, CtxSeparator, useContextMenu } from "../../ui/con import { withShortcut } from "../../../shortcuts"; import type { WsGroup, WsTab } from "../../../lib/code/workspace/model"; import { PresenceDot } from "../agent/PresenceDot"; +import { focusGroup } from "../../../lib/code/workspace/groupRegistry"; +import { useCodeGroup } from "./groupContext"; import { endTabDrag, isDraggingTab, startTabDrag, takeTabDrag } from "../../../lib/code/workspace/tabDrag"; const DRAG_TYPE = "application/x-codecast-tab"; @@ -28,6 +33,8 @@ export interface TabBarProps { leftInset: boolean; rightInset: boolean; canSplit: boolean; + /** Its number among the groups, when there are several. */ + groupNumber?: number; /** Each takes the group, so one stable set serves every group. */ onActivate(groupId: string, path: string): void; onClose(groupId: string, path: string): void; @@ -35,6 +42,8 @@ export interface TabBarProps { onMove(fromGroupId: string, path: string, toGroupId: string, toIndex: number): void; onMenu(groupId: string, action: TabMenuAction, path: string): void; onSplit(groupId: string): void; + /** List this group's tabs (the strip hides some). */ + onListTabs(groupId: string): void; } /** A tab's handlers: one object per strip that never changes, so a tab @@ -43,7 +52,9 @@ interface TabEvents { activate(path: string): void; close(path: string): void; keep(path: string): void; - context(e: React.MouseEvent, path: string): void; + context(e: React.MouseEvent | React.KeyboardEvent, path: string): void; + /** Back to the group's editor (a press on a tab leaves focus there). */ + focusView(): void; dragStart(e: React.DragEvent, path: string): void; dragOver(e: React.DragEvent, path: string): void; drop(e: React.DragEvent, path: string): void; @@ -64,10 +75,31 @@ const nameOf = (path: string) => (isVirtualTab(path) ? virtualTabTitle(path) : p /** Width of the fade over a clipped edge of the strip. */ const FADE_PX = 28; -/** Fade whichever edges hide tabs. */ -function paintClip(strip: HTMLElement): void { +/** A name's tail that stays whole when the name is cut: its extension, with a + * test or spec marker before it. */ +const NAME_TAIL = /(?:\.(?:test|spec|stories|mount\.test|d))?\.[^.]+$/; + +/** Fade whichever edges hide tabs, and count the tabs not wholly in view. */ +function paintClip(strip: HTMLElement, chip: HTMLElement | null): void { const left = strip.scrollLeft > 1; const right = strip.scrollLeft + strip.clientWidth < strip.scrollWidth - 1; + if (chip) { + let hidden = 0; + if (left || right) { + const from = strip.scrollLeft; + const to = from + strip.clientWidth; + for (const el of strip.children) { + const t = el as HTMLElement; + if (t.dataset.tabPath && (t.offsetLeft < from - 1 || t.offsetLeft + t.offsetWidth > to + 1)) hidden++; + } + } + const label = hidden ? `+${hidden}` : ""; + if (chip.textContent !== label) { + chip.textContent = label; + chip.setAttribute("aria-label", `${hidden} more tabs`); + } + chip.hidden = !hidden; + } const clip = left && right ? "both" : left ? "left" : right ? "right" : ""; if ((strip.dataset.clip ?? "") === clip) return; if (clip) strip.dataset.clip = clip; @@ -89,6 +121,18 @@ function revealTab(strip: HTMLElement, tab: HTMLElement): void { else if (end + (last ? 0 : FADE_PX) > strip.scrollLeft + strip.clientWidth) strip.scrollLeft = last ? strip.scrollWidth : end + FADE_PX - strip.clientWidth; } +/** The name, at most 22ch: the middle goes, the extension stays. */ +function TabName({ name, italic, className = "" }: { name: string; italic: boolean; className?: string }) { + const tail = NAME_TAIL.exec(name)?.[0] ?? ""; + const stem = tail && tail.length < name.length ? name.slice(0, -tail.length) : name; + return ( + + {stem} + {stem !== name && {tail}} + + ); +} + const Tab = memo(function Tab({ vaultId, tab, @@ -96,9 +140,11 @@ const Tab = memo(function Tab({ focused, duplicateName, dropBefore, + panelId, events, }: { vaultId: string; + panelId: string; tab: WsTab; active: boolean; focused: boolean; @@ -107,17 +153,33 @@ const Tab = memo(function Tab({ events: TabEvents; }) { const dirty = useCodeStore((s) => !!s.dirty[bufferKey(vaultId, tab.path)]); + const conflict = useCodeStore((s) => s.conflicts[bufferKey(vaultId, tab.path)]); const isNew = useIsNewFile(bufferKey(vaultId, tab.path)); const name = nameOf(tab.path); const dir = duplicateName ? tab.path.slice(0, Math.max(0, tab.path.length - name.length - 1)).split("/").pop() : null; + const state = fileStateWords(conflict, dirty); + // Anything pending holds the close button's slot, as a dirty dot does. + const marked = !!state; + const label = [dir ? `${name} (${dir})` : name, state, tab.pinned && "pinned", tab.preview && "preview", isNew && "new file"].filter(Boolean).join(", "); + const pressed = useRef(false); return (
void (pressed.current = true)} + // A press focuses the editor, as in Zed; only keys stop on the tab. + onFocus={() => { + if (pressed.current) events.focusView(); + pressed.current = false; + }} onMouseDown={(e) => { if (e.button === 0) events.activate(tab.path); }} @@ -133,7 +195,7 @@ const Tab = memo(function Tab({ onDragOver={(e) => events.dragOver(e, tab.path)} onDrop={(e) => events.drop(e, tab.path)} onDragEnd={endTabDrag} - className={`group/tab relative flex h-full shrink-0 cursor-default select-none items-center gap-1.5 border-r border-sol-border/30 pl-2.5 pr-1 text-meta transition-colors ${ + className={`group/tab relative flex h-full shrink-0 cursor-default select-none items-center gap-1.5 border-r border-sol-border/30 pl-2.5 pr-1 text-meta outline-none transition-colors focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-sol-cyan ${ active ? "bg-sol-bg text-sol-text" : "text-sol-text-dim hover:bg-sol-bg/50 hover:text-sol-text-muted" }`} > @@ -141,11 +203,11 @@ const Tab = memo(function Tab({ {active && } {dropBefore && } {tab.pinned ? : tabIcon(tab.path)} - {name} + {dir && {dir}} - {isNew && new} + {isNew && new} {!isVirtualTab(tab.path) && } - {tab.pinned && !dirty ? ( + {tab.pinned && !marked ? ( ) : ( )}
@@ -174,14 +236,19 @@ export const TabBar = memo(function TabBar({ leftInset, rightInset, canSplit, + groupNumber, onActivate, onClose, onKeep, onMove, onMenu, onSplit, + onListTabs, }: TabBarProps) { + const groupCtx = useCodeGroup(); + const groupKey = groupCtx?.key ?? group.id; const stripRef = useRef(null); + const chipRef = useRef(null); const [dropAt, setDropAt] = useState(null); const menu = useContextMenu(); @@ -194,7 +261,7 @@ export const TabBar = memo(function TabBar({ const el = [...tabs].find((t) => t.dataset.tabPath === group.active); const reveal = () => { if (el) revealTab(strip, el); - paintClip(strip); + paintClip(strip, chipRef.current); }; reveal(); // The tab can grow after it is shown (its "new" or dirty mark arriving). @@ -208,7 +275,7 @@ export const TabBar = memo(function TabBar({ useWatchEffect(() => { const strip = stripRef.current; if (!strip) return; - const paint = () => paintClip(strip); + const paint = () => paintClip(strip, chipRef.current); paint(); strip.addEventListener("scroll", paint, { passive: true }); const ro = typeof ResizeObserver === "function" ? new ResizeObserver(paint) : null; @@ -239,14 +306,36 @@ export const TabBar = memo(function TabBar({ if (d) onMove(d.groupId, d.path, group.id, index); }; - const latest = useRef({ group, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }); - latest.current = { group, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }; + const pinned = group.tabs.filter((t) => t.pinned); + const rest = pinned.length ? group.tabs.filter((t) => !t.pinned) : group.tabs; + const tabProps = (t: WsTab) => ({ + vaultId, + tab: t, + active: t.path === group.active, + focused, + duplicateName: (names.get(nameOf(t.path)) ?? 0) > 1, + dropBefore: dropAt === indexOf(t.path), + panelId: `${groupKey}:panel`, + }); + + const latest = useRef({ group, groupKey, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }); + latest.current = { group, groupKey, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }; const events = useMemo( () => ({ activate: (path) => latest.current.onActivate(latest.current.group.id, path), close: (path) => latest.current.onClose(latest.current.group.id, path), keep: (path) => latest.current.onKeep(latest.current.group.id, path), - context: (e, path) => latest.current.menu.open(e, path, { force: true }), + context: (e, path) => { + // From the keyboard (Shift-F10, the menu key) the menu opens under + // the tab; a click opens it at the pointer. + if ("key" in e || (e.clientX === 0 && e.clientY === 0)) { + e.preventDefault(); + const r = (e.currentTarget as HTMLElement).getBoundingClientRect(); + return latest.current.menu.openAt(r.left, r.bottom + 2, path); + } + latest.current.menu.open(e, path, { force: true }); + }, + focusView: () => focusGroup(latest.current.groupKey), dragStart: (e, path) => { startTabDrag({ groupId: latest.current.group.id, path }); e.dataTransfer.effectAllowed = "move"; @@ -269,8 +358,40 @@ export const TabBar = memo(function TabBar({ return (
{ + const el = e.target as HTMLElement; + const path = el.getAttribute("role") === "tab" ? el.dataset.tabPath : undefined; + if (!path) return; + const tabs = [...e.currentTarget.querySelectorAll("[role=tab]")]; + const i = tabs.indexOf(el); + const to = (j: number) => tabs[(j + tabs.length) % tabs.length]?.focus(); + if (e.key === "ArrowRight") to(i + 1); + else if (e.key === "ArrowLeft") to(i - 1); + else if (e.key === "Home") to(0); + else if (e.key === "End") to(tabs.length - 1); + else if (e.key === "Enter" || e.key === " ") { + onActivate(group.id, path); + requestAnimationFrame(() => focusGroup(groupKey)); + } else if (e.key === "Escape") focusGroup(groupKey); + else if (e.key === "Delete" || e.key === "Backspace") { + onClose(group.id, path); + // Focus stays in the strip, on the tab that took its place. + requestAnimationFrame(() => stripRef.current?.parentElement?.querySelector("[role=tab][tabindex='0']")?.focus()); + } else if (e.key === "ContextMenu" || (e.key === "F10" && e.shiftKey)) events.context(e, path); + else return; + e.preventDefault(); + e.stopPropagation(); + }} className={`flex h-8 shrink-0 items-stretch border-b border-sol-border/30 bg-sol-bg-alt/50 ${leftInset ? "pl-9" : ""} ${rightInset ? "pr-9" : ""}`} > + {pinned.length > 0 && ( +
+ {pinned.map((t) => ( + + ))} +
+ )}
- {group.tabs.map((t, i) => ( - 1} - dropBefore={dropAt === i} - events={events} - /> + {rest.map((t) => ( + ))} {dropAt === group.tabs.length && }
+ {/* Filled in by paintClip; React never renders the count. */} + ); diff --git a/packages/web/components/conversation/blocks/toolBlocks.tsx b/packages/web/components/conversation/blocks/toolBlocks.tsx index be86cf91fa..45d98a734e 100644 --- a/packages/web/components/conversation/blocks/toolBlocks.tsx +++ b/packages/web/components/conversation/blocks/toolBlocks.tsx @@ -813,14 +813,13 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti const startLine = getStartLine(); // Where the card's "Open in editor" lands: the lines a Read read, the lines - // an Edit wrote (flashed on arrival), the top of a written file, a patch's + // an Edit wrote (flashed on arrival, and found again by their text when the + // file has moved under them since), the top of a written file, a patch's // first file at its first hunk. A deleted file has nothing to open. const editorTarget = useMemo(() => { if (isApplyPatch) { const first = applyPatchDiffs.find((d) => d.operation !== "Delete"); - if (!first) return null; - const at = first.hunks.find((h) => h.newStart > 0)?.newStart; - return { path: first.filePath, ...(at ? { line: at } : {}) }; + return first ? patchSectionTarget(first) : null; } if (!filePath || (!isStandardEdit && !isMultiEdit && !isRead)) return null; if (isRead) { @@ -833,7 +832,7 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti const range = result && !result.is_error ? editedLineRange(safeString(result.content), newTexts[0]) : undefined; // A result with no line numbers (MultiEdit's "Applied N edits") leaves the // editor to find the edit's new text in the file once it shows. - return { path: filePath, ...(range ?? (newTexts.length ? { find: newTexts } : {})) }; + return { path: filePath, ...range, ...(newTexts.length ? { find: newTexts } : {}) }; }, [isApplyPatch, applyPatchDiffs, filePath, isStandardEdit, isMultiEdit, isRead, parsedInput, tool.name, result]); const toolColor = toolColorClass(isApplyPatch ? "apply_patch" : tool.name); @@ -920,7 +919,8 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti )} {editorTarget && ( - + // An edit opens with what it replaced peeked inline at its lines. + )} {browserTab && } {gitOutcome && } @@ -1092,8 +1092,11 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti const diffStartLine = diff.hunks[0]?.oldStart || diff.hunks[0]?.newStart || 1; return (
0 ? "border-t border-sol-border/20" : ""}> -
- {getRelativePath(diff.filePath)} +
+ {getRelativePath(diff.filePath)} + {isApplyPatch && "operation" in diff && diff.operation !== "Delete" && ( + + )}
}): { path: string; line?: number } { + const at = section.hunks.find((h) => h.newStart > 0)?.newStart; + return { path: section.filePath, ...(at ? { line: at } : {}) }; +} diff --git a/packages/web/components/pr/PRThread.tsx b/packages/web/components/pr/PRThread.tsx index cc4316c52c..1a5121c6b6 100644 --- a/packages/web/components/pr/PRThread.tsx +++ b/packages/web/components/pr/PRThread.tsx @@ -193,7 +193,10 @@ export function PRLineThread({ linkHref, onSelectLines, placement, + editAction, }: { + /** Opens the thread's lines in this machine's checkout, where there is one. */ + editAction?: ReactNode; /** Where the thread's passage is now, when it moved or is gone. */ placement?: AnchorPlacement | null; /** The address of the lines this thread is on, and selecting them. */ @@ -257,6 +260,7 @@ export function PRLineThread({
{span}
))} + {editAction} {noteMode && onNoteMode && (comments.length === 0 || replying) && ( )} diff --git a/packages/web/components/repo/BlobContent.tsx b/packages/web/components/repo/BlobContent.tsx index ea6fdd0464..de34d87c30 100644 --- a/packages/web/components/repo/BlobContent.tsx +++ b/packages/web/components/repo/BlobContent.tsx @@ -18,11 +18,8 @@ import { BlobView } from "./BlobView"; import { useCodeComments, useSyncFileCodeComments } from "../../hooks/useSyncCodeComments"; import { useAttributedSession, useLineComments } from "../../hooks/useLineComments"; import { useEventListener } from "../../hooks/useEventListener"; -import { useRepoBlame, useRepoBlameSessions, useRepoBlob, useRepoLog, useRepoWorktrees } from "../../hooks/useRepoBrowse"; -import { localCheckoutFile } from "../../lib/filesPane"; -import { OpenInEditorButton } from "../OpenInEditorButton"; -import { useInboxStore } from "../../store/inboxStore"; -import { localDeviceIdOf } from "../../hooks/useLocalDeviceId"; +import { useRepoBlame, useRepoBlameSessions, useRepoBlob, useRepoLog } from "../../hooks/useRepoBrowse"; +import { LocalEditButton } from "./LocalEditButton"; import { useWatchEffect } from "../../hooks/useWatchEffect"; import { serverCommentId, type CodeCommentRow } from "../../lib/prView"; import { @@ -304,22 +301,6 @@ export function BlobContent({ ); } -// "Open in editor": the same file at the same line in this machine's own -// checkout of the repository, when it has one. -function LocalEditButton({ repository, refName, path, line }: { repository: string; refName: string; path: string; line?: number }) { - const checkouts = useRepoWorktrees(repository).data?.checkouts; - const deviceId = useInboxStore(localDeviceIdOf); - const local = checkouts ? localCheckoutFile(checkouts, deviceId, refName, path) : null; - if (!local) return null; - return ( - - ); -} - function CommentedBlobView({ repository, path, anchorRef, content, selection, selectLine, blameRanges, blameMode, sessionRanges, sessionColors, focusSession }: { repository: string; path: string; anchorRef: string; content: string; selection: LineRange | null; selectLine: (line: number, extend: boolean) => void; diff --git a/packages/web/components/repo/RepoCompareContent.tsx b/packages/web/components/repo/RepoCompareContent.tsx index dacdf08f6b..dc30f504e2 100644 --- a/packages/web/components/repo/RepoCompareContent.tsx +++ b/packages/web/components/repo/RepoCompareContent.tsx @@ -7,6 +7,7 @@ import { useRepoCompare } from "../../hooks/useRepoBrowse"; import { commitPageHref, repoCompareHref, type RepoRouteFamily } from "../../lib/repoView"; import { serverErrorText } from "../../lib/errorCause"; import { useDiffAddress } from "../../hooks/useDiffAddress"; +import { useLocalEditAction } from "../../hooks/useLocalEdit"; export function RepoCompareContent({ repository, base, head, family }: { repository: string; base: string; head: string; family: RepoRouteFamily; @@ -19,6 +20,9 @@ export function RepoCompareContent({ repository, base, head, family }: { const rootRef = useRef(null); const diffHref = useCallback((hash: string) => repoCompareHref(repository, base, head, family) + hash, [repository, base, head, family]); const { flow } = useDiffAddress({ diffHref, here: true, ready: files.length > 0, rootRef, stickyTop: 0 }); + // Each file's "Edit": the file in this machine's checkout of the head, with + // the editor's diff against the base, when a worktree sits on the head. + const editAction = useLocalEditAction(repository, head, (c) => (c.onRef ? { ref: base, label: base } : null)); return
{ event.preventDefault(); const fields = new FormData(event.currentTarget); @@ -49,7 +53,7 @@ export function RepoCompareContent({ repository, base, head, family }: { {commit.author_login || commit.author_name} )} } - {files.length ? :

No file changes between these refs.

} + {files.length ? :

No file changes between these refs.

} }
; } diff --git a/packages/web/components/sidebar/navPrimitives.tsx b/packages/web/components/sidebar/navPrimitives.tsx index abd0971bf4..509117e26c 100644 --- a/packages/web/components/sidebar/navPrimitives.tsx +++ b/packages/web/components/sidebar/navPrimitives.tsx @@ -44,6 +44,8 @@ export type SectionRowSpec = { control?: React.ReactNode; /** A suggestion rather than a live object — rendered quieter until hover. */ dim?: boolean; + /** Something new waits inside: the name carries weight and full ink. */ + unread?: boolean; /** A real address: the row is a link to it (open in a new tab, copy), and `onSelect` runs after the click. */ href?: string; /** Hover text when it should say more than the name ("Message Sam"). */ @@ -61,6 +63,7 @@ export function SectionRow({ row, className }: { row: SectionRowSpec; className? onContextMenu={row.onContextMenu} {...(row.path ? paneDragProps(row.path, row.name) : {})} data-nav-dim={row.dim ? "" : undefined} + data-nav-unread={row.unread ? "" : undefined} className={`flex items-center group/v transition-colors ${ row.active ? "bg-sol-bg-highlight text-sol-text" @@ -98,7 +101,7 @@ export function SectionRow({ row, className }: { row: SectionRowSpec; className? aria-current={row.active ? "page" : undefined} > {row.icon} - {row.name} + {row.name} )} {/* A control is the point of the row it sits on, so it survives the diff --git a/packages/web/components/stage/StageSplitView.tsx b/packages/web/components/stage/StageSplitView.tsx index 772b1aef5d..7caa151c11 100644 --- a/packages/web/components/stage/StageSplitView.tsx +++ b/packages/web/components/stage/StageSplitView.tsx @@ -27,7 +27,7 @@ import { type StageNode, } from "../../store/stageSplit"; import { StageRail } from "./StageRail"; -import { paneSessionId, stageClose, stageExpand, stageFocus, stageNavigateLeaf, startPaneDrag } from "../../lib/stage"; +import { stageLeafSession, stageClose, stageExpand, stageFocus, stageNavigateLeaf, startPaneDrag } from "../../lib/stage"; import { pathLabel } from "../../lib/pathLabel"; import { browserPathLabel, isBrowserRoutePath, subscribeBrowserTitles } from "../../lib/browserPane"; import { isSimulatorRoutePath } from "../../lib/simulatorPane"; @@ -151,7 +151,8 @@ const StageCell = memo(function StageCell({ solo: boolean; rail: "left" | "right" | null; }) { - const sessionId = paneSessionId(path); + const leafSession = stageLeafSession(path); + const sessionId = leafSession?.sessionId ?? null; const title = usePaneTitle(path); const restore = useCallback(() => { useInboxStore.getState().setStageWide(null); @@ -192,7 +193,7 @@ const StageCell = memo(function StageCell({ expand, so the drag handle is a grip that surfaces on hover. */} {!solo && } - + ) : ownsHeader ? ( diff --git a/packages/web/components/tasks/TaskInlineThread.tsx b/packages/web/components/tasks/TaskInlineThread.tsx index 5fe03a7aec..ef1eef708c 100644 --- a/packages/web/components/tasks/TaskInlineThread.tsx +++ b/packages/web/components/tasks/TaskInlineThread.tsx @@ -8,6 +8,7 @@ // reconciles exactly as it does on the task page. import type { ReactNode } from "react"; +import { FilePathContext, useFolderPathContext } from "../../lib/filePathLinks"; import { useSyncTaskDetail, useTaskComments } from "../../hooks/useSyncTasks"; import { useTaskRow } from "../../hooks/useThreadPreviews"; import { TaskCommentStream, type TaskOwnerRef } from "./TaskCommentStream"; @@ -28,8 +29,10 @@ export function TaskInlineThread({ taskId, newSince, focusComposer = false, owne const task = useTaskRow(taskId); const comments = useTaskComments(taskId); const desc = (task?.description ?? "").trim(); + // A path the description or a comment cites is relative to the task's project. + const fileCtx = useFolderPathContext(task?.project_path); return ( - <> + {desc && (
Description @@ -38,6 +41,6 @@ export function TaskInlineThread({ taskId, newSince, focusComposer = false, owne )} {children} - + ); } diff --git a/packages/web/components/terminal/ConversationTerminal.tsx b/packages/web/components/terminal/ConversationTerminal.tsx index d2db01bc67..793f5dd80e 100644 --- a/packages/web/components/terminal/ConversationTerminal.tsx +++ b/packages/web/components/terminal/ConversationTerminal.tsx @@ -166,6 +166,7 @@ function SplitBody({ convKey, split, tmuxSession }: { convKey: string; split: Sp target, title: target, detached: true, + conversationId: convKey, // Interactive, same as a manual `tmux attach` — the pill is just the // safe version of it (ignore-size, no nesting). interactive: true, diff --git a/packages/web/components/vault/VaultFileView.tsx b/packages/web/components/vault/VaultFileView.tsx index c2b8a2a79a..dff93236e5 100644 --- a/packages/web/components/vault/VaultFileView.tsx +++ b/packages/web/components/vault/VaultFileView.tsx @@ -6,15 +6,15 @@ import { memo, Suspense, useMemo, useState } from "react"; import { lazyNamed } from "../../lib/lazyNamed"; import { useWatchEffect } from "../../hooks/useWatchEffect"; import { FileQuestion, FileWarning } from "lucide-react"; +import { FileUnavailable } from "./FileUnavailable"; import { VAULT_MAX_PREVIEW_BYTES, vaultFileKind } from "@codecast/shared/contracts"; import { CODE_EDITOR_MAX_BYTES } from "../../lib/code/limits"; -import { vaultAssetUrl } from "../../lib/vault/client"; +import { readFailureLabel, vaultAssetUrl } from "../../lib/vault/client"; import { useVaultStore } from "../../store/vaultStore"; import { bufferKey, useCodeStore } from "../../store/codeStore"; -import { VaultFileHeader, RevealButton } from "./VaultFileHeader"; +import { VaultFileHeader } from "./VaultFileHeader"; import { CodeFileBar } from "../code/CodeFileBar"; import { useVaultEntryState } from "./useVaultEntry"; -import { buttonVariants } from "../ui/button"; /** Bytes, in the unit a person would say out loud. */ function formatSize(bytes: number): string { @@ -29,36 +29,6 @@ function formatSize(bytes: number): string { return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[i]}`; } -/** A centered dead end with one honest sentence and a way out to Finder. */ -function NoPreview({ - path, - icon, - title, - detail, -}: { - path: string; - icon: React.ReactNode; - title: string; - detail: string; -}) { - const canReveal = useVaultStore((s) => !!s.endpoint && !s.isRemote); - return ( -
- {icon} -
{title}
-
{detail}
- {canReveal && ( - - Show in Finder - - )} -
- ); -} - // The editor is its own chunk: nobody who only browses images pays for // CodeMirror. Files prewarms it once the browser is idle, so the first source // file opens without waiting on the download. @@ -99,7 +69,10 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: // asked yet" never flashes as "couldn't read", and a file that returns (an // add or change event) is read again. const readKey = `${path}@${entry?.mtime ?? ""}`; - const [failedRead, setFailedRead] = useState(null); + // The last failed read: which version of the entry, and why (a status a + // person can act on). Retry clears it and asks again. + const [failedRead, setFailedRead] = useState<{ key: string; reason: string } | null>(null); + const [attempt, setAttempt] = useState(0); useWatchEffect(() => { if (kind !== "text" || body) return; const store = useVaultStore.getState(); @@ -109,18 +82,24 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: ? store.loadTextBody(path, { maxBytes: CODE_EDITOR_MAX_BYTES }) : null; void read?.then( - () => { + (reason) => { const s = useVaultStore.getState(); - if (!s.bodies[path] && !s.loadingPaths[path]) setFailedRead(readKey); + if (!s.bodies[path] && !s.loadingPaths[path]) setFailedRead({ key: readKey, reason: reason ?? "Unreadable" }); }, - () => setFailedRead(readKey), + (e) => setFailedRead({ key: readKey, reason: readFailureLabel(e) }), ); - }, [kind, readKey, !!body, endpoint, isRemote]); + }, [kind, readKey, !!body, endpoint, isRemote, attempt]); // No daemon and none coming: no read will run, so say so rather than load - // forever. A cached boot is not that: the daemon is still being reached (the - // page says so in its banner), and the read runs once the endpoint lands. + // forever. A cached boot is not that: the daemon is still being reached, and + // the read runs once the endpoint lands (CodeFileView marks a long wait). const unreachable = !isRemote && !endpoint && connection === "no-daemon"; - const readFailedRaw = !body && !unsaved && (failedRead === readKey || unreachable); + const failReason = failedRead?.key === readKey ? failedRead.reason : unreachable ? "No daemon" : null; + const readFailedRaw = !body && !unsaved && failReason !== null; + const retryRead = () => { + setFailedRead(null); + if (unreachable) void useVaultStore.getState().reconnect(); + else setAttempt((n) => n + 1); + }; const missing = entryState === "missing"; // A text path with nothing on disk, in a vault this machine writes: the // editor stays (CodeFileView opens an empty buffer under that name, created @@ -129,12 +108,7 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: const readFailed = !newFile && readFailedRaw; if (missing && !newFile && !(kind === "text" && unsaved)) { - return ( -
- -
This file does not exist.
-
- ); + return } title="Not on disk" />; } const assetSrc = @@ -143,11 +117,11 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: const renderBody = () => { if (tooLarge) { return ( - } - title="Too large to preview" - detail={`${formatSize(size)} — open it in your editor instead.`} + title="Too large" + detail={`${formatSize(size)} · limit ${formatSize(kind === "text" ? CODE_EDITOR_MAX_BYTES : VAULT_MAX_PREVIEW_BYTES)}`} /> ); } @@ -175,17 +149,23 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: } // Only the scan's own size can tell "empty" from "we don't have it": // calling a failed read "empty" would be a quiet lie about the file. - return ( -
- {size === 0 ? "This file is empty." : "Couldn't read this file."} -
+ return size === 0 ? ( + } title="Empty file" /> + ) : ( + } + title="Couldn't read" + detail={failReason ?? undefined} + onRetry={retryRead} + /> ); } return ( - } - title="No preview for this file type" + title="No preview" detail={formatSize(size)} /> ); @@ -194,8 +174,9 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: // A text file fills the pane and scrolls inside the editor, which renders // only what is on screen; everything else scrolls as a page. One compact row // names the file; the editor owns the rest of the height. A text file keeps - // this layout while its body loads, so the editor is never rebuilt. - if (kind === "text" && !tooLarge && !readFailed) { + // this layout while its body loads, and when it cannot be shown, so the + // breadcrumbs, reveal and bookmark stay put. + if (kind === "text") { return (
@@ -206,7 +187,7 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: return (
-
+
{renderBody()}
diff --git a/packages/web/components/vault/VaultScopeLine.tsx b/packages/web/components/vault/VaultScopeLine.tsx index 043f5693b1..8d74ed9460 100644 --- a/packages/web/components/vault/VaultScopeLine.tsx +++ b/packages/web/components/vault/VaultScopeLine.tsx @@ -74,7 +74,7 @@ export function VaultScopeLine({ return (
diff --git a/packages/web/components/vault/useVaultSidePanel.ts b/packages/web/components/vault/useVaultSidePanel.ts index 43418d7b14..005ddbc37d 100644 --- a/packages/web/components/vault/useVaultSidePanel.ts +++ b/packages/web/components/vault/useVaultSidePanel.ts @@ -1,6 +1,7 @@ import { useRef, useState } from "react"; import { usePanelRef } from "react-resizable-panels"; import { useWatchEffect } from "../../hooks/useWatchEffect"; +import { useOnRequest } from "../../hooks/useOnRequest"; import { collapsePanelSoon } from "../../lib/vault/collapsePanelSoon"; import { useVaultStore } from "../../store/vaultStore"; @@ -20,13 +21,7 @@ export function useVaultSidePanel(inSplitPane: boolean, showGraph: boolean, conn const [paneRightPanelOpen, setPaneRightPanelOpen] = useState(false); const rightPanelOpen = inSplitPane ? paneRightPanelOpen : storeRightPanelOpen; const setRightPanelOpen = inSplitPane ? setPaneRightPanelOpen : setStoreRightPanelOpen; - const tagPaneRequest = useVaultStore((s) => s.tagPaneRequest); - const seenTagPaneRequest = useRef(tagPaneRequest); - useWatchEffect(() => { - if (seenTagPaneRequest.current === tagPaneRequest) return; - seenTagPaneRequest.current = tagPaneRequest; - setRightPanelOpen(true); - }, [tagPaneRequest]); + useOnRequest(useVaultStore((s) => s.tagPaneRequest), () => setRightPanelOpen(true)); const sidePanelRef = usePanelRef(); const sideAppliedRef = useRef(null); useWatchEffect(() => { diff --git a/packages/web/hooks/useJumpToDecisionAsk.ts b/packages/web/hooks/useJumpToDecisionAsk.ts index 9821f85eb5..48c62125e2 100644 --- a/packages/web/hooks/useJumpToDecisionAsk.ts +++ b/packages/web/hooks/useJumpToDecisionAsk.ts @@ -4,6 +4,7 @@ import { api } from "@codecast/convex/convex/_generated/api"; import { useInboxStore, isConvexId, isSessionHidden } from "../store/inboxStore"; import { findDecisionAnchorMessage } from "../lib/decisionQueue"; import { useOpenSession } from "./useOpenSession"; +import { requestThreadView } from "../lib/decisionOpenRegistry"; /** Where a decision was asked: the `cast decide` call's message, found in the * loaded rows or, when it is older than them, by the server from the decision @@ -56,6 +57,8 @@ export function useJumpToDecisionAsk( const row = store.sessions[conversationId]; if (row && (isSessionHidden(row) || row.inbox_killed_at)) store.restoreSession(conversationId); if (row) store.adoptSession(conversationId); + // The person asked for the conversation: its decision card folds so the thread shows. + requestThreadView(conversationId); openSession(conversationId); // The ask's message is scrolled to only while the view is on this session: // an open diverted elsewhere (a background tab, another window) leaves no diff --git a/packages/web/hooks/useSessionLineMessage.ts b/packages/web/hooks/useSessionLineMessage.ts new file mode 100644 index 0000000000..3d8761f981 --- /dev/null +++ b/packages/web/hooks/useSessionLineMessage.ts @@ -0,0 +1,92 @@ +import { useState } from "react"; +import { useConvex, type ConvexReactClient } from "convex/react"; +import { api } from "@codecast/convex/convex/_generated/api"; +import { useWatchEffect } from "./useWatchEffect"; + +// A message named by session and line (`jx72x09:3091`) resolved to its +// message id. The server scans the session up to the line, so every line one +// render cites for a session goes out in one call (lines asked in the same +// tick are batched), and an answer is kept for the life of the tab and in +// localStorage: a line names the same message once the session has grown past +// it, so a reload reads the id without scanning again. + +type Answer = { messageId: string | null }; + +const STORAGE_PREFIX = "cc:msgline:"; +const answers = new Map(); +const listeners = new Map void>>(); +const queued = new Map>(); +let flushTimer: ReturnType | null = null; + +const keyOf = (session: string, line: number) => `${session}:${line}`; + +function readStored(key: string): Answer | undefined { + try { + const raw = typeof localStorage !== "undefined" ? localStorage.getItem(STORAGE_PREFIX + key) : null; + return raw ? { messageId: raw } : undefined; + } catch { + return undefined; + } +} + +function settle(key: string, answer: Answer) { + answers.set(key, answer); + if (answer.messageId) { + try { + localStorage.setItem(STORAGE_PREFIX + key, answer.messageId); + } catch {} + } + listeners.get(key)?.forEach((fn) => fn()); +} + +function flush(client: ConvexReactClient) { + flushTimer = null; + const batch = [...queued]; + queued.clear(); + for (const [session, lineSet] of batch) { + const lines = [...lineSet]; + client + .action(api.messageLines.resolve, { session, lines }) + .then((res) => { + for (const line of lines) settle(keyOf(session, line), { messageId: res.ids[String(line)] ?? null }); + }) + .catch(() => { + // Unresolved stays unknown (not cached), so the next mount asks again. + for (const line of lines) listeners.get(keyOf(session, line))?.forEach((fn) => fn()); + }); + } +} + +function request(client: ConvexReactClient, session: string, line: number) { + const set = queued.get(session) ?? new Set(); + set.add(line); + queued.set(session, set); + if (!flushTimer) flushTimer = setTimeout(() => flush(client), 0); +} + +/** The id of the message at `line` of `session`: undefined while resolving, null when there is none or it is not readable. */ +export function useSessionLineMessage(session: string | null, line: number | null): string | null | undefined { + const client = useConvex(); + const key = session && line ? keyOf(session, line) : null; + const known = () => { + if (!key) return undefined; + const hit = answers.get(key) ?? readStored(key); + if (hit && !answers.has(key)) answers.set(key, hit); + return hit?.messageId; + }; + const [id, setId] = useState(known); + useWatchEffect(() => { + if (!key || !session || !line) return; + const update = () => setId(known()); + const set = listeners.get(key) ?? new Set(); + set.add(update); + listeners.set(key, set); + if (answers.has(key)) update(); + else request(client, session, line); + return () => { + set.delete(update); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, client]); + return id; +} diff --git a/packages/web/lib/__tests__/decisionQueueKeys.test.ts b/packages/web/lib/__tests__/decisionQueueKeys.test.ts index 357bf09594..d9e42dbcc9 100644 --- a/packages/web/lib/__tests__/decisionQueueKeys.test.ts +++ b/packages/web/lib/__tests__/decisionQueueKeys.test.ts @@ -51,10 +51,10 @@ describe("stand-down: inputs that are not the card's own box", () => { }); describe("the card's own free-text box", () => { - test("Enter asks with the words; ⌘ or Ctrl with Enter answers with them", () => { - expect(routeQueueKey(key("Enter"), ctx({ editing: true, inOwnFreeTextBox: true }))).toEqual({ kind: "commit-free-text", answer: false }); - expect(routeQueueKey(key("Enter", { metaKey: true }), ctx({ editing: true, inOwnFreeTextBox: true }))).toEqual({ kind: "commit-free-text", answer: true }); - expect(routeQueueKey(key("Enter", { ctrlKey: true }), ctx({ editing: true, inOwnFreeTextBox: true }))).toEqual({ kind: "commit-free-text", answer: true }); + test("Enter, or ⌘ or Ctrl with Enter, sends the words", () => { + expect(routeQueueKey(key("Enter"), ctx({ editing: true, inOwnFreeTextBox: true }))).toMatchObject({ kind: "commit-free-text" }); + expect(routeQueueKey(key("Enter", { metaKey: true }), ctx({ editing: true, inOwnFreeTextBox: true }))).toMatchObject({ kind: "commit-free-text" }); + expect(routeQueueKey(key("Enter", { ctrlKey: true }), ctx({ editing: true, inOwnFreeTextBox: true }))).toMatchObject({ kind: "commit-free-text" }); // A chord in any other box is that box's. expect(routeQueueKey(key("Enter", { metaKey: true }), ctx({ editing: true, inOwnFreeTextBox: false }))).toBeNull(); }); diff --git a/packages/web/lib/__tests__/editorPaletteCommands.test.ts b/packages/web/lib/__tests__/editorPaletteCommands.test.ts index 0411967ce6..cf2cb591d2 100644 --- a/packages/web/lib/__tests__/editorPaletteCommands.test.ts +++ b/packages/web/lib/__tests__/editorPaletteCommands.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { CODE_COMMAND_IDS } from "../code/commands"; -import { EDITOR_PALETTE_COMMANDS, editorCommandsLead } from "../editorPaletteCommands"; +import { EDITOR_PALETTE_COMMANDS, editorCommandsLead, editorPaletteKey } from "../editorPaletteCommands"; import { formatAcceleratorParts } from "../../shortcuts"; describe("editor palette commands", () => { @@ -20,6 +20,13 @@ describe("editor palette commands", () => { expect(formatAcceleratorParts(quote.editorKey!).length).toBe(2); }); + test("the review commands are offered, each entry under its own key", () => { + const keys = EDITOR_PALETTE_COMMANDS.map(editorPaletteKey); + expect(new Set(keys).size).toBe(keys.length); + const labels = EDITOR_PALETTE_COMMANDS.filter((c) => c.id.startsWith("git.")).map((c) => c.label); + expect(labels).toEqual(["Diff vs HEAD", "Diff against…", "Diff side by side", "Next change", "Previous change", "Peek change", "Revert change"]); + }); + // With Files focused, the words the editor shares with the app's pane // commands lead with the Editor group. test("split, close and search lead with the editor's commands; other words don't", () => { diff --git a/packages/web/lib/__tests__/filesPane.test.ts b/packages/web/lib/__tests__/filesPane.test.ts index 0156dec7de..58a6dbf95a 100644 --- a/packages/web/lib/__tests__/filesPane.test.ts +++ b/packages/web/lib/__tests__/filesPane.test.ts @@ -22,6 +22,8 @@ describe("the editor address", () => { expect(parseCursorTarget(l)).toEqual({ line: 10, column: 3, endLine: 14 }); expect(parseCursorTarget("12-20")).toEqual({ line: 12, column: undefined, endLine: 20 }); expect(parseCursorTarget("12:4")).toEqual({ line: 12, column: 4 }); + // A restored tab names the line at the top of its view too. + expect(parseCursorTarget("380:5@400")).toEqual({ line: 380, column: 5, top: 400 }); // A raw `l` off a URL rides through the ?path= → ?f= rewrite as it came. expect(filesHref({ path: "x.ts", line: "10:3-14" })).toBe("/files?f=x.ts&l=10%3A3-14"); }); @@ -92,14 +94,40 @@ describe("ranges", () => { expect(findTextRange(file, [" return null;"])).toEqual({ line: 2 }); }); + test("findTextRange takes the occurrence nearest a hint line", () => { + const file = "a\n return null;\nb\nc\nd\n return null;\ne\n"; + expect(findTextRange(file, [" return null;"], 5)).toEqual({ line: 6 }); + expect(findTextRange(file, [" return null;"], 1)).toEqual({ line: 2 }); + // A text that occurs once wins wherever the hint is. + expect(findTextRange(file, [" return null;", "d"], 1)).toEqual({ line: 5 }); + }); + test("a diff base maps to the git ref the editor diffs against", () => { expect(gitRefForDiffBase("session", [])).toEqual({ ref: "HEAD", label: "HEAD" }); + // A commit whose hash went unrecorded falls back. expect(gitRefForDiffBase("session", [{ changeType: "commit" }])?.ref).toBe("@merge-base"); expect(gitRefForDiffBase("commit", [{ changeType: "commit" }])?.ref).toBe("HEAD"); expect(gitRefForDiffBase("branch", [])?.ref).toBe("@merge-base"); expect(gitRefForDiffBase("turn", [])).toBeNull(); }); + test("a trunk session's refs come from its own commits, not the branch", () => { + // Committed and pushed on main: the merge base with origin would be its + // own last commit, and the diff would read "No changes". + const pushed = [{ changeType: "edit" }, { changeType: "commit", commitHash: "aaaa111" }, { changeType: "edit" }, { changeType: "commit", commitHash: "bbbb222" }]; + expect(gitRefForDiffBase("session", pushed)).toEqual({ ref: "aaaa111^", label: "Session base" }); + expect(gitRefForDiffBase("commit", pushed)).toEqual({ ref: "bbbb222", label: "Last commit" }); + expect(gitRefForDiffBase("branch", pushed)?.ref).toBe("@merge-base"); + }); + + test("another session's later commits do not move this session's last commit", () => { + // Only this session's changes are listed: someone else committing on top + // leaves "Commit" at this session's own commit, never HEAD. + const mine = [{ changeType: "write" }, { changeType: "commit", commitHash: "cccc333" }, { changeType: "edit" }]; + expect(gitRefForDiffBase("commit", mine)?.ref).toBe("cccc333"); + expect(gitRefForDiffBase("session", mine)?.ref).toBe("cccc333^"); + }); + test("localCheckoutFile picks this machine's worktree on the ref", () => { const checkouts = [ { root: "/m/app", device_id: "other", mine: true, worktrees: [{ path: "/m/app", main: true }] }, diff --git a/packages/web/lib/__tests__/inboxRouting.test.ts b/packages/web/lib/__tests__/inboxRouting.test.ts index 8606dd0051..2cde2353a2 100644 --- a/packages/web/lib/__tests__/inboxRouting.test.ts +++ b/packages/web/lib/__tests__/inboxRouting.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "bun:test"; -import { isInboxRoute, isInboxSessionView, pageOwnsRailHighlight, railPointerOnNavigate, resolveSessionSelectKind, sessionListActiveIdOf } from "../inboxRouting"; +import { isInboxRoute, isInboxSessionView, railPointerOnNavigate, resolveSessionSelectKind, sessionListActiveIdOf } from "../inboxRouting"; // The rail keeps this one row visible whatever its membership, so it must be // the session on stage and nothing else: a teammate's shared session stayed in @@ -34,22 +34,6 @@ describe("inboxRouting", () => { }); }); -// The decision queue writes the rail pointer itself; the layout's -// leave-the-inbox carry-over must not overwrite it (it did: the queue's effect -// commits first, the layout's default landed on top, and the rail highlighted -// the inbox's conversation instead of the question). -describe("pageOwnsRailHighlight", () => { - it("is the Decisions page, and nothing else", () => { - expect(pageOwnsRailHighlight("/decisions")).toBe(true); - expect(pageOwnsRailHighlight("/decisions/sd-4")).toBe(false); - expect(pageOwnsRailHighlight("/inbox")).toBe(false); - expect(pageOwnsRailHighlight("/tasks")).toBe(false); - expect(pageOwnsRailHighlight("/conversation/abc")).toBe(false); - expect(pageOwnsRailHighlight(null)).toBe(false); - expect(pageOwnsRailHighlight(undefined)).toBe(false); - }); -}); - // Regression: opening /tasks (or any page with no conversation on the stage) // left a session row lit in the rail, because leaving the inbox copied the // attended conversation into the rail pointer and leaving a conversation page @@ -61,6 +45,7 @@ describe("railPointerOnNavigate", () => { expect(railPointerOnNavigate("/docs")).toBe("clear"); expect(railPointerOnNavigate("/plans")).toBe("clear"); expect(railPointerOnNavigate("/org")).toBe("clear"); + expect(railPointerOnNavigate("/decisions")).toBe("clear"); }); it("keeps it where the surface highlights its own pointer", () => { @@ -68,10 +53,6 @@ describe("railPointerOnNavigate", () => { expect(railPointerOnNavigate("/conversation/abc")).toBe("keep"); expect(railPointerOnNavigate("/conversation/abc", "inbox")).toBe("keep"); }); - - it("leaves the Decisions page alone: its stepper publishes the pointer itself", () => { - expect(railPointerOnNavigate("/decisions")).toBe("keep"); - }); }); describe("resolveSessionSelectKind", () => { diff --git a/packages/web/lib/__tests__/stage.test.ts b/packages/web/lib/__tests__/stage.test.ts index edd37544cf..048f0d1f4f 100644 --- a/packages/web/lib/__tests__/stage.test.ts +++ b/packages/web/lib/__tests__/stage.test.ts @@ -2,7 +2,7 @@ import { replaceGlobals } from "../../test-helpers/globals"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "bun:test"; import { useInboxStore, type AppTab } from "../../store/inboxStore"; import { besideLeafId, leavesOf, seedLeafId } from "../../store/stageSplit"; -import { openBeside, openBrowserPane, openSessionInFocusedPane, paneSessionId, performStageDrop, stageRenderLayout } from "../stage"; +import { openBeside, openBrowserPane, openSessionInFocusedPane, paneSessionId, performStageDrop, sessionPanePath, stageLeafSession, stageRenderLayout } from "../stage"; import { parseBrowserRoute } from "../browserPane"; // performStageDrop is the one entry point every drag source funnels into; @@ -265,6 +265,14 @@ describe("openBeside — the reused Option-click target", () => { expect(t.path).toBe("/tasks"); }); + it("a conversation already beside moves to the message instead of opening twice", () => { + const id = "jx78ksdh85pw088a1d2ce6ndgx83z42a"; + expect(openBeside(sessionPanePath(id))).toBe(true); + expect(openBeside(sessionPanePath(id, "m9"))).toBe(true); + const paths = leavesOf(activeTab().layout!).map((l) => l.path); + expect(paths).toEqual(["/tasks", `/conversation/${id}#msg-m9`]); + }); + it("a path already on stage opens nothing and moves nothing", () => { state().stageInsertLeaf("root", "right", "/docs"); const before = activeTab(); @@ -376,3 +384,16 @@ describe("paneSessionId", () => { expect(paneSessionId("/conversation/3f2c9a1e-7b1d-4c55-9a0e-1c2d3e4f5a6b")).toBeNull(); }); }); + +describe("stageLeafSession", () => { + const id = "jx78ksdh85pw088a1d2ce6ndgx83z42a"; + it("a leaf at a message is that conversation, opened at the message", () => { + expect(sessionPanePath(id, "m1")).toBe(`/conversation/${id}#msg-m1`); + expect(stageLeafSession(sessionPanePath(id, "m1"))).toEqual({ sessionId: id, messageId: "m1" }); + expect(stageLeafSession(sessionPanePath(id))).toEqual({ sessionId: id, messageId: undefined }); + }); + it("keeps share links and short ids page entries", () => { + expect(stageLeafSession(`/conversation/${id}?share=t#msg-m1`)).toBeNull(); + expect(stageLeafSession("/conversation/jx7etg8#msg-m1")).toBeNull(); + }); +}); diff --git a/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts b/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts index aec5c87320..16b42bce22 100644 --- a/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts +++ b/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { existsSync, readFileSync } from "node:fs"; -import { dirname, join, relative, resolve } from "node:path"; +import { join } from "node:path"; +import { ALIASES, WEB, rel, walk } from "../../test-helpers/importGraph"; // The standalone boots (src/shareBoot.tsx: the share pages and a guest's // /meet page) exist so that a stranger's page carries nothing of the app: no @@ -17,61 +17,8 @@ import { dirname, join, relative, resolve } from "node:path"; // runs, which is how a module the guest never exercises (the error reporter // behind notificationDelivery, say) stays out of what the page loads. -const WEB = resolve(import.meta.dir, "../.."); -const ALIASES: Record = { - "next/navigation": "src/compat/next-navigation.ts", - "next/link": "src/compat/next-link.tsx", -}; const FORBIDDEN = [/^store\//, /^lib\/calls\/callManager\.ts$/, /^src\/compat\/next-navigation\.ts$/]; -const IMPORT_RE = /(?:^|[\s;])(?:import|export)\s+(type\s+)?(?:[^'"]*?\sfrom\s+)?["']([^"']+)["']/g; - -function resolveFile(base: string): string | null { - for (const ext of ["", ".ts", ".tsx", "/index.ts", "/index.tsx"]) { - const p = base + ext; - if (existsSync(p) && !p.endsWith("/")) { - try { - readFileSync(p); - return p; - } catch { - // a directory - } - } - } - return null; -} - -function resolveSpec(from: string, spec: string): string | null { - if (ALIASES[spec]) return join(WEB, ALIASES[spec]); - if (spec.startsWith("@/")) return resolveFile(join(WEB, spec.slice(2))); - if (spec.startsWith(".")) return resolveFile(resolve(dirname(from), spec)); - return null; // a package: never the app -} - -/** Every web file the entry reaches, with the chain that reached it. */ -function walk(entry: string): Map { - const seen = new Map([[entry, [rel(entry)]]]); - const queue = [entry]; - while (queue.length) { - const file = queue.shift()!; - if (!/\.(ts|tsx)$/.test(file)) continue; - const src = readFileSync(file, "utf8"); - for (const m of src.matchAll(IMPORT_RE)) { - if (m[1]) continue; // `import type` erases - const spec = m[2]; - const target = resolveSpec(file, spec); - if (!target || seen.has(target)) continue; - seen.set(target, [...seen.get(file)!, rel(target)]); - queue.push(target); - } - } - return seen; -} - -function rel(p: string): string { - return relative(WEB, p); -} - function leaks(entry: string): string[] { const out: string[] = []; for (const [file, chain] of walk(join(WEB, entry))) { diff --git a/packages/web/lib/calls/callManager.ts b/packages/web/lib/calls/callManager.ts index c50556be6b..631b7ddf0e 100644 --- a/packages/web/lib/calls/callManager.ts +++ b/packages/web/lib/calls/callManager.ts @@ -57,6 +57,8 @@ import { import { shouldRejoinAfterDisconnect, shouldYieldCallOnDisconnect } from "./callHandoff"; import { track as trackEvent } from "../analytics"; import { bindCallCursors } from "./callCursors"; +import { attachAudio, audioElementCount, clearAudio, detachAudio, markAudioBlocked, playRoomAudio, rebuildRoomAudio, roomBlocked, startAudioWatch } from "./remoteAudio"; +import { announceScreenShare } from "./shareBanner"; import { focusExistingHuddle, huddleInOtherWindow } from "./huddleWindow"; import { getMicLevel, startLevelMeter, stopLevelMeter } from "./localMicLevel"; import { peekOsPermissions, permissionHint, refreshOsPermissions } from "../osPermissions"; @@ -85,8 +87,6 @@ let callGen = 0; // The room a PERSON joined on purpose (JoinOpts.intent), if any. Auto-scribe // reads it: a walkie's background seat never transcribes. let deliberateRoomKey: string | null = null; -let audioHost: HTMLElement | null = null; -const audioEls = new Map(); // React binds the live Convex client here (useCallSync); everything below // no-ops politely until it has. @@ -129,16 +129,6 @@ function setCall(patch: Parameters["se useInboxStore.getState().setCallState(patch); } -function ensureAudioHost(): HTMLElement { - if (!audioHost) { - audioHost = document.createElement("div"); - audioHost.style.display = "none"; - audioHost.dataset.role = "huddle-audio"; - document.body.appendChild(audioHost); - } - return audioHost; -} - let tilesSnapshot: ParticipantTile[] = []; const tileSubscribers = new Set<() => void>(); @@ -192,7 +182,9 @@ async function controlJoin(roomKey: string, opts?: { walkieJoin?: boolean; priva // Only ever true, never false: the stamp says a conversation started here // and nothing takes that back but leaving. ...(opts?.walkieJoin || walkieJoinedSeat === roomKey ? { walkie_join: true } : {}), - ...(opts?.private ? { private: true } : {}), + // Either choice is sent when one was made: absent lets the server pick + // the room's default (private for a people room). + ...(opts?.private !== undefined ? { private: opts.private } : {}), ...(opts?.intent === "deliberate" ? { deliberate: true } : {}), }); } @@ -240,27 +232,6 @@ function stopHeartbeat() { heartbeatTimer = null; } -function attachAudio(track: RemoteTrack, participantId: string) { - if (track.kind !== Track.Kind.Audio) return; - // Idempotent: the prewarm sweep below and the TrackSubscribed listener can - // both reach the same track, and a second element would play the voice twice. - if (audioEls.has(`${participantId}:${track.sid}`)) return; - const el = track.attach(); - el.dataset.participant = participantId; - ensureAudioHost().appendChild(el); - audioEls.set(`${participantId}:${track.sid}`, el); -} - -function detachAudio(track: RemoteTrack, participantId: string) { - const key = `${participantId}:${track.sid}`; - const el = audioEls.get(key); - track.detach().forEach((e) => e.remove()); - if (el) { - el.remove(); - audioEls.delete(key); - } -} - /** Is this LiveKit identity (a user id, per `mintAccessToken`) a live seat in * the room's occupancy as the store holds it? Prewarm rows never reach the * store: `getRoomOccupancy` projects `liveMembers`, which drops them. */ @@ -297,8 +268,7 @@ function teardownMedia() { stopHeartbeat(); stopSeatSoundWatch(); stopLevelMeter(); - for (const el of audioEls.values()) el.remove(); - audioEls.clear(); + clearAudio(); if (room) { room.removeAllListeners(); void room.disconnect(); @@ -600,6 +570,17 @@ async function joinCallHere(roomKey: string, opts?: JoinOpts): Promise { // different event from unsubscribe and must also clear the tile — without // this a stopped share leaves a dead hero on the stage. r.on(RoomEvent.TrackUnpublished, () => rebuildTiles()); + // The browser refused to play an element until the person interacts + // (autoplay). LiveKit reports it here; the stage offers Turn on sound, and + // the next click anywhere in the window unblocks it too. + r.on(RoomEvent.AudioPlaybackStatusChanged, () => { + if (self === room) markAudioBlocked(roomBlocked(self)); + }); + // A teammate starting a share is worth a system banner (lib/calls/shareBanner). + r.on(RoomEvent.TrackPublished, (pub, participant: RemoteParticipant) => { + if (self !== room || pub.source !== Track.Source.ScreenShare) return; + announceScreenShare({ roomKey, identity: participant.identity, name: participant.name, trackSid: pub.trackSid }); + }); // Teammates' pointers over a screen share, on the data channel. bindCallCursors(r); r.on(RoomEvent.TrackMuted, rebuildTiles); @@ -751,6 +732,8 @@ async function joinCallHere(roomKey: string, opts?: JoinOpts): Promise { if (superseded(r)) return; startLevelMeter(room); setCall({ phase: "connected", reconnecting: false }); + markAudioBlocked(roomBlocked(r)); + startAudioWatch(() => room); if (!rejoin) soundCallJoin(); startHeartbeat(roomKey); rebuildTiles(); @@ -1142,7 +1125,21 @@ export function getRoom(): Room | null { * test that pins that case, and for a console checking the same thing by * hand. */ export function getAudioElementCount(): number { - return audioEls.size; + return audioElementCount(); +} + +/** Unblock the room's sound after the browser held it (autoplay). Must run + * inside a user gesture to work. */ +export async function startCallAudio(): Promise { + if (voiceHostElsewhere() && !room && (await sendVoiceCommand("startCallAudio"))) return; + await playRoomAudio(room); +} + +/** Rebuild every voice's element: the person's own fix for a voice they + * cannot hear. */ +export async function repairCallAudio(): Promise { + if (voiceHostElsewhere() && !room && (await sendVoiceCommand("repairCallAudio"))) return; + await rebuildRoomAudio(room); } /** The attach path itself, for the test that proves it is idempotent — a track @@ -1614,6 +1611,10 @@ export async function runCallCommand(cmd: string, args: unknown[]): Promise