CodeNomad/packages/ui/tests/browser/project-git-lifecycle.test.ts
Pascal André a5efdefc8d
feat(missions): resume recurring Missions after OpenCode restarts with native schedules (#1259)
Closes #926.

## What changes

Recurring Missions now survive OpenCode restarts (update, crash and
relaunch, reboot) without a manual **Resume**, and the scheduler offers
more than "once a day at a fixed time".

- **Native schedules.** OpenCode's own scheduler
(`experimental.schedules`, OpenCode 2.2.3+) owns the calendar; Missions
decides whether a passage may run (CAS admission, no duplicates,
Pause/Stop, errors and uncertain states stay manual). A dedicated
technical conversation with a local no-op model carries the wake, so
wakes, titles and compaction make no provider HTTP requests.
- **Richer scheduling**, in one collapsed **Scheduling** section of the
Create/Edit editor (default: once, immediately, no condition): date,
delay, interval (≥15 min), daily, chosen weekdays, up to eight times a
day, day of month, native cron; optional end date/duration and a maximum
number of launched passages; five event conditions (another schedule
succeeds, a one-time Mission completes, new local commits, a new message
in a followed conversation, explicit files change). Up to five upcoming
dates are previewed in the saved IANA zone.
- **Created paused, started with Play.** Everything is editable before
the first launch; after it, edits follow the approved matrix (future
parameters between passages, objective/notes journaled during a
passage).
- **Keep OpenCode running.** A Preferences setting supervises the shared
OpenCode service through the OS (Windows Task Scheduler with a periodic
recovery task, macOS LaunchAgent, Linux systemd user unit with
lingering, WSL from Windows). ON by default at the first Play unless OFF
was saved; OFF removes supervision without stopping OpenCode; a live
service is never killed or duplicated.
- **Existing daily schedules** keep their path and controls; no
migration.
- Help (English and nine translations) and dev-docs are updated.

## Validation

- Typechecks (4 workspaces); server Missions/host-lifetime suites; UI
unit tests 1945/1945; help 31/31 and build.
- Real isolated OpenCode services (2.2.5, minimum 2.2.3): resting
schedule resumes after service restart with no client and no Resume; 32
real passages with history/quota/phase preserved; concurrent wakes admit
once; DST and catch-up for every frequency type; forced local
auto-compaction and restart during maintenance with zero provider HTTP;
real upgrade 2.2.3 → 2.2.5.
- OS supervision on Windows, WSL, Ubuntu VM (two real reboots, healthy
before login; OFF without a session) and macOS VM (Aqua session,
crashes, OFF/adoption). On the final bundle: two real periodic Windows
recovery relaunches; WSL OFF/Retry on a live HTTP 500 service keeps the
same process.
- Windows Electron and Tauri packages run in private profiles: paused
creation, nine frequencies, preview.
- Full browser suite: 956/957 in the last tier; the failure is
`directory-browser.test.ts` (folder picker timeout), unchanged by this
branch, and that file passes 20/20 on rerun. Earlier dev-baseline runs
on the same machine also lost module loads to
`net::ERR_NO_BUFFER_SPACE`.

## Known limits (not qualified in this PR)

- macOS reboot followed by a real login, and a Windows host reboot/logon
(needs a disposable bench).
- Real screen-reader output (keyboard, ARIA and RTL checks pass).
- Linux/macOS desktop packages.
- OpenCode's background *pre*-compaction never applies to the technical
wake conversations: their local model reports zero tokens, below the
native minimum. Their automatic local compaction is qualified.

## Follow-up

Integration with native `/goal` comes in a separate PR.
2026-11-01 14:40:24 +01:00

176 lines
10 KiB
TypeScript

import assert from "node:assert/strict"
import { before, after, test } from "node:test"
import { fileURLToPath } from "node:url"
import { borrowFixture } from "./fixture-borrow"
import { chromium, type Browser, type Page } from "playwright"
import { armFixtureNavigationBudget } from "./fixture-navigation-budget"
import { observeHeaderFixture } from "./header-fixture-diagnostics"
let browser: Browser, url: string
before(async () => {
const fixture = await borrowFixture({
name: "project-git-lifecycle",
routes: [
{ path: "/fixture", html: "<html><body><div id=\"root\"></div><script type=\"module\" src=\"/tests/browser/fixtures/project-git-lifecycle.tsx\"></script></body></html>" },
],
})
url = fixture.url
browser = await chromium.launch({ executablePath: process.env.CODENOMAD_BROWSER_PATH || undefined })
armFixtureNavigationBudget(browser)
})
after(async () => { await browser?.close() })
async function setup(page: Page, blocked?: Promise<void>) {
const requests: string[] = [], errors: string[] = []
const observer = observeHeaderFixture(page)
await observer.install()
page.on("pageerror", error => errors.push(error.message))
await page.route(url => url.pathname.startsWith("/api/") || url.pathname.startsWith("/workspaces/"), async route => {
const path = new URL(route.request().url()).pathname
requests.push(path)
if (path.endsWith("/git-status") || path.endsWith("/vcs/status")) await blocked
const json = path.endsWith("/git-status") ? [{ path: "file.txt", originalPath: null,
stagedStatus: null, stagedAdditions: 0, stagedDeletions: 0, unstagedStatus: "modified", unstagedAdditions: 1, unstagedDeletions: 0 }]
: path.endsWith("/git-diff") ? { before: "old\n", after: "new\n", isBinary: false }
: { data: [] }
await route.fulfill({ json }).catch(() => {})
})
try {
await page.goto(url)
await page.locator('[data-project="first"]').waitFor()
} catch (error) {
await observer.diagnose(message => console.error(message)).catch(() => undefined)
throw error
} finally { observer.detach() }
return { requests, errors }
}
test("Git transport mocks preserve module paths containing an api segment", async () => {
const page = await browser.newPage()
try {
await page.route("**/__fixture_modules/api/bootstrap.js", route => route.fulfill({ contentType: "text/javascript", body: "export const ready = true" }))
const { requests } = await setup(page)
assert.equal(await page.evaluate(async () => {
const modulePath = "/__fixture_modules/api/bootstrap.js"
return (await import(modulePath)).ready
}), true)
assert.equal(requests.includes("/__fixture_modules/api/bootstrap.js"), false)
} finally { await page.close() }
})
test("metadata and restored tabs preserve shells, Git reads and commit drafts", async () => {
const page = await browser.newPage()
try {
const { requests, errors } = await setup(page)
await page.waitForFunction(() => document.querySelector('[data-project="first"] [data-diff]')?.textContent === "new\n")
await page.getByRole("textbox", { name: "Commit first", exact: true }).fill("unfinished commit")
const firstReads = requests.filter(path => path.endsWith("/git-status")).length
await page.evaluate(() => {
const f = (window as any).fixture
for (let i = 0; i < 8; i++) { f.add(`other-${i}`); f.update("first", `name-${i}`) }
})
assert.equal(await page.locator('[data-project="first"] [data-name]').textContent(), "name-7")
assert.equal(await page.getByRole("textbox", { name: "Commit first", exact: true }).inputValue(), "unfinished commit")
assert.equal(await page.evaluate(() => (window as any).fixture.mounts.first), 1)
assert.equal(requests.filter(path => path.endsWith("/git-status")).length, firstReads)
assert.ok(!requests.some(path => path.includes("other-")), "hidden projects must not fetch Git")
await page.evaluate(() => (window as any).fixture.select("other-0"))
await page.waitForFunction(() => document.querySelector('[data-project="other-0"] [data-diff]')?.textContent === "new\n")
await page.evaluate(() => (window as any).fixture.select("first"))
await page.waitForFunction(() => document.querySelector('[data-project="first"]')?.getAttribute("data-loading") === "false")
assert.equal(await page.getByRole("textbox", { name: "Commit first", exact: true }).inputValue(), "unfinished commit")
assert.deepEqual(errors, [])
} finally { await page.close() }
})
test("a disposed panel cannot queue a trailing Git refresh or diff after a slow status response", async () => {
const page = await browser.newPage()
await page.clock.install()
let release!: () => void
const blocked = new Promise<void>(resolve => { release = resolve })
try {
const statusRequested = page.waitForRequest(request => new URL(request.url()).pathname.endsWith("/git-status"))
const { requests, errors } = await setup(page, blocked)
await statusRequested
await page.evaluate(() => (window as any).fixture.invalidate("first"))
await page.clock.fastForward(150)
await page.evaluate(() => (window as any).fixture.close("first"))
release()
await page.waitForFunction(() => (window as any).fixture.disposals.first === 1)
assert.equal(requests.filter(path => path.endsWith("/git-status")).length, 1)
assert.ok(!requests.some(path => path.endsWith("/git-diff")))
assert.deepEqual(errors, [])
} finally { release(); await page.close() }
})
test("queued hidden-project Git reads are cancelled before dispatch", async () => {
const page = await browser.newPage()
try {
const { requests, errors } = await setup(page)
await page.waitForFunction(() => document.querySelector('[data-project="first"] [data-diff]')?.textContent === "new\n")
await page.evaluate(() => { const f = (window as any).fixture; f.occupy(); f.add("second"); f.select("second") })
await page.evaluate(() => { const f = (window as any).fixture; f.select("first"); f.release() })
await page.waitForFunction(() => document.querySelector('[data-project="first"]')?.getAttribute("data-loading") === "false")
assert.ok(!requests.some(path => path.includes("/second/")))
assert.deepEqual(errors, [])
} finally { await page.close() }
})
for (const mode of ["deadline", "deactivate"] as const) test(`SDK status releases its real transport and slot on ${mode}`, async () => {
const page = await browser.newPage()
let release!: () => void
const blocked = new Promise<void>(resolve => { release = resolve })
try {
await setup(page)
await page.waitForFunction(() => document.querySelector('[data-project="first"] [data-diff]')?.textContent === "new\n")
await page.route("**/api/vcs/status*", async route => { await blocked; await route.fulfill({ json: [] }).catch(() => {}) })
const requested = page.waitForRequest(r => r.url().includes("/api/vcs/status"))
const aborted = page.waitForEvent("requestfailed", { predicate: r => r.url().includes("/api/vcs/status"), timeout: 10000 })
await page.evaluate(() => { (window as any).refresh = (window as any).fixture.panels.first.refreshGitStatus() })
await requested
if (mode === "deactivate") await page.evaluate(() => (window as any).fixture.deactivate())
await aborted
await page.evaluate(() => (window as any).refresh)
// Both slots must be reusable while the obsolete upstream remains blocked.
await page.evaluate(() => { const f = (window as any).fixture; f.add("second"); f.select("second") })
await page.waitForFunction(() => document.querySelector('[data-project="second"] [data-diff]')?.textContent === "new\n")
} finally { release(); await page.close() }
})
test("explicit refresh cannot launch a new diff after deactivation aborts its status", async () => {
const page = await browser.newPage()
let release!: () => void
const blocked = new Promise<void>(resolve => { release = resolve })
try {
const { requests } = await setup(page)
await page.waitForFunction(() => document.querySelector('[data-project="first"] [data-diff]')?.textContent === "new\n")
const diffs = requests.filter(path => path.endsWith("/git-diff")).length
await page.route(/\/git-status(?:\?|$)/, async route => { await blocked; await route.fulfill({ json: [] }).catch(() => {}) })
const requested = page.waitForRequest(r => new URL(r.url()).pathname.endsWith("/git-status"))
await page.evaluate(() => { (window as any).refresh = (window as any).fixture.panels.first.refreshGitStatus() })
await requested
await page.evaluate(() => (window as any).fixture.deactivate())
await page.evaluate(() => (window as any).refresh)
assert.equal(requests.filter(path => path.endsWith("/git-diff")).length, diffs)
} finally { release(); await page.close() }
})
test("a late commit cannot clear a new worktree draft or refresh its Git selection", async () => {
const page = await browser.newPage()
let release!: () => void
const blocked = new Promise<void>(resolve => { release = resolve })
try {
const { requests } = await setup(page)
await page.waitForFunction(() => document.querySelector('[data-project="first"] [data-diff]')?.textContent === "new\n")
const diffs = requests.filter(path => path.endsWith("/git-diff")).length
await page.route("**/git-commit", async route => { await blocked; await route.fulfill({ json: { ok: true } }) })
const requested = page.waitForRequest(r => r.url().endsWith("/git-commit"))
await page.evaluate(() => { const f = (window as any).fixture; f.panels.first.setGitCommitMessage("old draft"); (window as any).commit = f.panels.first.submitGitCommit() })
assert.ok((await requested).url().includes("/root/"))
await page.evaluate(() => { const f = (window as any).fixture; f.worktree.first("other"); f.panels.first.setGitCommitMessage("new draft") })
release()
await page.evaluate(() => (window as any).commit)
assert.equal(await page.getByRole("textbox", { name: "Commit first", exact: true }).inputValue(), "new draft")
assert.equal(requests.filter(path => path.endsWith("/git-diff")).length, diffs)
} finally { release(); await page.close() }
})