diff --git a/.gitattributes b/.gitattributes
index 9f43f6095a..d575062b44 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -3,3 +3,6 @@ packages/core/src/database/migration.gen.ts linguist-generated
packages/core/src/models-dev/snapshot.txt linguist-generated
packages/core/src/**/*.txt text eol=lf
packages/httpapi-codegen/test/generated/*.ts text eol=lf
+
+# Preserve the audited bytes of the vendored CookieJar bundle on Windows.
+packages/desktop/vendor/cm-ae/** -text
diff --git a/.github/actions/setup-bun/action.yml b/.github/actions/setup-bun/action.yml
index 013b334b56..6f250e2d99 100644
--- a/.github/actions/setup-bun/action.yml
+++ b/.github/actions/setup-bun/action.yml
@@ -20,7 +20,7 @@ runs:
- name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
- node-version: "24"
+ node-version: "24.15"
- name: Get baseline download URL
id: bun-url
@@ -88,6 +88,7 @@ runs:
shell: bash
env:
CM_WPP_SSH_KEY: ${{ inputs.wpp-ssh-key }}
+ GH_TOKEN: ${{ github.token }}
run: |
if [ -z "$CM_WPP_SSH_KEY" ]; then
echo "::error::CM_WPP_SSH_KEY with read access to trmosala/CM-WPP-Bits is required."
@@ -95,7 +96,7 @@ runs:
fi
umask 077
printf '%s\n' "$CM_WPP_SSH_KEY" > "$RUNNER_TEMP/cm-wpp-key"
- curl --fail --silent --show-error https://api.github.com/meta | node -e '
+ curl --fail --silent --show-error --header "Authorization: Bearer $GH_TOKEN" https://api.github.com/meta | node -e '
let data = ""
process.stdin.on("data", chunk => data += chunk)
process.stdin.on("end", () => {
diff --git a/.github/workflows/cookiemonster-desktop.yml b/.github/workflows/cookiemonster-desktop.yml
index 36f1875251..2277396aa6 100644
--- a/.github/workflows/cookiemonster-desktop.yml
+++ b/.github/workflows/cookiemonster-desktop.yml
@@ -87,6 +87,12 @@ jobs:
OPENCODE_CHANNEL: dev
run: bun test --preload ./test/preload.ts --timeout 20000 electron-builder.config.test.ts src/main/macos-user-install.test.ts
+ - name: Verify pinned WPP backend and host contracts
+ timeout-minutes: 3
+ run: |
+ bun run --cwd packages/desktop/wpp/node_modules/@cookiemonster/wpp test
+ bun run --cwd packages/desktop test:wpp
+
- name: Import Developer ID certificate
uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0
with:
@@ -148,6 +154,17 @@ jobs:
cd packages/desktop/dist
shasum -a 256 cookiemonster-mac-arm64.dmg > SHA256SUMS.txt
+ - name: Verify packaged macOS activation with a hidden worker
+ timeout-minutes: 3
+ run: |
+ mount="$RUNNER_TEMP/cm-activation-mount"
+ mkdir "$mount"
+ hdiutil attach packages/desktop/dist/cookiemonster-mac-arm64.dmg -readonly -nobrowse -mountpoint "$mount"
+ trap 'hdiutil detach "$mount"' EXIT
+ mkdir "$RUNNER_TEMP/cm-activation"
+ ditto "$mount/CookieMonster.app" "$RUNNER_TEMP/cm-activation/CookieMonster.app"
+ bun packages/desktop/scripts/check-mac-activation.ts "$RUNNER_TEMP/cm-activation/CookieMonster.app"
+
- name: Upload verified installer
if: ${{ !inputs.publish }}
timeout-minutes: 3
diff --git a/.github/workflows/pr-management.yml b/.github/workflows/pr-management.yml
index b6aa4e589d..ecb1c7b72d 100644
--- a/.github/workflows/pr-management.yml
+++ b/.github/workflows/pr-management.yml
@@ -6,7 +6,7 @@ on:
jobs:
check-duplicates:
- runs-on: blacksmith-4vcpu-ubuntu-2404
+ runs-on: ubuntu-24.04
permissions:
contents: read
pull-requests: write
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index d004db4658..b15c1ae2d2 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -23,7 +23,7 @@ env:
jobs:
affected:
name: affected packages
- runs-on: blacksmith-4vcpu-ubuntu-2404
+ runs-on: ubuntu-24.04
outputs:
app: ${{ steps.packages.outputs.app }}
steps:
@@ -58,9 +58,9 @@ jobs:
matrix:
settings:
- name: linux
- host: blacksmith-4vcpu-ubuntu-2404
+ host: ubuntu-24.04
- name: windows
- host: blacksmith-4vcpu-windows-2025
+ host: windows-2025
runs-on: ${{ matrix.settings.host }}
defaults:
run:
@@ -84,6 +84,23 @@ jobs:
if: runner.os == 'Linux'
run: bun run test:effect-simplification-rules
+ - name: Install Electron for desktop runtime tests
+ working-directory: packages/desktop
+ run: node -e "require(require.resolve('electron/install.js'))"
+
+ - name: Install Chromium for browser unit tests
+ working-directory: packages/app
+ run: bunx playwright install --with-deps chromium
+
+ - name: Install ripgrep for offline core tests
+ run: |
+ if [ "$RUNNER_OS" = "Linux" ]; then
+ sudo apt-get update
+ sudo apt-get install -y ripgrep
+ else
+ choco install ripgrep --yes --no-progress
+ fi
+
- name: Check Effect simplifications
if: runner.os == 'Linux'
run: bun run lint:effect-simplifications
@@ -102,15 +119,23 @@ jobs:
turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}-
turbo-${{ runner.os }}-
+ - name: Initialize installed PowerShell runtime
+ if: runner.os == 'Linux'
+ run: |
+ # Cold PowerShell startup can exceed a unit test's five-second budget.
+ if command -v pwsh > /dev/null; then
+ pwsh -NoLogo -NoProfile -NonInteractive -Command "Write-Output 'PowerShell ready'"
+ fi
+
- name: Run unit tests
timeout-minutes: 20
run: |
- # The runners have four vCPUs, and each Bun test process performs its own concurrent work.
+ # Each package creates concurrent work; serialize packages to bound hosted process pressure.
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
- GITHUB_ACTIONS=false bun turbo test --concurrency=3
+ GITHUB_ACTIONS=false bun turbo test --concurrency=1
exit 0
fi
- GITHUB_ACTIONS=false bun turbo test --affected --concurrency=3
+ GITHUB_ACTIONS=false bun turbo test --affected --concurrency=1
env:
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: ${{ runner.os == 'Windows' && 'true' || 'false' }}
TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }}
@@ -135,7 +160,7 @@ jobs:
TURBO_SCM_HEAD: ${{ github.sha }}
- name: Verify compiled service lifecycle
- if: always()
+ if: ${{ !cancelled() }}
timeout-minutes: 10
working-directory: packages/cli
env:
@@ -145,13 +170,13 @@ jobs:
bun run script/service-smoke.ts
- name: Setup Node build runtime
- if: always()
+ if: ${{ !cancelled() }}
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- name: Verify Node build
- if: always()
+ if: ${{ !cancelled() }}
timeout-minutes: 15
working-directory: packages/cli
env:
@@ -178,9 +203,9 @@ jobs:
matrix:
settings:
- name: linux
- host: blacksmith-4vcpu-ubuntu-2404
+ host: ubuntu-24.04
- name: windows
- host: blacksmith-4vcpu-windows-2025
+ host: windows-2025
runs-on: ${{ matrix.settings.host }}
env:
E2E_ENABLED: ${{ needs.affected.outputs.app == 'true' && github.ref_name != 'dev' && github.head_ref != 'dev' }}
diff --git a/bun.lock b/bun.lock
index 1b8e909115..090a64ef09 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1107,6 +1107,7 @@
"solid-js@1.9.15": "patches/solid-js@1.9.15.patch",
"vite@8.2.2": "patches/vite@8.2.2.patch",
"@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch",
+ "@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch",
"@dnd-kit/dom@0.5.0": "patches/@dnd-kit%2Fdom@0.5.0.patch",
"@ai-sdk/openai-compatible@2.0.41": "patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch",
},
diff --git a/package.json b/package.json
index c703dc6f77..2a841c987c 100644
--- a/package.json
+++ b/package.json
@@ -184,6 +184,7 @@
"@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch",
"ghostty-web@github:anomalyco/ghostty-web#83c0a07": "patches/ghostty-web@0.3.0.patch",
"vite@8.2.2": "patches/vite@8.2.2.patch",
- "@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch"
+ "@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch",
+ "@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch"
}
}
diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts
index a434d07c23..57113c7a7a 100644
--- a/packages/app/component-tests/composer.spec.ts
+++ b/packages/app/component-tests/composer.spec.ts
@@ -96,13 +96,17 @@ for (const direction of ["ltr", "rtl"]) {
).toBeLessThan(1)
await page.keyboard.press("Enter")
// Below the mobile breakpoint the variant picker opens in a bottom drawer instead of a menu.
- await expect(
+
+ const option =
width < 768
? page
.getByRole("dialog", { name: "Choose model variant", exact: true })
.getByRole("button", { name: "high", exact: true })
- : page.getByRole("menuitemradio", { name: "high", exact: true }),
- ).toBeVisible()
+ : page.getByRole("menuitemradio", { name: "high", exact: true })
+
+ await expect(option).toBeVisible()
+ // The mobile drawer starts below the viewport; wait until its options are presented before dismissal.
+ await expect(option).toBeInViewport({ ratio: 1 })
await page.keyboard.press("Escape")
await expect(variant).toBeFocused()
await expect(submit).toBeInViewport()
@@ -110,7 +114,8 @@ for (const direction of ["ltr", "rtl"]) {
await add.click()
await expect(page.getByRole("menuitem", { name: "Images and files" })).toBeVisible()
await page.keyboard.press("Escape")
- expect(await add.boundingBox()).toEqual(fixedAdd)
+ // Menu dismissal restores focus and scroll position after its closing animation.
+ await expect.poll(() => add.boundingBox()).toEqual(fixedAdd)
}
if (alternate !== "none") {
@@ -123,6 +128,36 @@ for (const direction of ["ltr", "rtl"]) {
}
}
+for (const motion of ["no-preference", "reduce"] as const) {
+ story(
+ `returns focus when the mobile variant drawer closes before its opening paint (${motion})`,
+ async ({ mount, page }) => {
+ await page.setViewportSize({ width: 360, height: 720 })
+ await page.emulateMedia({ reducedMotion: motion })
+ const component = await mount("opencode-composer-flow--toolbar-overflow")
+ const variant = component.getByRole("button", { name: "Choose model variant" })
+ await expect(variant).toBeVisible()
+ await page.clock.install({ time: 0 })
+ await page.clock.pauseAt(1000)
+ await variant.focus()
+ await page.keyboard.press("Enter")
+ const drawer = page.getByRole("dialog", { name: "Choose model variant", exact: true })
+ await expect(drawer.getByRole("button", { name: "high", exact: true })).toBeVisible()
+ // No opening animation-frame callback has run when Escape arrives.
+ await page.keyboard.press("Escape")
+ await page.clock.runFor(1000)
+ await expect(drawer).toBeHidden()
+ await expect(variant).toBeFocused()
+ await page.clock.resume()
+ await page.keyboard.press("Enter")
+ await expect(drawer.getByRole("button", { name: "high", exact: true })).toBeInViewport({ ratio: 1 })
+ await page.keyboard.press("Escape")
+ await expect(drawer).toBeHidden()
+ await expect(variant).toBeFocused()
+ },
+ )
+}
+
story("does not mask or pad controls when they fit", async ({ mount }) => {
const component = await mount("opencode-composer-flow--model-and-variant")
const controls = component.locator('[data-slot="composer-controls"]')
diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts
index 87fe50661d..652fae7188 100644
--- a/packages/app/e2e/regression/composer.spec.ts
+++ b/packages/app/e2e/regression/composer.spec.ts
@@ -455,7 +455,7 @@ test("marks a Console provider with its workspace only when it is also connected
await expect(menu.getByText(/Anomaly \//)).toHaveCount(0)
})
-test("shows thinking on hover or a non-default selection while preserving keyboard access", async ({ page }) => {
+test("keeps the effort picker visible while preserving selection and keyboard access", async ({ page }) => {
const { editor: input } = await openSession(page, {
name: "ComposerThinking",
provider: provider({ id: "thinking-model", name: "Thinking Model", variants: { high: {} } }),
@@ -467,13 +467,13 @@ test("shows thinking on hover or a non-default selection while preserving keyboa
await page.mouse.move(0, 0)
await expect(control).toHaveText("default")
- await expect(control).toHaveCSS("opacity", "0")
- await expect(control).toHaveCSS("pointer-events", "none")
+ await expect(control).toHaveCSS("opacity", "1")
+ await expect(control).toHaveCSS("pointer-events", "auto")
await input.hover()
await expect(control).toHaveCSS("opacity", "1")
- // The menu keeps the control visible after the pointer leaves.
+ // The control stays visible while its menu is open.
await control.click()
await expect(option("high")).toBeVisible()
await page.mouse.move(0, 0)
@@ -491,7 +491,7 @@ test("shows thinking on hover or a non-default selection while preserving keyboa
await input.click()
await page.mouse.move(0, 0)
await expect(control).toHaveText("default")
- await expect(control).toHaveCSS("opacity", "0")
+ await expect(control).toHaveCSS("opacity", "1")
// The single-agent fixture has only Add and Model before the thinking trigger.
await page.keyboard.press("Tab")
@@ -507,5 +507,5 @@ test("shows thinking on hover or a non-default selection while preserving keyboa
await page.keyboard.press("Escape")
await expect(control).toBeFocused()
await page.keyboard.press("Tab")
- await expect(control).toHaveCSS("opacity", "0")
+ await expect(control).toHaveCSS("opacity", "1")
})
diff --git a/packages/app/e2e/regression/side-panels.spec.ts b/packages/app/e2e/regression/side-panels.spec.ts
index a41039333b..3daa8e95dd 100644
--- a/packages/app/e2e/regression/side-panels.spec.ts
+++ b/packages/app/e2e/regression/side-panels.spec.ts
@@ -1,4 +1,4 @@
-import { expect, test, type Locator, type Page } from "@playwright/test"
+import { expect, test, type CDPSession, type Locator, type Page } from "@playwright/test"
import { tabKey } from "../utils/app"
import { fileDiff, openSession } from "../utils/workspace"
import { expectSessionTitle } from "../utils/waits"
@@ -96,6 +96,8 @@ test("review and terminal follow the session tab and stay mounted", async ({ pag
})
test("terminal stacks under review by default and spans the bottom when configured", async ({ page }) => {
+ const clock = await page.context().newCDPSession(page)
+ await clock.send("Animation.enable")
await page.setViewportSize({ width: 1400, height: 900 })
// A large nested branch diff; its first file is the sentinel that proves the virtualized tree stays mounted.
@@ -150,10 +152,10 @@ test("terminal stacks under review by default and spans the bottom when configur
// Closing review mid-motion: the terminal grows upward with its bottom fixed and its content top-anchored.
const stacked = await stackGeometry(page)
- await holdTransitions(page)
+ await holdTransitions(page, clock)
await toggle.click()
const closing = await stackGeometry(page, 0.5)
- await releaseTransitions(page)
+ await releaseTransitions(page, clock)
await expect(reviewPanel).toBeHidden()
await expect(terminalPanel).toBeVisible()
const alone = await stackGeometry(page)
@@ -171,10 +173,10 @@ test("terminal stacks under review by default and spans the bottom when configur
// Hiding the terminal mid-motion: both surfaces fill their regions and the clipped terminal keeps its size.
const open = await stackGeometry(page)
- await holdTransitions(page)
+ await holdTransitions(page, clock)
await page.keyboard.press("Control+Backquote")
const hiding = await stackGeometry(page, 0.5)
- await releaseTransitions(page)
+ await releaseTransitions(page, clock)
await expect(terminalPanel).toBeHidden()
expect(hiding.moving).toEqual(expect.arrayContaining(["session-side-region", "session-side-terminal-region"]))
expect(hiding.terminalRegion).toBeLessThan(open.terminalRegion - 1)
@@ -319,8 +321,12 @@ async function expectTreeSentinel(page: Page) {
}
// Pauses each CSS transition as it starts, so a real toggle can be measured mid-motion.
-function holdTransitions(page: Page) {
+async function holdTransitions(page: Page, clock: CDPSession) {
+ // Under CPU contention, transitionrun can arrive after the transition finished; stop compositor time first.
+ await clock.send("Animation.setPlaybackRate", { playbackRate: 0 })
+
return page.evaluate(() => {
+ // SAFETY: This fixture owns the optional e2eHold state on this page.
const host = window as Window & { e2eHold?: { active: boolean } }
if (!host.e2eHold) {
@@ -339,18 +345,22 @@ function holdTransitions(page: Page) {
})
}
-function releaseTransitions(page: Page) {
- return page.evaluate(() => {
- ;(window as Window & { e2eHold?: { active: boolean } }).e2eHold!.active = false
+async function releaseTransitions(page: Page, clock: CDPSession) {
+ await page.evaluate(() => {
+ // SAFETY: holdTransitions created this page-owned state before release.
+ const host = window as Window & { e2eHold?: { active: boolean } }
+ host.e2eHold!.active = false
document
.getAnimations()
.filter((item) => item instanceof CSSTransition && item.playState === "paused")
.forEach((item) => item.finish())
})
+ await clock.send("Animation.setPlaybackRate", { playbackRate: 1 })
}
// With `progress`, waits for the held region height transitions and seeks every held transition to that point first.
async function stackGeometry(page: Page, progress?: number) {
+ // SAFETY: These filtered CSS transitions have keyframe effects targeting the owning DOM elements.
const held = () =>
page.evaluate(() =>
document
@@ -371,6 +381,7 @@ async function stackGeometry(page: Page, progress?: number) {
.getAnimations()
.filter((item): item is CSSTransition => item instanceof CSSTransition && item.playState === "paused")
+ // SAFETY: CSS transitions on these regions have keyframe effects targeting DOM elements.
const region = transitions.find(
(item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot") === "session-side-region",
)
@@ -387,6 +398,7 @@ async function stackGeometry(page: Page, progress?: number) {
const terminal = box("#terminal-panel")!
const content = box('[data-slot="terminal-panel-content"]')!
+ // SAFETY: The filtered CSS transitions target DOM elements, as in the region lookup above.
return {
moving: transitions.map((item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot")),
terminalRegion: terminalRegion.height,
@@ -414,6 +426,7 @@ async function expectTerminalControlsAligned(terminal: Locator, toggle: Locator)
const centers = await Promise.all(
[terminal.getByRole("button", { name: "New terminal", exact: true }), toggle].map((button) =>
button.locator("svg").evaluate((element) => {
+ // SAFETY: The locator selects svg elements, whose geometry is read below.
const svg = element as SVGSVGElement
const path = svg.getBBox()
diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts
index f72b093331..a408aa4c22 100644
--- a/packages/app/e2e/regression/tabs.spec.ts
+++ b/packages/app/e2e/regression/tabs.spec.ts
@@ -692,6 +692,44 @@ test("inactive tabs load attention and inbox, but read the transcript only on se
expect(errors).toEqual([])
})
+test("closing a tab releases its transcript, and reopening it reads the transcript again", async ({ page }) => {
+ const reads: string[] = []
+ const errors: string[] = []
+ page.on("pageerror", (error) => errors.push(error.message))
+ page.on("request", (request) => {
+ if (request.method() === "GET") reads.push(new URL(request.url()).pathname)
+ })
+
+ const history = (id: string) =>
+ page.locator(`[data-timeline-row="UserMessage"][data-message-id="msg_${id}_history"]`)
+
+ await openSession(page, {
+ name: "TabRetention",
+ sessions: [a, b],
+ pageMessages: (id) => ({
+ items: [{ id: `msg_${id}_history`, type: "user", text: `History of ${id}`, time: { created: 1 } }],
+ }),
+ })
+ await expect(history(a.id)).toContainText(`History of ${a.id}`)
+
+ await page.locator(`[data-titlebar-tab-link][href="${sessionHref(b.id)}"]`).click()
+ await expect(history(b.id)).toContainText(`History of ${b.id}`)
+ await page.keyboard.press("Control+w")
+ await expect(page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)).toHaveCount(0)
+ await expectSessionTitle(page, a.title)
+
+ // A release has no visible signal, so wait past the retention delay. The open tab keeps its transcript.
+ await page.waitForTimeout(2_000)
+ await expect(history(a.id)).toContainText(`History of ${a.id}`)
+
+ await page.keyboard.press("Control+Shift+T")
+ await expectSessionTitle(page, b.title)
+ await expect(history(b.id)).toContainText(`History of ${b.id}`)
+ await expect.poll(() => reads.filter((path) => path === `/api/session/${b.id}/message`).length).toBe(2)
+ expect(reads.filter((path) => path === `/api/session/${a.id}/message`)).toHaveLength(1)
+ expect(errors).toEqual([])
+})
+
test("five loaded workspace tabs stay rendered and reactive through repeated switches", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
diff --git a/packages/app/e2e/regression/whats-new.spec.ts b/packages/app/e2e/regression/whats-new.spec.ts
index 9e91bb5170..f08f5e367a 100644
--- a/packages/app/e2e/regression/whats-new.spec.ts
+++ b/packages/app/e2e/regression/whats-new.spec.ts
@@ -219,7 +219,10 @@ async function serveChangelog(page: Page, body: typeof changelog | typeof cliOnl
async function start(page: Page, seed: SeedInput) {
await mockWorkspace(page, { name: "Whats New", sessions: [], seed })
await page.goto("/")
- await expectAppVisible(page.getByRole("button", { name: "Settings", exact: true }))
+ // The startup dialog may already hide the shell from accessibility queries.
+ await expectAppVisible(
+ page.getByRole("button", { name: "Settings", exact: true, includeHidden: true }).filter({ visible: true }),
+ )
}
function stored(page: Page, key: string) {
diff --git a/packages/app/src/cookiemonster/browser/browser-site.tsx b/packages/app/src/cookiemonster/browser/browser-site.tsx
index 47fcf42fba..69eb46b618 100644
--- a/packages/app/src/cookiemonster/browser/browser-site.tsx
+++ b/packages/app/src/cookiemonster/browser/browser-site.tsx
@@ -8,6 +8,8 @@ export function BrowserSite(props: {
tab: BrowserTab
profile: BrowserProfile
busy: boolean
+ // SAFETY: Command results are opaque except the documented false inspection outcome checked below.
+ // oxlint-disable-next-line anti-slop/no-unknown-returns
command(value: BrowserCommand): Promise
}) {
const language = useLanguage()
@@ -92,6 +94,7 @@ export function BrowserSite(props: {
void props.command({
op: "site-permission",
origin: origin(),
+ // SAFETY: This owned select offers only the three BrowserPermission values below.
[device]: event.currentTarget.value as BrowserPermission,
})
}
@@ -114,6 +117,7 @@ export function BrowserSite(props: {
void props.command({
op: "site-permission",
origin: origin(),
+ // SAFETY: This owned select offers only the three BrowserPermission values below.
[permission]: event.currentTarget.value as BrowserPermission,
})
}
@@ -158,12 +162,18 @@ export function BrowserSite(props: {
+
+
{language.t("browser.site.inspecting")}
+
}
>
{(inspection) => (
diff --git a/packages/app/src/cookiemonster/browser/en.ts b/packages/app/src/cookiemonster/browser/en.ts
index 7ffa2c7ec7..0e071f61a9 100644
--- a/packages/app/src/cookiemonster/browser/en.ts
+++ b/packages/app/src/cookiemonster/browser/en.ts
@@ -106,6 +106,7 @@ export const browser = {
"browser.site.data": "Site data",
"browser.site.inspecting": "Inspecting Chromium site data…",
"browser.site.inspectFailed": "Could not inspect this site. Try Refresh inspection.",
+ "browser.site.stale": "Showing previous inspection results. Site data may have changed.",
"browser.site.cookies": "Cookies matching this page: {{count}}",
"browser.site.usage": "Origin storage reported by Chromium: {{size}}",
"browser.site.storage": "Stored categories: {{types}}",
diff --git a/packages/app/src/runtime/i18n/desktop-native.ts b/packages/app/src/runtime/i18n/desktop-native.ts
index 7fb1d7d49e..40881b1148 100644
--- a/packages/app/src/runtime/i18n/desktop-native.ts
+++ b/packages/app/src/runtime/i18n/desktop-native.ts
@@ -306,6 +306,9 @@ export const DESKTOP_NATIVE_ENGLISH = {
"desktop.picker.error.notSelected": "File was not selected by the picker",
"desktop.picker.error.sizeLimit": "Selected attachments exceed the {{limit}} MB limit",
+
+ "desktop.openWith.error.appNotAllowed": "Application is not allowed: {{app}}",
+ "desktop.openWith.error.notAbsolute": "Open target must be an absolute path",
} as const
export type DesktopNativeKey = keyof typeof DESKTOP_NATIVE_ENGLISH
@@ -314,6 +317,7 @@ export type DesktopNativeMessages = Record
export type DesktopNativeBundle = { locale: DesktopNativeLocale; messages: DesktopNativeMessages }
+// SAFETY: DesktopNativeKey is exactly the key union of this owned literal.
export const DESKTOP_NATIVE_KEYS = Object.keys(DESKTOP_NATIVE_ENGLISH) as DesktopNativeKey[]
export const DESKTOP_NATIVE_MAX_PAYLOAD_BYTES = 64 * 1024
@@ -324,10 +328,13 @@ export function createDesktopNativeBundle(
): DesktopNativeBundle {
return {
locale,
+ // SAFETY: Every declared key occurs once and the translator returns a string for each.
messages: Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key) => [key, translate(key)])) as DesktopNativeMessages,
}
}
+// SAFETY: This IPC decoder checks payload size, locale, exact keys and string values before returning a bundle.
+/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type */
export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined
@@ -337,11 +344,13 @@ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle |
return undefined
}
+ // SAFETY: The guard above establishes an object; its fields remain unknown until checked below.
const bundle = value as { locale?: unknown; messages?: unknown }
if (!DESKTOP_NATIVE_LOCALES.some((locale) => locale === bundle.locale)) return undefined
if (!bundle.messages || typeof bundle.messages !== "object" || Array.isArray(bundle.messages)) return undefined
+ // SAFETY: Messages is a non-array object; this boundary checks every unknown member below.
const messages = bundle.messages as Record
const keys = Object.keys(messages)
@@ -351,8 +360,10 @@ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle |
if (!keys.every((key) => key in DESKTOP_NATIVE_ENGLISH)) return undefined
+ // SAFETY: The bounded payload now has a supported locale, the exact native keys and only string values.
return bundle as DesktopNativeBundle
}
+/* oxlint-enable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type */
export function formatDesktopNativeMessage(message: string, params?: Record) {
if (!params) return message
diff --git a/packages/app/src/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx
index 13e686e8c3..a7560b83f2 100644
--- a/packages/app/src/runtime/server/runtime.tsx
+++ b/packages/app/src/runtime/server/runtime.tsx
@@ -1,6 +1,20 @@
import { createSimpleContext } from "@opencode/ui/context"
-import { Accessor, batch, createEffect, createMemo, createResource, createRoot, getOwner, untrack } from "solid-js"
+import {
+ Accessor,
+ batch,
+ createEffect,
+ createMemo,
+ createResource,
+ createRoot,
+ getOwner,
+ untrack,
+ useTransition,
+} from "solid-js"
+import { useLocation } from "@solidjs/router"
import { createServerProjects, RECENTLY_CLOSED_DISPLAY_LIMIT, ServerConnection, useServers } from "./registry"
+import { createSessionRetention } from "./session-retention"
+import { sessionHref } from "@/shell/routes/session"
+import { useTabs } from "@/shell/tabs/tabs"
import { pathKey } from "@/workspaces/path-key"
import { useServerHealth } from "@/runtime/server/health"
import { createServerSdkContext } from "./client"
@@ -198,6 +212,32 @@ function createServerController(
createPermissionAutoApprover({ sdk, data })
const notification = createServerNotificationState({ sdk, data, key: connKey, coordinator: notificationCoordinator })
+ const tabs = useTabs()
+ const location = useLocation()
+ // Parsed here because the shared route parser throws on routes it does not recognise.
+ const routes = sessionHref(connKey, "")
+ createSessionRetention({
+ session: data.session,
+ ready: tabs.ready,
+ visible: () => {
+ const routed = location.pathname.startsWith(routes)
+ ? location.pathname.slice(routes.length).split("/")[0]
+ : undefined
+
+ return [
+ ...(routed ? [routed] : []),
+ ...tabs.store.flatMap((tab) =>
+ tab.type === "session" && tab.server === connKey
+ ? [tab.sessionId, tab.routeSessionId, tab.routeParentId].flatMap((id) => (id ? [id] : []))
+ : [],
+ ),
+ ]
+ },
+ navigating: useTransition()[0],
+ // Covers an open path whose transcript read lands before the transition adding its tab commits.
+ delay: 1_000,
+ })
+
function enrich(project: { worktree: string; expanded: boolean }) {
const [childStore] = sync.child(project.worktree, { bootstrap: false })
const projectID = childStore.project
diff --git a/packages/app/src/runtime/server/session-retention.ts b/packages/app/src/runtime/server/session-retention.ts
new file mode 100644
index 0000000000..38b22f7d64
--- /dev/null
+++ b/packages/app/src/runtime/server/session-retention.ts
@@ -0,0 +1,64 @@
+import { createEffect, onCleanup, type Accessor } from "solid-js"
+import type { Data } from "@opencode/client/solid"
+
+type Session = Pick
+
+/**
+ * Releases the cached transcripts of session families that no open tab, session route, running work or attention
+ * request keeps. A family is released once it has stayed unkept for `delay` with no transition pending, since an open
+ * path can read a transcript before the transition that adds its tab or route commits. Late reads and events that
+ * bring rows back to a released family start a new delay, so they cannot keep it cached.
+ */
+export function createSessionRetention(input: {
+ session: Session
+ /** Persisted tabs have loaded. */
+ ready: Accessor
+ /** Sessions shown by open tabs or the current route. */
+ visible: Accessor
+ navigating: Accessor
+ delay: number
+}) {
+ const timers = new Map>()
+ onCleanup(() => timers.forEach((timer) => clearTimeout(timer)))
+ const unkept = () => new Set(input.ready() && !input.navigating() ? unkeptRoots(input.session, input.visible()) : [])
+
+ const release = (root: string) => {
+ timers.set(
+ root,
+ setTimeout(() => {
+ timers.delete(root)
+ input.session.evict(root)
+
+ // Eviction keeps unacknowledged submissions and sessions still being created, and settling them need not
+ // change the cached set this policy tracks. Retry while the family stays unkept and cached.
+ if (!timers.has(root) && unkept().has(root)) release(root)
+ }, input.delay),
+ )
+ }
+
+ createEffect(() => {
+ const roots = unkept()
+ timers.forEach((timer, root) => {
+ if (roots.has(root)) return
+ clearTimeout(timer)
+ timers.delete(root)
+ })
+ // A family that keeps receiving rows still releases at its first deadline.
+ roots.forEach((root) => {
+ if (!timers.has(root)) release(root)
+ })
+ })
+}
+
+function unkeptRoots(session: Session, visible: readonly string[]) {
+ const kept = new Set(
+ [...visible, ...session.active(), ...session.permission.sessions(), ...session.form.sessions()].map((id) =>
+ session.root(id),
+ ),
+ )
+
+ return session
+ .cached()
+ .map((id) => session.root(id))
+ .filter((root) => !kept.has(root))
+}
diff --git a/packages/app/src/session/session-screen.stories.tsx b/packages/app/src/session/session-screen.stories.tsx
index 9b47241bec..0c5d746a9b 100644
--- a/packages/app/src/session/session-screen.stories.tsx
+++ b/packages/app/src/session/session-screen.stories.tsx
@@ -15,6 +15,8 @@ import {
terminalPassedDocument,
} from "@opencode/session-ui/storybook"
import { SessionPreview } from "./story-model"
+import { SettingsProvider } from "@/settings/model"
+import type { JSX } from "solid-js"
const description = "opencode · modular-session-ui"
@@ -51,6 +53,13 @@ export default {
title: "OpenCode/Session/Complete workspace",
id: "app-current-session-surface",
component: SessionPreview,
+ decorators: [
+ (Story: () => JSX.Element) => (
+
+
+
+ ),
+ ],
parameters: {
layout: "fullscreen",
docs: {
diff --git a/packages/app/src/session/timeline/observe-element-offset.test.ts b/packages/app/src/session/timeline/observe-element-offset.test.ts
index 2a2eea1449..a770e75008 100644
--- a/packages/app/src/session/timeline/observe-element-offset.test.ts
+++ b/packages/app/src/session/timeline/observe-element-offset.test.ts
@@ -8,6 +8,8 @@ test("restores a view observed before its first attachment", async () => {
const mutations = controlledMutations(targetWindow)
const viewport = targetWindow.document.createElement("div")
+ // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options.
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture.
const instance = {
scrollElement: viewport,
targetWindow,
@@ -45,6 +47,8 @@ test("reports a divergent native offset once and ignores equal offsets and unrel
route.append(viewport)
targetWindow.document.body.append(route)
+ // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options.
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture.
const instance = {
scrollElement: viewport,
targetWindow,
@@ -93,6 +97,8 @@ test("keeps checking until stale reset-delay callbacks can no longer win", async
route.append(viewport)
targetWindow.document.body.append(route)
+ // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options.
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture.
const instance = {
scrollElement: viewport,
targetWindow,
@@ -137,6 +143,8 @@ test("cleanup suppresses queued delegated callbacks, reconnect checks, and later
route.append(viewport)
document.body.append(route)
+ // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options.
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture.
const instance = {
scrollElement: viewport,
targetWindow: window,
@@ -170,8 +178,50 @@ test("cleanup suppresses queued delegated callbacks, reconnect checks, and later
route.remove()
})
+test("ends a scroll at the live offset after a write without its own scroll event", async () => {
+ const viewport = document.createElement("div")
+ document.body.append(viewport)
+
+ // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options.
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture.
+ const instance = {
+ scrollElement: viewport,
+ targetWindow: window,
+ scrollOffset: 0,
+ options: {
+ horizontal: false,
+ isRtl: false,
+ isScrollingResetDelay: 10,
+ useScrollendEvent: false,
+ },
+ } as unknown as Virtualizer
+
+ const calls: [number, boolean][] = []
+
+ const cleanup = observeElementOffsetReconnectAware(instance, (offset, isScrolling) => {
+ calls.push([offset, isScrolling])
+ instance.scrollOffset = offset
+ })
+
+ try {
+ viewport.scrollTop = 100
+ viewport.dispatchEvent(new Event("scroll"))
+ // A history prepend anchors with a write whose scroll event a long task can hold past the reset delay.
+ viewport.scrollTop = 2_620
+ await new Promise((resolve) => setTimeout(resolve, 25))
+
+ expect(calls).toEqual([
+ [100, true],
+ [2_620, false],
+ ])
+ } finally {
+ cleanup?.()
+ viewport.remove()
+ }
+})
+
type FrameWindow = {
- requestAnimationFrame(callback: () => void): unknown
+ requestAnimationFrame(callback: () => void): void
performance: { now(): number }
}
@@ -188,6 +238,8 @@ function controlledMutations(targetWindow: Window) {
class ControlledMutationObserver {
constructor(callback: MutationCallback) {
+ // SAFETY: The callback uses only the observer lifecycle methods implemented by this controlled fixture.
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Controlled observer intentionally omits unused browser internals.
emit = (record) => callback([record], this as unknown as MutationObserver)
}
observe() {}
@@ -199,7 +251,9 @@ function controlledMutations(targetWindow: Window) {
Object.defineProperty(targetWindow, "MutationObserver", { value: ControlledMutationObserver })
+ // SAFETY: The production observer reads only type, target, addedNodes, and removedNodes from these fixture records.
const record = (target: Node, addedNodes: Node[], removedNodes: Node[]) =>
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM nodes implement the DOM methods consumed by the observer.
({ type: "childList", target, addedNodes, removedNodes }) as unknown as MutationRecord
return {
diff --git a/packages/app/src/session/timeline/observe-element-offset.ts b/packages/app/src/session/timeline/observe-element-offset.ts
index 80f3d5fb4d..5571955cd9 100644
--- a/packages/app/src/session/timeline/observe-element-offset.ts
+++ b/packages/app/src/session/timeline/observe-element-offset.ts
@@ -6,14 +6,16 @@ export function observeElementOffsetReconnectAware void,
) {
let active = true
+ const element = instance.scrollElement
const deliver = (offset: number, isScrolling: boolean) => {
if (!active) return
- callback(offset, isScrolling)
+ // The core's reset-delay fallback repeats the offset read by the last scroll event. A long task can hold a
+ // write's own scroll event past that delay, so ending the scroll at the stored offset would revert the write.
+ callback(isScrolling || !element ? offset : element.scrollTop, isScrolling)
}
const cleanupOffset = observeElementOffset(instance, deliver)
- const element = instance.scrollElement
const targetWindow = instance.targetWindow
const root = element?.closest("main") ?? element?.ownerDocument.body
diff --git a/packages/app/test-browser/browser-site.test.ts b/packages/app/test-browser/browser-site.test.ts
new file mode 100644
index 0000000000..1b9269fed7
--- /dev/null
+++ b/packages/app/test-browser/browser-site.test.ts
@@ -0,0 +1,104 @@
+import { expect, test } from "bun:test"
+import { mkdtemp, rm } from "node:fs/promises"
+import { join, resolve } from "node:path"
+import { pathToFileURL } from "node:url"
+import { build } from "vite"
+import solid from "vite-plugin-solid"
+import { browser } from "../src/cookiemonster/browser/en"
+
+test("mounted site inspection exposes failed refreshes over retained data and clears them on retry or navigation", async () => {
+ const directory = await mkdtemp(resolve("test-browser/.site-inspection-"))
+ const host = document.createElement("div")
+ document.body.append(host)
+ let dispose = () => {}
+
+ try {
+ await build({
+ configFile: false,
+ root: resolve("."),
+ logLevel: "warn",
+ plugins: [
+ {
+ name: "site-inspection-fixture",
+ enforce: "pre",
+ resolveId(id) {
+ for (const name of ["site-inspection-fixture", "@/runtime/i18n/language"]) {
+ if (id === name || id.replaceAll("\\", "/") === resolve(name.replace("@/", "src/")).replaceAll("\\", "/"))
+ return "\0" + name
+ }
+ },
+ load(id) {
+ if (id === "\0@/runtime/i18n/language")
+ return `import { browser } from ${JSON.stringify(resolve("src/cookiemonster/browser/en.ts"))};
+ export const useLanguage = () => ({intl:()=>"en-US", t:(key, params={})=>Object.entries(params).reduce((text,[name,value])=>text.replaceAll("{{"+name+"}}",String(value)),browser[key] ?? key)});`
+
+ if (id === "\0site-inspection-fixture")
+ return `
+ import { createComponent } from "solid-js";
+ import { createStore } from "solid-js/store";
+ import { render } from "solid-js/web";
+ import { BrowserSite } from ${JSON.stringify(resolve("src/cookiemonster/browser/browser-site.tsx"))};
+ export function mount(host, initialFailure=false) {
+ const [state,setState]=createStore({result:initialFailure?"false":"true",tab:{id:"tab",url:"https://first.example/page",agentAccess:true,siteData:initialFailure?undefined:{origin:"https://first.example",cookies:1,usage:1024,storage:[]}}});
+ const dispose=render(()=>createComponent(BrowserSite,{get tab(){return state.tab},profile:{},busy:false,command:async()=>{if(state.result==="reject")throw Error("inspection failed");return state.result!=="false"}}),host);
+ return {dispose,result:value=>setState("result",value),tab:value=>setState("tab",value)};
+ }`
+ },
+ },
+ solid(),
+ ],
+ resolve: { alias: { "@": resolve("src") } },
+ build: {
+ outDir: directory,
+ emptyOutDir: false,
+ minify: false,
+ lib: { entry: "site-inspection-fixture", formats: ["es"], fileName: () => "fixture.mjs" },
+ },
+ })
+ const fixture = await import(pathToFileURL(join(directory, "fixture.mjs")).href)
+ const mounted = fixture.mount(host)
+ dispose = mounted.dispose
+ const tick = () => new Promise((resolve) => setImmediate(resolve))
+
+ const refresh = () =>
+ [...host.querySelectorAll("button")]
+ .find((button) => button.textContent?.trim() === browser["browser.site.refresh"])!
+ .click()
+
+ await tick()
+ expect(host.textContent).toContain("Cookies matching this page: 1")
+
+ for (const failure of ["false", "reject"]) {
+ mounted.result(failure)
+ refresh()
+ await tick()
+ expect(host.textContent).toContain(browser["browser.site.inspectFailed"])
+ expect(host.textContent).toContain(browser["browser.site.stale"])
+ expect(host.textContent).toContain("Cookies matching this page: 1")
+ }
+
+ mounted.result("true")
+ mounted.tab({ siteData: { origin: "https://first.example", cookies: 2, usage: 1024, storage: [] } })
+ refresh()
+ await tick()
+ expect(host.textContent).toContain("Cookies matching this page: 2")
+ expect(host.textContent).not.toContain(browser["browser.site.inspectFailed"])
+ expect(host.textContent).not.toContain(browser["browser.site.stale"])
+ mounted.tab({ url: "https://second.example/" })
+ await tick()
+ expect(host.textContent).toContain(browser["browser.site.inspecting"])
+ expect(host.textContent).not.toContain("Cookies matching this page:")
+ dispose()
+ host.replaceChildren()
+ const initial = fixture.mount(host, true)
+ dispose = initial.dispose
+ await tick()
+ expect(host.textContent).toContain(browser["browser.site.inspectFailed"])
+ expect(host.textContent).not.toContain(browser["browser.site.stale"])
+ expect(host.textContent).not.toContain(browser["browser.site.inspecting"])
+ } finally {
+ dispose()
+ host.remove()
+ await rm(directory, { recursive: true, force: true })
+ }
+}, 30_000)
diff --git a/packages/app/test-browser/cm-loading.fixture.tsx b/packages/app/test-browser/cm-loading.fixture.tsx
index 095e5ccb89..7430d129ec 100644
--- a/packages/app/test-browser/cm-loading.fixture.tsx
+++ b/packages/app/test-browser/cm-loading.fixture.tsx
@@ -17,7 +17,9 @@ function Fixture() {
return (
+ section { display:flex; } svg { flex-shrink:0; }
+ /* Own layer per compared row, so identical rows raster from the same tile origin. */
+ #project, #recent, #tabs { will-change: transform; }`}
diff --git a/packages/app/test-browser/cm-loading.test.ts b/packages/app/test-browser/cm-loading.test.ts
index bf123b3dec..a9fd0cd40f 100644
--- a/packages/app/test-browser/cm-loading.test.ts
+++ b/packages/app/test-browser/cm-loading.test.ts
@@ -9,7 +9,9 @@ import solid from "vite-plugin-solid"
test("session cookies share their animation and phase across late mounts, updates, and reduced motion", async () => {
const directory = await mkdtemp(join(tmpdir(), "cm-loading-"))
- const browser = await chromium.launch()
+ // SVG images follow Chromium's own reduced-motion preference (the OS setting on Windows), not page emulation.
+ // Pin it so the motion checks are deterministic; page emulation below still covers reduced motion.
+ const browser = await chromium.launch({ args: ["--force-prefers-no-reduced-motion"] })
const server = createServer(async (request, response) => {
const pathname = new URL(request.url ?? "/", "http://localhost").pathname
@@ -31,6 +33,7 @@ test("session cookies share their animation and phase across late mounts, update
await new Promise((done) => server.listen(0, "127.0.0.1", done))
const address = server.address()
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Node returns a Unix socket path or a TCP address; this fixture binds TCP.
if (!address || typeof address === "string") throw new Error("Loader fixture server did not bind")
try {
diff --git a/packages/app/test-browser/session-retention.test.ts b/packages/app/test-browser/session-retention.test.ts
new file mode 100644
index 0000000000..338f170eca
--- /dev/null
+++ b/packages/app/test-browser/session-retention.test.ts
@@ -0,0 +1,415 @@
+import { expect, test } from "bun:test"
+import { OpenCode, type OpenCodeEvent, type SessionInfo } from "@opencode/client/promise"
+import { createData, type CreateDataInput } from "@opencode/client/solid"
+import { createRoot, createSignal } from "solid-js"
+import { unwrap } from "solid-js/store"
+import { createSessionRetention } from "@/runtime/server/session-retention"
+
+// Runs under the browser build: the server build of Solid never runs the policy's effect.
+const delay = 10
+
+test("releases unkept families after the delay and keeps visible, running and attention families", async () => {
+ const ids = ["ses_open", "ses_open_child", "ses_closed", "ses_closed_child", "ses_running", "ses_asked"]
+ const scope = setup({ visible: ["ses_open_child"] })
+
+ try {
+ scope.remember("ses_open")
+ scope.remember("ses_open_child", "ses_open")
+ scope.remember("ses_closed")
+ scope.remember("ses_closed_child", "ses_closed")
+ scope.remember("ses_running")
+ scope.remember("ses_asked")
+ scope.data.session.setStatus("ses_running", "running")
+ scope.emit(permissionAsked("ses_asked"))
+
+ for (const id of ids) await scope.data.session.message.sync(id)
+ await settle()
+
+ expect(ids.filter(scope.cached)).toEqual(["ses_open", "ses_open_child", "ses_running", "ses_asked"])
+ // Eviction drops only transcript rows.
+ expect(scope.data.session.get("ses_closed_child")?.parentID).toBe("ses_closed")
+ expect(scope.data.session.family("ses_closed")).toEqual(["ses_closed", "ses_closed_child"])
+ expect(scope.data.session.status("ses_running")).toBe("running")
+ expect(scope.data.session.permission.list("ses_asked")?.[0]?.id).toBe("per_ses_asked")
+
+ scope.data.session.setStatus("ses_running", "idle")
+ await settle()
+ expect(ids.filter(scope.cached)).toEqual(["ses_open", "ses_open_child", "ses_asked"])
+ } finally {
+ scope.dispose()
+ }
+})
+
+test("closing a child tab keeps its still-visible parent and sibling family", async () => {
+ const ids = ["ses_parent", "ses_child", "ses_sibling"]
+ const scope = setup({ visible: ["ses_parent", "ses_child"] })
+
+ try {
+ scope.remember("ses_parent")
+ scope.remember("ses_child", "ses_parent")
+ scope.remember("ses_sibling", "ses_parent")
+
+ for (const id of ids) await scope.data.session.message.sync(id)
+
+ scope.setVisible(["ses_parent"])
+ await settle()
+ expect(ids.filter(scope.cached)).toEqual(ids)
+
+ scope.setVisible([])
+ await settle()
+ expect(ids.filter(scope.cached)).toEqual([])
+ } finally {
+ scope.dispose()
+ }
+})
+
+test("waits for persisted tabs, and keeps a read that lands before its tab or navigation commits", async () => {
+ const scope = setup({ ready: false })
+
+ try {
+ scope.remember("ses_opening")
+ await scope.data.session.message.sync("ses_opening")
+ await settle()
+ expect(scope.cached("ses_opening")).toBe(true)
+
+ // Home reads the transcript before its transition adds the tab.
+ scope.setReady(true)
+ scope.setVisible(["ses_opening"])
+ await settle()
+ expect(scope.cached("ses_opening")).toBe(true)
+
+ scope.setNavigating(true)
+ scope.setVisible([])
+ await settle()
+ expect(scope.cached("ses_opening")).toBe(true)
+
+ scope.setNavigating(false)
+ await settle()
+ expect(scope.cached("ses_opening")).toBe(false)
+ } finally {
+ scope.dispose()
+ }
+})
+
+test("late reads, late pages and later events are released again, and reopening reads the transcript", async () => {
+ const late = Promise.withResolvers()
+ const older = Promise.withResolvers()
+ const ids = ["ses_paged", "ses_late"]
+
+ const scope = setup({
+ visible: ids,
+ read(url) {
+ if (url.searchParams.has("cursor")) return older.promise
+
+ if (url.pathname.endsWith("/ses_late/message")) return late.promise
+
+ return undefined
+ },
+ })
+
+ try {
+ scope.remember("ses_paged")
+ scope.remember("ses_late")
+ await scope.data.session.message.sync("ses_paged")
+ await scope.data.session.pending.sync("ses_late")
+
+ const reads = Promise.allSettled([
+ scope.data.session.message.sync("ses_late"),
+ scope.data.session.message.loadMore("ses_paged"),
+ ])
+
+ scope.setVisible([])
+ await settle()
+ expect(ids.filter(scope.cached)).toEqual([])
+
+ late.resolve()
+ older.resolve()
+ await reads
+ // Both reads publish after their family was evicted.
+ expect(ids.filter(scope.cached)).toEqual(ids)
+ await settle()
+ expect(ids.filter(scope.cached)).toEqual([])
+
+ scope.emit(agentSelected("ses_paged"))
+ expect(scope.cached("ses_paged")).toBe(true)
+ await settle()
+ expect(scope.cached("ses_paged")).toBe(false)
+
+ scope.setVisible(["ses_paged"])
+ await scope.data.session.message.sync("ses_paged")
+ await settle()
+ expect(scope.transcriptReads("ses_paged")).toBe(2)
+ expect(scope.data.session.message.list("ses_paged").map((item) => item.id)).toEqual(["msg_ses_paged"])
+ } finally {
+ late.resolve()
+ older.resolve()
+ scope.dispose()
+ }
+})
+
+test.each(["echo", "reject"] as const)(
+ "keeps a closed session's optimistic prompt past the deadline and releases it after its %s",
+ async (mode) => {
+ const answer = Promise.withResolvers()
+
+ const scope = setup({
+ async read(url) {
+ if (!url.pathname.endsWith("/prompt")) return undefined
+ await answer.promise
+
+ return mode === "reject"
+ ? Response.json({ message: "rejected" }, { status: 400 })
+ : Response.json({ id: "msg_local" })
+ },
+ })
+
+ try {
+ scope.remember("ses_submit")
+
+ const prompt = Promise.allSettled([
+ scope.data.session.prompt({ sessionID: "ses_submit", id: "msg_local", text: "local" }),
+ ])
+
+ await settle()
+ // The deadline passed while the submission awaited its acknowledgement.
+ expect(scope.data.session.message.list("ses_submit").map((item) => item.id)).toEqual(["msg_local"])
+
+ if (mode === "echo") scope.emit(enqueued("ses_submit", "msg_local"))
+ answer.resolve()
+ await prompt
+ await settle()
+ expect(scope.cached("ses_submit")).toBe(false)
+ expect(scope.data.session.pending.list("ses_submit")).toEqual([])
+ } finally {
+ answer.resolve()
+ scope.dispose()
+ }
+ },
+)
+
+test("keeps a closed session's first prompt while its creation is unacknowledged, then releases it", async () => {
+ const created = Promise.withResolvers()
+
+ const scope = setup({
+ read(url) {
+ if (url.pathname === "/api/session") return created.promise
+
+ if (url.pathname.endsWith("/prompt")) return Promise.resolve(Response.json({ id: "msg_first" }))
+
+ return undefined
+ },
+ })
+
+ try {
+ const session = scope.data.session.create({})
+
+ const prompt = Promise.allSettled([
+ scope.data.session.prompt({ sessionID: session.id, id: "msg_first", text: "first" }),
+ ])
+
+ await settle()
+ // Eviction skips a session whose creation the server has not acknowledged.
+ expect(scope.data.session.message.list(session.id).map((item) => item.id)).toEqual(["msg_first"])
+
+ created.resolve(Response.json({ data: info(session.id) }))
+ await session.request
+ scope.emit(enqueued(session.id, "msg_first"))
+ await prompt
+ await settle()
+ expect(scope.cached(session.id)).toBe(false)
+ expect(scope.data.session.pending.list(session.id)).toEqual([])
+ expect(scope.data.session.get(session.id)?.id).toBe(session.id)
+ } finally {
+ scope.dispose()
+ }
+})
+
+test("closed transcripts and the rows later events bring back do not stay on the heap", async () => {
+ if (process.env.CM_RETENTION_HEAP_PROBE !== "1") {
+ // Other browser tests can release their heaps between samples; measure this contract in its own process.
+ const result = Bun.spawnSync(
+ [
+ process.execPath,
+ "test",
+ "--conditions=browser",
+ "--preload",
+ "./happydom.ts",
+ import.meta.path,
+ "-t",
+ "closed transcripts and the rows",
+ ],
+ { env: { ...process.env, CM_RETENTION_HEAP_PROBE: "1" }, timeout: 20_000, stdout: "pipe", stderr: "pipe" },
+ )
+
+ expect(result.exitCode, result.stdout.toString() + result.stderr.toString()).toBe(0)
+
+ return
+ }
+
+ const count = 48
+ const size = 512 * 1024
+ const ids = Array.from({ length: count }, (_, index) => `ses_heavy_${index}`)
+ const scope = setup({ text: "x".repeat(size) })
+
+ try {
+ ids.forEach((id) => scope.remember(id))
+ scope.setVisible(ids)
+ const base = heap()
+
+ for (const id of ids) await scope.data.session.message.sync(id)
+ const rows = ids.map((id) => new WeakRef(unwrap(scope.data.session.message.list(id))[0]!))
+ const loaded = heap()
+
+ scope.setVisible([])
+ await settle()
+ ids.forEach((id) => scope.emit(agentSelected(id)))
+ expect(ids.filter(scope.cached)).toEqual(ids)
+ await settle()
+ const released = heap()
+
+ console.info(`[session-retention heap] base=${base} loaded=${loaded} released=${released}`)
+ expect(ids.filter(scope.cached)).toEqual([])
+ expect(loaded - base).toBeGreaterThan(count * size * 0.8)
+ expect(released - base).toBeLessThan((loaded - base) * 0.1)
+ expect(rows.filter((row) => row.deref() !== undefined)).toHaveLength(0)
+ } finally {
+ scope.dispose()
+ }
+})
+
+function settle() {
+ return Bun.sleep(delay * 5)
+}
+
+function heap() {
+ Bun.gc(true)
+
+ return process.memoryUsage().heapUsed
+}
+
+function setup(
+ input: {
+ visible?: string[]
+ ready?: boolean
+ text?: string
+ /** Delays a request, or answers it when the promise resolves to a response. */
+ read?: (url: URL) => Promise | undefined
+ } = {},
+) {
+ const listeners = new Set[0]>()
+ const reads: URL[] = []
+
+ const api = OpenCode.make({
+ baseUrl: "http://opencode.local",
+ fetch: async (request) => {
+ const url = new URL(request instanceof Request ? request.url : String(request))
+ reads.push(url)
+ const response = await input.read?.(url)
+
+ if (response) return response
+ const sessionID = url.pathname.split("/")[3]
+
+ if (url.pathname.endsWith("/inbox"))
+ return Response.json({
+ data: [
+ {
+ id: `inb_${sessionID}`,
+ sessionID,
+ type: "user",
+ delivery: "steer",
+ payload: { text: "pending" },
+ time: { created: 2 },
+ },
+ ],
+ })
+ const older = url.searchParams.has("cursor")
+
+ return Response.json({
+ data: [
+ {
+ id: older ? `msg_${sessionID}_older` : `msg_${sessionID}`,
+ type: "user",
+ text: input.text ?? "transcript",
+ time: { created: older ? 0 : 1 },
+ },
+ ],
+ cursor: older ? {} : { next: "older" },
+ })
+ },
+ })
+
+ return createRoot((dispose) => {
+ const data = createData({
+ api: () => api,
+ directory: "/project",
+ event: {
+ on: () => () => {},
+ listen(handler) {
+ listeners.add(handler)
+
+ return () => listeners.delete(handler)
+ },
+ },
+ })
+
+ const [visible, setVisible] = createSignal(input.visible ?? [])
+ const [ready, setReady] = createSignal(input.ready ?? true)
+ const [navigating, setNavigating] = createSignal(false)
+ createSessionRetention({ session: data.session, ready, visible, navigating, delay })
+
+ return {
+ data,
+ dispose,
+ setVisible,
+ setReady,
+ setNavigating,
+ emit: (details: OpenCodeEvent) => listeners.forEach((listener) => listener({ name: details.type, details })),
+ remember: (id: string, parentID?: string) => data.session.remember(info(id, parentID)),
+ cached: (id: string) => data.session.message.list(id).length > 0,
+ // Reads of the newest transcript page, not of older pages.
+ transcriptReads: (id: string) =>
+ reads.filter((url) => url.pathname.endsWith(`/${id}/message`) && !url.searchParams.has("cursor")).length,
+ }
+ })
+}
+
+function info(id: string, parentID?: string): SessionInfo {
+ return {
+ id,
+ parentID,
+ projectID: "project",
+ cost: 0,
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
+ time: { created: 0, updated: 0 },
+ location: { directory: "/project" },
+ }
+}
+
+function agentSelected(sessionID: string): OpenCodeEvent {
+ return {
+ id: `evt_agent_${sessionID}`,
+ created: 1,
+ type: "session.agent.selected",
+ durable: { aggregateID: sessionID, seq: 1, version: 1 },
+ data: { sessionID, agent: "build" },
+ }
+}
+
+function permissionAsked(sessionID: string): OpenCodeEvent {
+ return {
+ id: `evt_permission_${sessionID}`,
+ created: 1,
+ type: "permission.asked",
+ data: { id: `per_${sessionID}`, sessionID, action: "bash", resources: ["bun test"] },
+ }
+}
+
+function enqueued(sessionID: string, inboxID: string): OpenCodeEvent {
+ return {
+ id: `evt_${inboxID}`,
+ created: 1,
+ type: "session.inbox.enqueued",
+ durable: { aggregateID: sessionID, seq: 1, version: 1 },
+ data: { sessionID, inboxID, item: { type: "user", delivery: "steer", payload: { text: "echoed" } } },
+ }
+}
diff --git a/packages/cli/script/build-node.ts b/packages/cli/script/build-node.ts
index f7c64eeddc..566c797f76 100644
--- a/packages/cli/script/build-node.ts
+++ b/packages/cli/script/build-node.ts
@@ -155,7 +155,7 @@ for (const target of targets) {
)}\n`,
)
await verifyArtifact(path.join(outdir, name))
- if (host) await smoke(output)
+ if (host) await smoke(output, builder)
}
async function resolveHostNode() {
@@ -225,14 +225,20 @@ async function resolveTargetNode(target: NodeTarget, host?: string) {
return realpath(executable)
}
-async function smoke(output: string) {
+async function smoke(output: string, node: string) {
const root = await mkdtemp(path.join(os.tmpdir(), "opencode-node-smoke-"))
const executable = path.join(root, path.basename(output))
await copyFile(output, executable)
if (process.platform !== "win32") await chmod(executable, 0o755)
run(executable, ["--version"], root)
run(executable, ["--help"], root)
- await rm(root, { recursive: true, force: true })
+ // Use Node's retry-aware cleanup for transient Windows directory locks.
+ run(node, [
+ "--input-type=module",
+ "-e",
+ "import { rm } from 'node:fs/promises'; await rm(process.argv[1], { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })",
+ root,
+ ])
}
function targetName(target: NodeTarget) {
diff --git a/packages/client/src/solid/data.ts b/packages/client/src/solid/data.ts
index c5036a03f4..9b9300d9ec 100644
--- a/packages/client/src/solid/data.ts
+++ b/packages/client/src/solid/data.ts
@@ -1428,6 +1428,12 @@ export function createData(config: CreateDataInput) {
status === "running" ? [sessionID] : [],
)
},
+ /** Sessions holding transcript or pending rows. Notifies only when that set changes, not per streamed row. */
+ cached: createMemo(
+ () => [...new Set([...Object.keys(store.session.message), ...Object.keys(store.session.pending)])].toSorted(),
+ [],
+ { equals: (a, b) => a.length === b.length && a.every((id, index) => id === b[index]) },
+ ),
// Inputs are the pending user and synthetic items; compactions are control items.
input: {
list(sessionID: string) {
diff --git a/packages/cm-browser/README.md b/packages/cm-browser/README.md
index 677b6998c5..263246ee4a 100644
--- a/packages/cm-browser/README.md
+++ b/packages/cm-browser/README.md
@@ -2,6 +2,14 @@
The desktop browser uses main-owned Electron `WebContentsView` tabs. Tabs belong to a chat session and retain their pages when switching tabs, switching sessions, or hiding the browser panel. Closing a tab respects its `beforeunload` handler. Pop-ups open as new tabs and preserve normal opener behavior.
+## Backend trust and request limits
+
+The desktop trusts its authenticated V2 backend, installed plugins, and the task/session IDs that backend supplies across tasks. This boundary does not isolate tasks after backend compromise. Web pages remain untrusted. Main still checks native ownership, task grants, delegated leases, pause state, document identity, and delivery validity for each operation.
+
+The V2 browser RPC validates serialized request events against a 64 KiB UTF-8 budget before publishing them. The largest permitted typed input is 10,000 characters, at most 40,000 UTF-8 bytes; site-tool arguments have an 8 KiB limit, and delegation is limited to 16 tab IDs. These inputs fit within the envelope budget. Rejected events disconnect the browser port and settle its pending operations. The native bridge also caps active requests at 256. These are admission limits, not a guarantee against the memory required to construct an input or a compromised backend bypassing its own schema.
+
+Responses keep their existing RPC compatibility limit and main-owned snapshot/image budgets. The previous request-event ceiling was 20 Mi UTF-16 code units. Ordinary request parsing already drops unused fields. The 1 MiB unused-field probe demonstrated acceptance, without establishing lasting retention or an OOM. The legacy DOM assertion memory spike was measured separately.
+
## Autonomous agent browsing
CM Browser is the default desktop browser for agent tasks. The model starts with `browser_read_state`, creates a tab with `browser_create_tab` when needed, then uses `browser_navigate`. Creation initializes upload interception before authorizing the blank tab. Create, select and close use standing task authority for agent-controlled tabs, without routine native approval. Explicit OpenCode ask/deny rules still apply. Selecting or creating a tab reveals the browser panel.
diff --git a/packages/cm-browser/src/protocol.ts b/packages/cm-browser/src/protocol.ts
index d6ef695263..d857c98027 100644
--- a/packages/cm-browser/src/protocol.ts
+++ b/packages/cm-browser/src/protocol.ts
@@ -4,6 +4,7 @@ export const ALLOWLIST_FILENAME = "cm-browser-allowlist.json"
export const STATE_DIRECTORY_NAME = "CookieMonster"
export const MAX_URL_LENGTH = 2_048
export const MAX_TYPED_TEXT = 10_000
+export const MAX_REQUEST_BYTES = 64 * 1024
export const MAX_SNAPSHOT_BYTES = 64 * 1024
export const OPERATION_TIMEOUT_MS = 15_000
export const MAX_SCREENSHOT_EDGE = 4096
diff --git a/packages/cm-browser/src/rpc.ts b/packages/cm-browser/src/rpc.ts
index 9ec1a39ee8..17617fa7ad 100644
--- a/packages/cm-browser/src/rpc.ts
+++ b/packages/cm-browser/src/rpc.ts
@@ -1,8 +1,13 @@
import { Rpc } from "@opencode/schema/rpc"
import { z } from "zod"
+import { MAX_REQUEST_BYTES } from "./protocol"
const connectionID = z.string().regex(/^[a-f\d-]{36}$/)
const message = z.string().max(20 * 1024 * 1024)
+const requestMessage = z
+ .string()
+ .max(MAX_REQUEST_BYTES)
+ .refine((value) => Buffer.byteLength(value) <= MAX_REQUEST_BYTES, "Browser request exceeds 64 KiB")
export const BrowserRpc = Rpc.define({
id: "cookiemonster.browser",
methods: {
@@ -12,6 +17,6 @@ export const BrowserRpc = Rpc.define({
},
events: {
attached: { schema: z.object({ connectionID }) },
- request: { schema: z.object({ connectionID, message }) },
+ request: { schema: z.object({ connectionID, message: requestMessage }) },
},
})
diff --git a/packages/cm-browser/test/rpc-budget.test.ts b/packages/cm-browser/test/rpc-budget.test.ts
new file mode 100644
index 0000000000..a714366122
--- /dev/null
+++ b/packages/cm-browser/test/rpc-budget.test.ts
@@ -0,0 +1,67 @@
+import { expect, test } from "bun:test"
+import { mkdtemp, rm } from "node:fs/promises"
+import { join } from "node:path"
+import { tmpdir } from "node:os"
+import { OpenCode } from "@opencode/sdk"
+import { Plugin } from "@opencode/plugin"
+import { BrowserRpc } from "../src/rpc"
+import { MAX_REQUEST_BYTES, MAX_TYPED_TEXT } from "../src/protocol"
+
+test("the real RPC event boundary rejects oversized serialized browser requests in UTF-8 bytes", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "cm-browser-budget-"))
+ const ready = Promise.withResolvers<(message: string) => Promise>()
+ try {
+ await using host = await OpenCode.create({
+ config: { directory, project: false, content: "{}" },
+ models: { fetch: false },
+ fs: { filewatcher: false },
+ plugins: [
+ Plugin.define({
+ id: "browser-budget",
+ async setup(ctx) {
+ const rpc = await ctx.rpc.register(BrowserRpc, {
+ attach: async () => null,
+ detach: async () => null,
+ result: async () => null,
+ })
+ if (ctx.location.directory === directory)
+ ready.resolve((message) =>
+ rpc.events.emit("request", { connectionID: "00000000-0000-4000-8000-000000000001", message }),
+ )
+ return rpc.dispose
+ },
+ }),
+ ],
+ })
+ await host.model.list({ location: { directory } })
+ const emit = await ready.promise
+ const fill = JSON.stringify({
+ type: "browser_request",
+ id: "one",
+ sessionID: "task",
+ request: { op: "fill", tabID: "tab", ref: "element", text: "界".repeat(MAX_TYPED_TEXT) },
+ })
+ await expect(emit(fill)).resolves.toBeUndefined()
+ await expect(emit("x".repeat(MAX_REQUEST_BYTES))).resolves.toBeUndefined()
+ for (const message of [
+ "x".repeat(MAX_REQUEST_BYTES + 1),
+ "界".repeat(Math.ceil(MAX_REQUEST_BYTES / 3)),
+ JSON.stringify({
+ type: "browser_request",
+ id: "one",
+ sessionID: "task",
+ request: { op: "list_tabs" },
+ unused: "x".repeat(1024 * 1024),
+ }),
+ ]) {
+ const rejected = await emit(message).then(
+ () => false,
+ () => true,
+ )
+ expect(rejected).toBe(true)
+ }
+ await expect(emit(fill)).resolves.toBeUndefined()
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
+}, 20_000)
diff --git a/packages/core/package.json b/packages/core/package.json
index c249782e64..f1d67760e5 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -30,6 +30,10 @@
"./*": "./src/*.ts"
},
"imports": {
+ "#cm-ae-plugin": {
+ "workerd": "./src/cm-ae/plugin.workerd.ts",
+ "default": "./src/cm-ae/plugin.ts"
+ },
"#sqlite": {
"workerd": "./src/database/sqlite.workerd.ts",
"bun": "./src/database/sqlite.bun.ts",
diff --git a/packages/core/src/cm-ae/plugin.ts b/packages/core/src/cm-ae/plugin.ts
index 7b6c8dbc91..0c544a30b6 100644
--- a/packages/core/src/cm-ae/plugin.ts
+++ b/packages/core/src/cm-ae/plugin.ts
@@ -238,3 +238,5 @@ export const Plugin = {
)
}),
}
+
+export const plugins = [Plugin] as const
diff --git a/packages/core/src/cm-ae/plugin.workerd.ts b/packages/core/src/cm-ae/plugin.workerd.ts
new file mode 100644
index 0000000000..e826884ffb
--- /dev/null
+++ b/packages/core/src/cm-ae/plugin.workerd.ts
@@ -0,0 +1,4 @@
+export * as CmAePlugin from "./plugin.workerd.js"
+
+// The desktop bundle loader needs native files and dynamic imports unavailable in workerd.
+export const plugins = [] as const
diff --git a/packages/core/src/cm-ae/skills.ts b/packages/core/src/cm-ae/skills.ts
index 028c83a856..d56f92786c 100644
--- a/packages/core/src/cm-ae/skills.ts
+++ b/packages/core/src/cm-ae/skills.ts
@@ -2,6 +2,7 @@ import path from "node:path"
import { randomBytes } from "node:crypto"
import { stat } from "node:fs/promises"
import { AbsolutePath } from "@opencode/schema/schema"
+import { Glob } from "@opencode/util/glob"
import { Schema } from "effect"
import type { Skill } from "@opencode/schema/skill"
import { ManagedSkill } from "./managed.js"
@@ -29,11 +30,10 @@ export function skills(input: {
throw error
})
if (!exists) continue
- for await (const file of new Bun.Glob("**/SKILL.md").scan({
+ for (const file of await Glob.scan("**/SKILL.md", {
cwd: root,
absolute: true,
- onlyFiles: true,
- followSymlinks: true,
+ symlink: true,
}))
files.add(AbsolutePath.make(file))
}
diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts
index a026f6342a..2f8c50efc7 100644
--- a/packages/core/src/plugin/internal.ts
+++ b/packages/core/src/plugin/internal.ts
@@ -1,7 +1,7 @@
export * as PluginInternal from "./internal.js"
import { ScheduleRuntime } from "../schedule/runtime.js"
-import { CmAePlugin } from "../cm-ae/plugin.js"
+import { CmAePlugin } from "#cm-ae-plugin"
import { SchedulePlugin } from "../schedule/plugin.js"
import { LLMClient } from "@opencode/ai"
import type { Plugin } from "@opencode/plugin/effect/plugin"
@@ -290,6 +290,6 @@ export const list = Effect.fn("PluginInternal.list")(function* () {
)
return {
pre: resolve(pre),
- post: resolve(process.env.CM_DESKTOP === "1" ? [...post, SchedulePlugin.Plugin, CmAePlugin.Plugin] : post),
+ post: resolve(process.env.CM_DESKTOP === "1" ? [...post, SchedulePlugin.Plugin, ...CmAePlugin.plugins] : post),
}
})
diff --git a/packages/core/test/cm-ae-platform.test.ts b/packages/core/test/cm-ae-platform.test.ts
new file mode 100644
index 0000000000..2ecb96898e
--- /dev/null
+++ b/packages/core/test/cm-ae-platform.test.ts
@@ -0,0 +1,22 @@
+import { expect, test } from "bun:test"
+import { join } from "node:path"
+import { CmAePlugin } from "#cm-ae-plugin"
+
+test("native AE registration keeps the desktop plugin", () => {
+ expect(CmAePlugin.plugins).toHaveLength(1)
+ expect(CmAePlugin.plugins[0] === CmAePlugin.Plugin).toBe(true)
+})
+
+test("workerd omits the native AE bundle loader", () => {
+ const result = Bun.spawnSync(
+ [
+ process.execPath,
+ "--conditions=workerd",
+ "-e",
+ 'import { CmAePlugin } from "#cm-ae-plugin"; console.log(CmAePlugin.plugins.length)',
+ ],
+ { cwd: join(import.meta.dir, "..") },
+ )
+ expect(result.exitCode, result.stderr.toString()).toBe(0)
+ expect(result.stdout.toString().trim()).toBe("0")
+})
diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts
index be7576907f..fea5e6af2a 100644
--- a/packages/core/test/git.test.ts
+++ b/packages/core/test/git.test.ts
@@ -34,45 +34,52 @@ describe("Git", () => {
}),
)
- it.live("clones a remote and reads checkout metadata", () =>
- withRemote((fixture) =>
- Effect.gen(function* () {
- const git = yield* Git.Service
- const target = AbsolutePath.make(path.join(fixture.root, "checkout"))
- const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target })
-
- expect(yield* git.remote.get(repository)).toBe(fixture.remote)
- expect(yield* git.history.head(repository)).toBeString()
- expect(yield* git.history.branch(repository)).toBe("main")
- expect(yield* git.history.defaultRemoteBranch(repository)).toBe("main")
- expect(repository.worktree).toBe(target)
- expect(repository.gitDirectory).toBe(AbsolutePath.make(path.join(target, ".git")))
- expect(repository.commonDirectory).toBe(repository.gitDirectory)
- expect(yield* read(path.join(target, "README.md"))).toBe("one\n")
- }),
- ),
+ // These fixtures launch several Git processes; hosted Windows cold starts can exceed five seconds.
+ it.live(
+ "clones a remote and reads checkout metadata",
+ () =>
+ withRemote((fixture) =>
+ Effect.gen(function* () {
+ const git = yield* Git.Service
+ const target = AbsolutePath.make(path.join(fixture.root, "checkout"))
+ const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target })
+
+ expect(yield* git.remote.get(repository)).toBe(fixture.remote)
+ expect(yield* git.history.head(repository)).toBeString()
+ expect(yield* git.history.branch(repository)).toBe("main")
+ expect(yield* git.history.defaultRemoteBranch(repository)).toBe("main")
+ expect(repository.worktree).toBe(target)
+ expect(repository.gitDirectory).toBe(AbsolutePath.make(path.join(target, ".git")))
+ expect(repository.commonDirectory).toBe(repository.gitDirectory)
+ expect(yield* read(path.join(target, "README.md"))).toBe("one\n")
+ }),
+ ),
+ { timeout: 15_000 },
)
- it.live("fetches, checks out, and resets remote changes", () =>
- withRemote((fixture) =>
- Effect.gen(function* () {
- const git = yield* Git.Service
- const target = AbsolutePath.make(path.join(fixture.root, "checkout"))
- const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target })
-
- yield* Effect.promise(() => commit(fixture.source, "two\n", "second"))
- yield* git.sync.fetchRemotes(repository)
- yield* git.sync.resetHard(repository, "origin/main")
- expect(yield* read(path.join(target, "README.md"))).toBe("two\n")
-
- yield* Effect.promise(() => branch(fixture.source, "feature/docs", "feature\n"))
- yield* git.sync.fetchBranch(repository, { branch: "feature/docs" })
- yield* git.sync.checkoutRemoteBranch(repository, { branch: "feature/docs" })
- yield* git.sync.resetHard(repository, "origin/feature/docs")
- expect(yield* git.history.branch(repository)).toBe("feature/docs")
- expect(yield* read(path.join(target, "README.md"))).toBe("feature\n")
- }),
- ),
+ it.live(
+ "fetches, checks out, and resets remote changes",
+ () =>
+ withRemote((fixture) =>
+ Effect.gen(function* () {
+ const git = yield* Git.Service
+ const target = AbsolutePath.make(path.join(fixture.root, "checkout"))
+ const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target })
+
+ yield* Effect.promise(() => commit(fixture.source, "two\n", "second"))
+ yield* git.sync.fetchRemotes(repository)
+ yield* git.sync.resetHard(repository, "origin/main")
+ expect(yield* read(path.join(target, "README.md"))).toBe("two\n")
+
+ yield* Effect.promise(() => branch(fixture.source, "feature/docs", "feature\n"))
+ yield* git.sync.fetchBranch(repository, { branch: "feature/docs" })
+ yield* git.sync.checkoutRemoteBranch(repository, { branch: "feature/docs" })
+ yield* git.sync.resetHard(repository, "origin/feature/docs")
+ expect(yield* git.history.branch(repository)).toBe("feature/docs")
+ expect(yield* read(path.join(target, "README.md"))).toBe("feature\n")
+ }),
+ ),
+ { timeout: 15_000 },
)
})
diff --git a/packages/core/test/snapshot.test.ts b/packages/core/test/snapshot.test.ts
index b725e6377f..4d4081a202 100644
--- a/packages/core/test/snapshot.test.ts
+++ b/packages/core/test/snapshot.test.ts
@@ -158,38 +158,42 @@ describe("Snapshot", () => {
),
)
- testEffect(Layer.empty).live("captures concurrently from independent processes", () =>
- Effect.acquireUseRelease(
- Effect.promise(() => tmpdir()),
- (tmp) =>
- Effect.gen(function* () {
- const project = path.join(tmp.path, "project")
- yield* Effect.promise(async () => {
- await fs.mkdir(project)
- await Promise.all(
- Array.from({ length: 200 }, (_, index) =>
- fs.writeFile(path.join(project, `f${index}.txt`), `${index}\n`),
- ),
- )
- await initGit(project, true)
- })
- // Each layer owns its own Git service, so their in-process locks do not coordinate.
- const writer = (id: number) =>
- Effect.gen(function* () {
- const snapshot = yield* Snapshot.Service
- return yield* Effect.forEach(
- Array.from({ length: 8 }, (_, index) => index),
- (index) =>
- Effect.promise(() => fs.writeFile(path.join(project, `writer-${id}.txt`), `${index}\n`)).pipe(
- Effect.andThen(snapshot.capture()),
- ),
+ // Keep the concurrent Git workload intact while allowing hosted Windows process startup.
+ testEffect(Layer.empty).live(
+ "captures concurrently from independent processes",
+ () =>
+ Effect.acquireUseRelease(
+ Effect.promise(() => tmpdir()),
+ (tmp) =>
+ Effect.gen(function* () {
+ const project = path.join(tmp.path, "project")
+ yield* Effect.promise(async () => {
+ await fs.mkdir(project)
+ await Promise.all(
+ Array.from({ length: 200 }, (_, index) =>
+ fs.writeFile(path.join(project, `f${index}.txt`), `${index}\n`),
+ ),
)
- }).pipe(Effect.provide(snapshotLayer(tmp.path, project)))
- const results = yield* Effect.all([writer(0), writer(1), writer(2)], { concurrency: "unbounded" })
- expect(results.flat().every((tree) => tree !== undefined)).toBe(true)
- }),
- (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
- ),
+ await initGit(project, true)
+ })
+ // Each layer owns its own Git service, so their in-process locks do not coordinate.
+ const writer = (id: number) =>
+ Effect.gen(function* () {
+ const snapshot = yield* Snapshot.Service
+ return yield* Effect.forEach(
+ Array.from({ length: 8 }, (_, index) => index),
+ (index) =>
+ Effect.promise(() => fs.writeFile(path.join(project, `writer-${id}.txt`), `${index}\n`)).pipe(
+ Effect.andThen(snapshot.capture()),
+ ),
+ )
+ }).pipe(Effect.provide(snapshotLayer(tmp.path, project)))
+ const results = yield* Effect.all([writer(0), writer(1), writer(2)], { concurrency: "unbounded" })
+ expect(results.flat().every((tree) => tree !== undefined)).toBe(true)
+ }),
+ (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
+ ),
+ { timeout: 15_000 },
)
testEffect(Layer.empty).live("captures a Location in a directory whose name starts with two dots", () =>
diff --git a/packages/desktop/README.md b/packages/desktop/README.md
index ce5a4e1a27..5ada061d13 100644
--- a/packages/desktop/README.md
+++ b/packages/desktop/README.md
@@ -77,6 +77,14 @@ CLI preparation uses these channel rules:
default. `bun dev --download-server ` instead downloads that CLI version for local development. Neither path
requires `OPENCODE_CLI_DIST` or runs the production prebuild.
+## CookieMonster Linux launcher migration
+
+Branded packages use `com.ogilvy.cookiemonster` for their executable, desktop entry, icon basename, window class, and metainfo. The app keeps its existing `com.ogilvy.cookiemonster` profile directory, including WPP sign-in and settings. Packaging identity is independent of whether WPP is enabled.
+
+Earlier CookieMonster packages installed OpenCode-named launchers and icons. Upgrading removes those obsolete package-owned files; an upstream OpenCode installation supplies its own. If a pinned CookieMonster launcher stops resolving, remove that old pin and pin the new CookieMonster entry. CookieMonster deliberately supplies no OpenCode-named compatibility launcher, so installing or removing it cannot replace upstream OpenCode's files.
+
+After producing a branded Debian archive, run `bun scripts/check-cm-linux.ts /path/to/cookiemonster.deb` from this package. The check rejects upstream launcher/icon/metainfo paths and verifies the installed desktop entry. Installation and removal coexistence must also be checked in a disposable environment.
+
## Startup benchmark
`bun run bench:startup` measures a **packaged** build from process spawn to the restored tab being ready and the
diff --git a/packages/desktop/electron-builder.config.test.ts b/packages/desktop/electron-builder.config.test.ts
index f9e62d8033..e6e3ff0552 100644
--- a/packages/desktop/electron-builder.config.test.ts
+++ b/packages/desktop/electron-builder.config.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from "bun:test"
import { statSync } from "node:fs"
-import { cp, mkdtemp, rm } from "node:fs/promises"
+import { cp, mkdir, mkdtemp, rm } from "node:fs/promises"
import { createRequire } from "node:module"
import os from "node:os"
import path from "node:path"
@@ -18,7 +18,11 @@ const channels = [
{ channel: "prod", appId: "ai.opencode.desktop" },
] as const
-function load(channel: string, target?: string): Configuration {
+function load(channel: string, target?: string, branded = false, wpp = false): Configuration {
+ const previousWpp = process.env.CM_WPP
+ process.env.CM_WPP = wpp ? "1" : "0"
+ const previousBrand = process.env.CM_BRAND
+ process.env.CM_BRAND = branded ? "1" : "0"
const previous = process.env.OPENCODE_CHANNEL
const previousTarget = process.env.OPENCODE_CLI_TARGET
process.env.OPENCODE_CHANNEL = channel
@@ -29,6 +33,11 @@ function load(channel: string, target?: string): Configuration {
try {
return getConfig()
} finally {
+ if (previousWpp === undefined) delete process.env.CM_WPP
+ else process.env.CM_WPP = previousWpp
+
+ if (previousBrand === undefined) delete process.env.CM_BRAND
+ else process.env.CM_BRAND = previousBrand
delete process.env.OPENCODE_CHANNEL
delete process.env.OPENCODE_CLI_TARGET
@@ -177,3 +186,54 @@ test("the trimmed Zip.js package can still export compressed logs", async () =>
await rm(dir, { recursive: true, force: true })
}
})
+
+test.each(channels)("CookieMonster identity is derived before Linux fields for $channel", ({ channel }) => {
+ const config = load(channel, undefined, true)
+ const id = "com.ogilvy.cookiemonster"
+ expect(config.appId).toBe(id)
+ expect(config.productName).toBe("CookieMonster")
+ expect(config.protocols).toEqual({ name: "CookieMonster", schemes: ["opencode"] })
+ expect(config.extraMetadata?.desktopName).toBe(`${id}.desktop`)
+ expect(config.linux?.executableName).toBe(id)
+ expect(config.linux?.desktop?.entry?.StartupWMClass).toBe(id)
+ expect(config.rpm?.packageName).toBe("cookiemonster")
+
+ for (const fpm of [config.deb?.fpm, config.rpm?.fpm]) {
+ expect(fpm).toHaveLength(1)
+ expect(fpm?.[0]).toEndWith(`=/usr/share/metainfo/${id}.metainfo.xml`)
+ }
+})
+
+test.each([false, true])("metainfo uses the same branded=%s desktop identity as packaging", async (branded) => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "desktop-metainfo-"))
+
+ try {
+ await mkdir(path.join(directory, "resources"))
+
+ const result = Bun.spawnSync(
+ [process.execPath, path.join(import.meta.dirname, "scripts/copy-metainfo.ts"), "prod"],
+ {
+ cwd: directory,
+ env: { ...process.env, CM_BRAND: branded ? "1" : "0" },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ )
+
+ expect(result.exitCode, Buffer.concat([result.stdout, result.stderr]).toString()).toBe(0)
+ const id = branded ? "com.ogilvy.cookiemonster" : "ai.opencode.desktop"
+ const xml = await Bun.file(path.join(directory, "resources", `${id}.metainfo.xml`)).text()
+ expect(xml).toContain(`${id}`)
+ expect(xml).toContain(`${id}.desktop`)
+ expect(xml).toContain(`${branded ? "CookieMonster" : "OpenCode"}`)
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
+})
+
+test.each([false, true])("WPP sign-in protocol follows the optional WPP build: %s", (wpp) => {
+ expect(load("prod", undefined, true, wpp).protocols).toEqual({
+ name: "CookieMonster",
+ schemes: wpp ? ["opencode", "cookiemonster"] : ["opencode"],
+ })
+})
diff --git a/packages/desktop/electron-builder.config.ts b/packages/desktop/electron-builder.config.ts
index 5aa01176b1..f5b21a216d 100644
--- a/packages/desktop/electron-builder.config.ts
+++ b/packages/desktop/electron-builder.config.ts
@@ -8,6 +8,7 @@ import type { CustomMacSignOptions } from "app-builder-lib"
import { Arch, type Configuration } from "electron-builder"
import { NativeArch } from "../../script/native-arch"
import { CLI_BINARIES, getCurrentCli, nodePtyPackage } from "./scripts/utils"
+import { desktopIdentity } from "./scripts/identity"
const execFileAsync = promisify(execFile)
@@ -63,17 +64,20 @@ function resolveChannel() {
return "dev"
}
-const APP_IDS = {
- dev: "ai.opencode.desktop.dev",
- beta: "ai.opencode.desktop.beta",
- prod: "ai.opencode.desktop",
-} as const
-
const getBase = (appId: string): Configuration => {
const target = getCurrentCli()
return {
artifactName: "opencode-desktop-${os}-${arch}.${ext}",
+ afterAllArtifactBuild: async (context) => {
+ if (appId === "com.ogilvy.cookiemonster") {
+ for (const artifact of context.artifactPaths.filter((file) => file.endsWith(".deb"))) {
+ await execFileAsync("bun", [path.join(packageDir, "scripts/check-cm-linux.ts"), artifact])
+ }
+ }
+
+ return []
+ },
directories: {
output: "dist",
buildResources: "resources",
@@ -176,10 +180,6 @@ const getBase = (appId: string): Configuration => {
notarize: true,
target: ["dmg", "zip"],
},
- protocols: {
- name: "OpenCode",
- schemes: ["opencode"],
- },
win: {
icon: `resources/icons/icon.ico`,
signtoolOptions: {
@@ -213,17 +213,23 @@ const getBase = (appId: string): Configuration => {
export function getConfig() {
const channel = resolveChannel()
- const appId = APP_IDS[channel]
+ const identity = desktopIdentity(channel)
+ const appId = identity.appId
const base = getBase(appId)
+ base.protocols = {
+ name: appId === "com.ogilvy.cookiemonster" ? "CookieMonster" : channel === "beta" ? "OpenCode Beta" : "OpenCode",
+ schemes:
+ appId === "com.ogilvy.cookiemonster" && process.env.CM_WPP === "1" ? ["opencode", "cookiemonster"] : ["opencode"],
+ }
switch (channel) {
case "dev": {
return {
...base,
appId,
- productName: "OpenCode Dev",
+ productName: identity.productName,
deb: { fpm: [metainfoFpm(appId)] },
- rpm: { packageName: "opencode-dev", fpm: [metainfoFpm(appId)] },
+ rpm: { packageName: identity.packageName, fpm: [metainfoFpm(appId)] },
}
}
@@ -231,15 +237,14 @@ export function getConfig() {
return {
...base,
appId,
- productName: "OpenCode Beta",
- protocols: { name: "OpenCode Beta", schemes: ["opencode"] },
+ productName: identity.productName,
publish: {
provider: "generic",
url: "https://opencode.ai/update/api/beta/desktop/opencode/",
channel: "latest",
},
deb: { fpm: [metainfoFpm(appId)] },
- rpm: { packageName: "opencode-beta", fpm: [metainfoFpm(appId)] },
+ rpm: { packageName: identity.packageName, fpm: [metainfoFpm(appId)] },
}
}
@@ -247,15 +252,17 @@ export function getConfig() {
return {
...base,
appId,
- productName: "OpenCode",
- protocols: { name: "OpenCode", schemes: ["opencode"] },
+ productName: identity.productName,
publish: {
provider: "generic",
url: "https://opencode.ai/update/api/latest/desktop/opencode/",
channel: "latest",
},
- deb: { fpm: [metainfoFpm(appId), legacyDesktopEntryFpm] },
- rpm: { packageName: "opencode", fpm: [metainfoFpm(appId), legacyDesktopEntryFpm] },
+ deb: { fpm: [metainfoFpm(appId), ...(appId === "ai.opencode.desktop" ? [legacyDesktopEntryFpm] : [])] },
+ rpm: {
+ packageName: identity.packageName,
+ fpm: [metainfoFpm(appId), ...(appId === "ai.opencode.desktop" ? [legacyDesktopEntryFpm] : [])],
+ },
}
}
}
@@ -267,36 +274,31 @@ const branded = process.env.CM_BRAND === "1"
const unsigned = process.env.CM_UNSIGNED === "1"
-const brandedConfig: Configuration = {
- ...config,
- ...(branded
- ? {
- appId: "com.ogilvy.cookiemonster",
- productName: "CookieMonster",
- artifactName: "cookiemonster-${os}-${arch}.${ext}",
- extraMetadata: {
- ...config.extraMetadata,
- cmUserInstall: true,
- ...(process.env.CM_VERSION ? { version: process.env.CM_VERSION } : {}),
- },
- extraResources: [
- ...(config.extraResources ?? []),
- { from: "resources/cm-plugins", to: "cm-plugins" },
- { from: "resources/vault-auth", to: "vault-auth" },
- { from: "resources/cm-ae", to: "cm-ae" },
+const brandedConfig: Configuration = branded
+ ? {
+ ...config,
+ artifactName: "cookiemonster-${os}-${arch}.${ext}",
+ extraMetadata: { ...config.extraMetadata, cmUserInstall: true },
+ extraResources: [
+ ...(config.extraResources ?? []),
+ { from: "resources/cm-plugins", to: "cm-plugins" },
+ { from: "resources/vault-auth", to: "vault-auth" },
+ { from: "resources/cm-ae", to: "cm-ae" },
+ ],
+ dmg: {
+ backgroundColor: "#ffffff",
+ window: { width: 540, height: 360 },
+ contents: [
+ { x: 160, y: 160, type: "file" },
+ { x: 380, y: 160, type: "file", path: path.join(packageDir, "resources", "Install CookieMonster.txt") },
],
- dmg: {
- backgroundColor: "#ffffff",
- window: { width: 540, height: 360 },
- contents: [
- { x: 160, y: 160, type: "file" },
- { x: 380, y: 160, type: "file", path: path.join(packageDir, "resources", "Install CookieMonster.txt") },
- ],
- },
- publish: { provider: "github", owner: "trmosala", repo: "opencode", channel: "latest" },
- }
- : {}),
-}
+ },
+ publish: { provider: "github", owner: "trmosala", repo: "opencode", channel: "latest" },
+ }
+ : config
+
+if (branded && process.env.CM_VERSION)
+ brandedConfig.extraMetadata = { ...brandedConfig.extraMetadata, version: process.env.CM_VERSION }
export default unsigned
? ({
diff --git a/packages/desktop/electron.vite.config.test.ts b/packages/desktop/electron.vite.config.test.ts
index bde2052332..b66b4b77ca 100644
--- a/packages/desktop/electron.vite.config.test.ts
+++ b/packages/desktop/electron.vite.config.test.ts
@@ -39,7 +39,7 @@ test("minifies only builds, previews onboarding only in development, and ships s
process.env.OPENCODE_CLI_TARGET = item.target
const main = (await load("build")).config.main
expect(main?.build?.externalizeDeps).toEqual({
- exclude: bundled,
+ exclude: ["@cookiemonster/wpp", ...bundled],
include: [nodePtyPackage(item.target)],
})
}
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index 9f5cca8ce0..730a008ae2 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -11,7 +11,7 @@
},
"scripts": {
"typecheck": "tsgo -b",
- "test": "bun test --timeout 30000",
+ "test": "bun test --preload ./test/preload.ts --timeout 30000",
"dev": "bun ./scripts/dev.ts",
"migration": "bun ./scripts/migration.ts",
"prebuild": "bun ./scripts/prebuild.ts",
diff --git a/packages/desktop/scripts/check-cm-linux.ts b/packages/desktop/scripts/check-cm-linux.ts
new file mode 100644
index 0000000000..423a2b96a8
--- /dev/null
+++ b/packages/desktop/scripts/check-cm-linux.ts
@@ -0,0 +1,56 @@
+import assert from "node:assert/strict"
+import { $ } from "bun"
+
+const artifact = process.argv[2]
+
+assert(artifact?.endsWith(".deb"), "Pass a CookieMonster Debian archive")
+
+const id = "com.ogilvy.cookiemonster"
+
+const entries = (await $`dpkg-deb --fsys-tarfile ${artifact} | tar -tf -`.text())
+ .split("\n")
+ .map((entry) => entry.replace(/^\.\//, ""))
+ .filter(Boolean)
+
+assert.equal((await $`dpkg-deb -f ${artifact} Package`.text()).trim(), "cookiemonster")
+
+assert(entries.includes(`usr/share/applications/${id}.desktop`), "CookieMonster desktop entry is missing")
+
+assert(entries.includes(`usr/share/metainfo/${id}.metainfo.xml`), "CookieMonster metainfo is missing")
+
+assert(entries.includes(`opt/CookieMonster/${id}`), "CookieMonster executable has the wrong name")
+
+assert(
+ entries.some((entry) => entry.startsWith("usr/share/icons/") && entry.endsWith(`/${id}.png`)),
+ "CookieMonster icons are missing",
+)
+
+const collisions = entries.filter(
+ (entry) =>
+ entry.startsWith("usr/share/applications/ai.opencode.") ||
+ entry === "usr/share/applications/opencode-desktop.desktop" ||
+ entry.startsWith("usr/share/metainfo/ai.opencode.") ||
+ (entry.startsWith("usr/share/icons/") && /\/(?:ai\.opencode\.|opencode-desktop\.)/.test(entry)),
+)
+
+assert.deepEqual(collisions, [], "CookieMonster archive contains upstream-owned launcher or icon paths")
+
+const desktop = await $`dpkg-deb --fsys-tarfile ${artifact} | tar -xOf - ./usr/share/applications/${id}.desktop`.text()
+
+assert.match(desktop, new RegExp(`^StartupWMClass=${id.replaceAll(".", "\\.")}$`, "m"))
+
+assert(desktop.includes(`Icon=${id}\n`), "Desktop icon identity differs from its file name")
+
+assert(desktop.includes(`/CookieMonster/${id}`), "Desktop launcher points at the wrong executable")
+
+const metadata =
+ await $`dpkg-deb --fsys-tarfile ${artifact} | tar -xOf - ./usr/share/metainfo/${id}.metainfo.xml`.text()
+
+assert(metadata.includes(`${id}`), "Metainfo identity differs from packaging")
+
+assert(
+ metadata.includes(`${id}.desktop`),
+ "Metainfo points at the wrong launcher",
+)
+
+console.log(JSON.stringify({ artifact, appId: id, entries: entries.length, result: "pass" }))
diff --git a/packages/desktop/scripts/check-mac-activation.ts b/packages/desktop/scripts/check-mac-activation.ts
new file mode 100644
index 0000000000..3967c62726
--- /dev/null
+++ b/packages/desktop/scripts/check-mac-activation.ts
@@ -0,0 +1,228 @@
+import { join } from "node:path"
+import { Schema } from "effect"
+
+if (process.platform !== "darwin") throw new Error("Packaged activation must be checked on macOS.")
+
+const bundle = process.argv[2]
+
+if (!bundle?.endsWith("/CookieMonster.app")) throw new Error("Pass the owned packaged CookieMonster.app path.")
+
+const executable = Bun.spawnSync([
+ "/usr/libexec/PlistBuddy",
+ "-c",
+ "Print :CFBundleExecutable",
+ join(bundle, "Contents/Info.plist"),
+])
+
+if (executable.exitCode !== 0) throw new Error("Could not read the packaged executable.")
+
+const child = Bun.spawn(
+ [join(bundle, "Contents/MacOS", executable.stdout.toString().trim()), "--inspect=127.0.0.1:9347"],
+ { stdout: "inherit", stderr: "inherit" },
+)
+
+const Evaluation = Schema.Struct({
+ result: Schema.Struct({ value: Schema.optionalKey(Schema.Boolean) }),
+ exceptionDetails: Schema.optionalKey(
+ Schema.Struct({
+ text: Schema.String,
+ exception: Schema.optionalKey(Schema.Struct({ description: Schema.optionalKey(Schema.String) })),
+ }),
+ ),
+})
+
+const waiting = new Map void; reject: (error: Error) => void }>()
+
+const Reply = Schema.Struct({
+ id: Schema.optionalKey(Schema.Number),
+ result: Schema.optionalKey(Evaluation),
+ error: Schema.optionalKey(Schema.Struct({ message: Schema.String })),
+})
+
+const Targets = Schema.Array(Schema.Struct({ type: Schema.String, webSocketDebuggerUrl: Schema.String }))
+
+let socket: WebSocket | undefined
+
+let sequence = 0
+
+try {
+ const deadline = Date.now() + 30_000
+
+ while (!socket && Date.now() < deadline) {
+ const response = await fetch("http://127.0.0.1:9347/json/list", { signal: AbortSignal.timeout(500) }).catch(
+ () => undefined,
+ )
+
+ if (response?.ok) {
+ const target = Schema.decodeUnknownSync(Targets)(await response.json()).find((target) => target.type === "node")
+
+ if (target) socket = new WebSocket(target.webSocketDebuggerUrl)
+ }
+
+ if (!socket) await Bun.sleep(100)
+ }
+
+ const connection = socket
+
+ if (!connection) throw new Error("The owned packaged app did not open its inspector.")
+ await new Promise((resolve, reject) => {
+ connection.addEventListener("open", () => resolve(), { once: true })
+ connection.addEventListener("error", () => reject(new Error("Packaged inspector connection failed.")), {
+ once: true,
+ })
+ })
+ connection.addEventListener("message", (event) => {
+ const reply = Schema.decodeUnknownSync(Reply)(JSON.parse(String(event.data)))
+
+ if (reply.id === undefined) return
+ const request = waiting.get(reply.id)
+ waiting.delete(reply.id)
+
+ if (reply.error) request?.reject(new Error(reply.error.message))
+ else if (reply.result) request?.resolve(reply.result)
+ })
+
+ const evaluate = async (expression: string) => {
+ const id = ++sequence
+
+ const result = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ waiting.delete(id)
+ reject(new Error("Packaged inspector request timed out."))
+ }, 5000)
+
+ waiting.set(id, {
+ resolve: (value) => {
+ clearTimeout(timer)
+ resolve(value)
+ },
+ reject: (error) => {
+ clearTimeout(timer)
+ reject(error)
+ },
+ })
+ // Inspector interrupts can reenter Node's module loader before its initialization finishes.
+ connection.send(
+ JSON.stringify({
+ id,
+ method: "Runtime.evaluate",
+ params: {
+ expression: `new Promise(resolve => process.nextTick(() => setImmediate(resolve))).then(() => (${expression}))`,
+ returnByValue: true,
+ awaitPromise: true,
+ },
+ }),
+ )
+ })
+
+ if (result.exceptionDetails)
+ throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text)
+
+ if (result.result.value === undefined) throw new Error("Packaged activation did not return a boolean.")
+
+ return result.result.value
+ }
+
+ if (!(await evaluate(`process.pid === ${child.pid}`)))
+ throw new Error("Inspector belongs to another process; refusing to operate it.")
+ const native = `process.getBuiltinModule('module').createRequire(process.execPath)('electron')`
+ const usable = `Boolean(${native}.BrowserWindow?.getAllWindows().some(w => w !== globalThis.__cmActivationWorker && w.isVisible() && w.webContents.getURL().startsWith('oc://renderer/')))`
+
+ const waitFor = async (stage: string, expression: string) => {
+ console.log(`Checking packaged activation: ${stage}`)
+ const deadline = Date.now() + 30_000
+
+ while (Date.now() < deadline) {
+ if (await evaluate(expression)) return
+ await Bun.sleep(100)
+ }
+
+ await evaluate(`(() => {
+ const {app, BrowserWindow} = ${native};
+ console.log(JSON.stringify({
+ stage: ${JSON.stringify(stage)},
+ ready: app?.isReady(),
+ activationHandlers: app?.listenerCount('activate'),
+ activationEvents: globalThis.__cmActivationEvents ?? 0,
+ windows: BrowserWindow?.getAllWindows().map(window => {
+ const url = URL.parse(window.webContents.getURL());
+ return {
+ id: window.id,
+ visible: window.isVisible(),
+ minimized: window.isMinimized(),
+ loading: window.webContents.isLoading(),
+ page: url ? url.protocol + '//' + url.host + url.pathname : '',
+ worker: window === globalThis.__cmActivationWorker,
+ };
+ }),
+ }));
+ return true;
+ })()`)
+ throw new Error(`Packaged activation condition timed out: ${stage}`)
+ }
+
+ // The inspector can precede BrowserWindow exports; the early window also needs lifecycle adoption before close.
+ await waitFor(
+ "initial main window and lifecycle adoption",
+ `${usable} && ${native}.app.listenerCount('activate') > 0`,
+ )
+
+ if (!(await evaluate(`${native}.app.isPackaged`))) throw new Error("This must exercise a packaged application.")
+ await evaluate(`(() => {
+ const {app, BrowserWindow} = ${native};
+ globalThis.__cmActivationEvents = 0;
+ app.on('activate', () => globalThis.__cmActivationEvents++);
+ globalThis.__cmActivationWorker = new BrowserWindow({show:false, webPreferences:{sandbox:true,contextIsolation:true,nodeIntegration:false}});
+ BrowserWindow.getAllWindows().filter(w => w !== globalThis.__cmActivationWorker).forEach(w => w.close());
+ app.hide();
+ return true;
+ })()`)
+ await waitFor(
+ "main windows closed with hidden worker preserved",
+ `${native}.BrowserWindow.getAllWindows().length === 1 && !globalThis.__cmActivationWorker.isDestroyed()`,
+ )
+
+ // Dock clicks send reopen; activate alone only brings the application to the foreground.
+ const activation = Bun.spawn(
+ [
+ "/usr/bin/osascript",
+ "-e",
+ `tell application ${JSON.stringify(bundle)} to reopen`,
+ "-e",
+ `tell application ${JSON.stringify(bundle)} to activate`,
+ ],
+ { stdout: "inherit", stderr: "inherit" },
+ )
+
+ const activationTimer = setTimeout(() => activation.kill("SIGTERM"), 15_000)
+ const activationCode = await activation.exited
+ clearTimeout(activationTimer)
+
+ if (activationCode !== 0) throw new Error("macOS could not activate the owned packaged app.")
+ await waitFor(
+ "native activation and restored visible main window",
+ `globalThis.__cmActivationEvents > 0 && ${usable}`,
+ )
+
+ if (!(await evaluate(`!globalThis.__cmActivationWorker.isDestroyed()`)))
+ throw new Error("Activation destroyed the hidden worker.")
+ console.log(
+ JSON.stringify({
+ result: "pass",
+ packaged: true,
+ platform: "darwin",
+ nativeActivation: true,
+ mainWindowRestored: true,
+ hiddenWorkerPreserved: true,
+ }),
+ )
+} finally {
+ socket?.close()
+
+ if (child.exitCode === null) {
+ child.kill("SIGTERM")
+ const timer = setTimeout(() => child.kill("SIGKILL"), 5000)
+ await child.exited
+ clearTimeout(timer)
+ }
+}
diff --git a/packages/desktop/scripts/copy-metainfo.ts b/packages/desktop/scripts/copy-metainfo.ts
index 0ad4b3e426..fcc734aa12 100644
--- a/packages/desktop/scripts/copy-metainfo.ts
+++ b/packages/desktop/scripts/copy-metainfo.ts
@@ -1,12 +1,19 @@
import { resolveChannel } from "./utils"
+import { desktopIdentity } from "./identity"
const arg = process.argv[2]
const channel = arg === "dev" || arg === "beta" || arg === "prod" ? arg : resolveChannel()
-const appId = channel === "prod" ? "ai.opencode.desktop" : `ai.opencode.desktop.${channel}`
+const identity = desktopIdentity(channel)
-const productName = channel === "prod" ? "OpenCode" : `OpenCode ${channel.charAt(0).toUpperCase() + channel.slice(1)}`
+const appId = identity.appId
+
+const productName = identity.productName
+
+const branded = process.env.CM_BRAND === "1"
+
+const repository = branded ? "https://github.com/trmosala/opencode" : "https://github.com/anomalyco/opencode"
const summary = `Open source AI coding agent${channel !== "prod" ? ` (${channel})` : ""}`
@@ -20,13 +27,13 @@ const xml = `
${productName}${summary}
-
- Anomaly Innovations Inc.
+
+ ${branded ? "CookieMonster contributors" : "Anomaly Innovations Inc."}
- OpenCode is an open source agent that helps you write and run code with any AI model.
+ ${branded ? productName : "OpenCode"} is an open source agent that helps you write and run code with any AI model.