Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat: add signed desktop updates with explicit restart

Rach Pradhan4c83fc58863b
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml
new file mode 100644
index 00000000..73016f93
--- /dev/null
+++ b/.github/workflows/desktop.yml
@@ -0,0 +1,25 @@
+name: desktop
+on:
+ pull_request:
+ paths: ['apps/native/**', '.github/workflows/desktop.yml']
+ push:
+ branches: [main]
+ paths: ['apps/native/**', '.github/workflows/desktop.yml']
+permissions:
+ contents: read
+jobs:
+ desktop:
+ runs-on: macos-14
+ timeout-minutes: 15
+ defaults:
+ run:
+ working-directory: apps/native
+ steps:
+ - uses: actions/checkout@v7
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: '1.4.2'
+ - run: bun install --frozen-lockfile
+ - run: bun run test:desktop
+ - run: bun run build
+ - run: bun build electron/updater-runtime.cjs --target=node --format=cjs --external electron --outfile /tmp/updater-runtime.cjs
diff --git a/README.md b/README.md
index 46507a91..de3b6631 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@
curl -fsSL https://github.com/justrach/codegraff/releases/latest/download/install.sh | sh
```
-<p align="center"><a href="https://github.com/justrach/codegraff/releases/download/v0.0.290/Codegraff-macos-arm64.dmg"><strong>Download CodeGraff for Mac</strong></a><br><sub>Apple Silicon · macOS 14+ · signed and notarized · everything included</sub></p>
+<p align="center"><a href="https://github.com/justrach/codegraff/releases/download/v0.0.291/Codegraff-macos-arm64.dmg"><strong>Download CodeGraff for Mac</strong></a><br><sub>Apple Silicon · macOS 14+ · signed and notarized · everything included</sub></p>
**Evaluated on FrontierHarness tasks.** Graff includes a reproducible
[FrontierHarness evaluation runner](graff-evals/frontier-harness/README.md),
@@ -138,13 +138,18 @@ next step supplied with useful information while reducing repeated input.
## Install
**Desktop (Apple Silicon, macOS 14+).**
-[Download CodeGraff v0.0.290](https://github.com/justrach/codegraff/releases/download/v0.0.290/Codegraff-macos-arm64.dmg),
+[Download CodeGraff v0.0.291](https://github.com/justrach/codegraff/releases/download/v0.0.291/Codegraff-macos-arm64.dmg),
open the disk image, and drag **Codegraff.app** onto **Applications**. Eject the disk image and open Codegraff from Applications.
The notarized bundle includes Graff, Chromium, Bun and the native macOS components;
you do not need a separate CLI, runtime, developer tools or local server.
-[Verify the download checksum](https://github.com/justrach/codegraff/releases/download/v0.0.290/Codegraff-DMG-SHA256SUMS).
+[Verify the download checksum](https://github.com/justrach/codegraff/releases/download/v0.0.291/Codegraff-DMG-SHA256SUMS).
For a `graff` command in your terminal, use the CLI installer below.
+Desktop builds from v0.0.291 check for updates online and download them in the
+background. Choose **Restart to update** when your work is finished, or use
+**Codegraff → Check for Updates…**. Automatic downloads can be disabled in that
+menu. Earlier builds need one manual installation to enable the updater.
+
**CLI (macOS · Linux · Windows).**
```sh
diff --git a/apps/native/app/layout.tsx b/apps/native/app/layout.tsx
index 46e13b79..73f39d26 100644
--- a/apps/native/app/layout.tsx
+++ b/apps/native/app/layout.tsx
@@ -5,6 +5,7 @@ import "./appearance.css";
import { appearanceScript } from "@/lib/appearance";
import { ThemeSync } from "@/components/site/ThemeSync";
import DesktopTitlebar from "@/components/site/DesktopTitlebar";
+import DesktopUpdates from "@/components/site/DesktopUpdates";
import { BrowserWarm } from "@/components/site/BrowserWarm";
const inter = Geist({
@@ -35,6 +36,7 @@ export default function RootLayout({
<ThemeSync />
<BrowserWarm />
<DesktopTitlebar />
+ <DesktopUpdates />
{children}
</body>
</html>
diff --git a/apps/native/bun.lock b/apps/native/bun.lock
index 7a69fc01..5b76b333 100644
--- a/apps/native/bun.lock
+++ b/apps/native/bun.lock
@@ -8,6 +8,7 @@
"@streamdown/code": "^1.1.1",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
+ "electron-updater": "6.8.9",
"glimm": "^0.3.0",
"iconoir-react": "^7.11.1",
"liveline": "^0.0.7",
@@ -199,12 +200,16 @@
"@xterm/xterm": ["@xterm/[email protected]", "", {}, "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg=="],
+ "argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
+
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"baseline-browser-mapping": ["[email protected]", "", { "bin": "dist/cli.cjs" }, "sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ=="],
+ "builder-util-runtime": ["[email protected]", "", { "dependencies": { "debug": "^4.3.4", "sax": "^1.2.4" } }, "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw=="],
+
"caniuse-lite": ["[email protected]", "", {}, "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg=="],
"ccount": ["[email protected]", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
@@ -237,6 +242,8 @@
"electron": ["[email protected]", "", { "dependencies": { "@electron-internal/extract-zip": "^1.0.1", "@electron/get": "^5.0.0", "@types/node": "^24.9.0" }, "bin": { "electron": "cli.js", "install-electron": "install.js" } }, "sha512-oK1icjhapp3xsUZycO9WZaLmd3hJnA7ieobC4mpdtO1pEN+PPGWpA3m1Mgzzuc1wzSD2Wai4zcH4yfpGJqxFMA=="],
+ "electron-updater": ["[email protected]", "", { "dependencies": { "builder-util-runtime": "9.7.0", "fs-extra": "^10.1.0", "js-yaml": "^4.1.0", "lazy-val": "^1.0.5", "lodash.escaperegexp": "^4.1.2", "lodash.isequal": "^4.5.0", "semver": "~7.7.3", "tiny-typed-emitter": "^2.1.0" } }, "sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig=="],
+
"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],
"entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
@@ -249,6 +256,8 @@
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
+ "fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
+
"glimm": ["[email protected]", "", { "peerDependencies": { "next": ">=14", "react": ">=18" }, "optionalPeers": ["next", "react"] }, "sha512-Maw5WJnUsgyfsHl7Vp95wa8G1uaFhUOSoQzAVPX1DxdHxmWNBa9VtDRNPplH1A+bIazn956ZP/wQvH4ZSxKN9Q=="],
"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
@@ -293,6 +302,12 @@
"jiti": ["[email protected]", "", { "bin": "lib/jiti-cli.mjs" }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
+ "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="],
+
+ "jsonfile": ["[email protected]", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="],
+
+ "lazy-val": ["[email protected]", "", {}, "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q=="],
+
"lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
"lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
@@ -319,6 +334,10 @@
"liveline": ["[email protected]", "", { "peerDependencies": { "react": ">=18" } }, "sha512-S1Weo1kmefiOCNaW/WFXErqJXlV8A/ldIkIthaOeT57I2ZhqhKLKQDJ1wfabtMSK9vJeU8PeMNHd8Sr8TLByWQ=="],
+ "lodash.escaperegexp": ["[email protected]", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="],
+
+ "lodash.isequal": ["[email protected]", "", {}, "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ=="],
+
"longest-streak": ["[email protected]", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
@@ -465,6 +484,8 @@
"remend": ["[email protected]", "", {}, "sha512-N3DiY5qbRPoa5vkxn1oDLMyXOVTeo6Hp+XOj6SIqJAYUgLS0Q587gILPMom/qm86AQ/ZrcOdwEIzCz8V3J0nxQ=="],
+ "sax": ["[email protected]", "", {}, "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q=="],
+
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["[email protected]", "", { "bin": "bin/semver.js" }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
@@ -497,6 +518,8 @@
"tapable": ["[email protected]", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
+ "tiny-typed-emitter": ["[email protected]", "", {}, "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA=="],
+
"trim-lines": ["[email protected]", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],
"trough": ["[email protected]", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="],
@@ -521,6 +544,8 @@
"unist-util-visit-parents": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
+ "universalify": ["[email protected]", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
+
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
"vfile-location": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg=="],
@@ -539,6 +564,8 @@
"electron/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q=="],
+ "electron-updater/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
+
"next/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="],
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index c6420e2f..f82cf1a6 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -9,6 +9,7 @@ import type { ModelChoice } from "@/lib/acp-client";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import ComposerMenu from "./ComposerMenu";
import { useComposerSweep } from "./useComposerSweep";
+import { useComposerSize } from "./useComposerSize";
import type { AcpCommand } from "@/lib/acp";
import {
filesFrom,
@@ -218,28 +219,7 @@ export default function PromptBar({
return () => clearTimeout(t);
}, [demo, listening]);
- useLayoutEffect(() => {
- const input = inputRef.current;
- const controls = controlsRef.current;
- const measure = measureRef.current;
- const modelButton = modelRef.current;
- if (!input || !controls || !measure || !modelButton) return;
-
- const fixedControlsWidth = 28 * 3 + modelButton.offsetWidth;
- const inlineGaps = 4 * 4;
- const inlineInputWidth = controls.clientWidth - fixedControlsWidth - inlineGaps;
- const needsFullWidth = draft.includes("\n") || measure.offsetWidth + 8 > inlineInputWidth;
- if (needsFullWidth !== expanded) {
- setExpanded(needsFullWidth);
- }
-
- const minHeight = 28;
- const maxHeight = 100;
- input.style.height = "0px";
- const contentHeight = input.scrollHeight;
- input.style.height = `${Math.min(Math.max(contentHeight, minHeight), maxHeight)}px`;
- input.style.overflowY = contentHeight > maxHeight ? "auto" : "hidden";
- }, [draft, expanded]);
+ useComposerSize({ inputRef, controlsRef, measureRef, modelRef, draft, expanded, setExpanded });
/* A recalled prompt lands with the caret at its end, ready to edit or send. */
useLayoutEffect(() => {
diff --git a/apps/native/components/primitives/useComposerSize.ts b/apps/native/components/primitives/useComposerSize.ts
new file mode 100644
index 00000000..002c57a3
--- /dev/null
+++ b/apps/native/components/primitives/useComposerSize.ts
@@ -0,0 +1,43 @@
+import { useLayoutEffect, type RefObject } from "react";
+
+export function useComposerSize({ inputRef, controlsRef, measureRef, modelRef, draft, expanded, setExpanded }: {
+ inputRef: RefObject<HTMLTextAreaElement | null>;
+ controlsRef: RefObject<HTMLDivElement | null>;
+ measureRef: RefObject<HTMLSpanElement | null>;
+ modelRef: RefObject<HTMLButtonElement | null>;
+ draft: string; expanded: boolean; setExpanded(value: boolean): void;
+}) {
+ useLayoutEffect(() => {
+ const input = inputRef.current, controls = controlsRef.current;
+ const measure = measureRef.current, model = modelRef.current;
+ if (!input || !controls || !measure || !model) return;
+ const resize = () => {
+ const label = model.querySelector("span.truncate");
+ const modelWidth = model.offsetWidth + (label ? label.scrollWidth - label.clientWidth : 0);
+ const effortWidth = model.nextElementSibling instanceof HTMLElement ? model.nextElementSibling.offsetWidth : 0;
+ const inlineWidth = controls.clientWidth - 28 * 3 - modelWidth - effortWidth - 4 * 4;
+ const fullWidth = draft.includes("\n") || measure.offsetWidth + 8 > inlineWidth;
+ if (fullWidth !== expanded) setExpanded(fullWidth);
+ input.style.height = "0px";
+ const height = input.scrollHeight;
+ input.style.height = `${Math.min(Math.max(height, 28), 100)}px`;
+ input.style.overflowY = height > 100 ? "auto" : "hidden";
+ };
+ resize();
+ let frame = 0;
+ const widths = new WeakMap<Element, number>();
+ const observer = new ResizeObserver(entries => {
+ let changed = false;
+ for (const entry of entries) {
+ if (widths.get(entry.target) !== entry.contentRect.width) changed = true;
+ widths.set(entry.target, entry.contentRect.width);
+ }
+ if (!changed) return;
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(resize);
+ });
+ observer.observe(controls);
+ observer.observe(input);
+ return () => { observer.disconnect(); cancelAnimationFrame(frame); };
+ }, [inputRef, controlsRef, measureRef, modelRef, draft, expanded, setExpanded]);
+}
diff --git a/apps/native/components/site/DesktopUpdates.tsx b/apps/native/components/site/DesktopUpdates.tsx
new file mode 100644
index 00000000..9d9acd9b
--- /dev/null
+++ b/apps/native/components/site/DesktopUpdates.tsx
@@ -0,0 +1,42 @@
+"use client";
+import { useEffect, useRef, useState } from "react";
+import { desktop, type UpdateState } from "@/lib/desktop";
+
+export default function DesktopUpdates() {
+ const [state, setState] = useState<UpdateState | null>(null);
+ const [dismissed, setDismissed] = useState(false);
+ const previous = useRef<UpdateState['status'] | null>(null);
+ useEffect(() => {
+ const bridge = desktop();
+ if (!bridge?.updates || !bridge.updateSubscribe) return;
+ let alive = true;
+ const receive = (next: UpdateState) => {
+ if (!alive) return;
+ if (next.status !== 'downloading' || previous.current !== 'downloading') setDismissed(false);
+ previous.current = next.status;
+ setState(next);
+ };
+ const unsubscribe = bridge.updateSubscribe(receive);
+ void bridge.updates('state').then(receive).catch(() => {});
+ return () => { alive = false; unsubscribe(); };
+ }, []);
+ if (!state || dismissed || state.status === 'idle' || (!state.interactive && ['current', 'checking', 'error', 'unavailable'].includes(state.status))) return null;
+ const message = {
+ checking: 'Checking for updates…', current: `Codegraff ${state.currentVersion} is up to date.`,
+ downloading: `Downloading Codegraff ${state.version} · ${state.percent ?? 0}%`,
+ ready: `Codegraff ${state.version} is ready.`, installing: 'Preparing to restart…',
+ error: state.message, unavailable: state.message,
+ }[state.status];
+ const act = async (action: 'check' | 'restart') => {
+ try { const next = await desktop()?.updates?.(action); if (next) setState(next); }
+ catch { setState({ ...state, status: 'error', interactive: true, message: 'Could not update. Please try again.' }); }
+ };
+ return <div data-desktop-update className="fixed bottom-4 left-4 z-[110] w-80 max-w-[calc(100vw-32px)] rounded-xl border border-line bg-page p-3 text-sm text-ink shadow-card">
+ <div className="flex items-center gap-3"><p role="status" className="min-w-0 flex-1">{message}</p>
+ <button aria-label="Dismiss update notification" className="size-7 shrink-0 rounded hover:bg-hover" onClick={() => setDismissed(true)}>×</button></div>
+ {state.status === 'downloading' && <progress aria-label="Update download" max={100} value={state.percent ?? 0} className="mt-2 h-1 w-full accent-current" />}
+ {state.status === 'ready' && <><p className="mt-1 text-xs text-ink-3">Restart when your work is finished. Active tasks and terminals will stop.</p>
+ <button className="mt-2 rounded-lg bg-ink px-3 py-1.5 text-page" onClick={() => void act('restart')}>Restart to update</button></>}
+ {state.status === 'error' && <button className="mt-2 rounded-lg bg-hover px-3 py-1.5" onClick={() => void act('check')}>Try again</button>}
+ </div>;
+}
diff --git a/apps/native/electron/README.md b/apps/native/electron/README.md
index d8da1418..4367b32d 100644
--- a/apps/native/electron/README.md
+++ b/apps/native/electron/README.md
@@ -5,7 +5,7 @@ action. It builds the production UI with Bun, packages Chromium, Bun, graff,
and the SwiftUI Activity sheet, then opens `zig-out/electron/Codegraff.app`.
Builds currently target Apple Silicon macOS 14+; Liquid Glass uses macOS 26+.
Source builds are signed locally for development. The
-[packaged v0.0.289 download](https://github.com/justrach/codegraff/releases/download/v0.0.289/Codegraff-macos-arm64.zip)
+[packaged desktop download](https://github.com/justrach/codegraff/releases/latest/download/Codegraff-macos-arm64.dmg)
is Developer ID signed and notarized. Open the disk image and drag Codegraff.app onto Applications;
the runtime, engine, browser and native components are included.
@@ -143,5 +143,33 @@ The command signs nested executables, notarizes and staples the app, creates the
Finder drag-to-Applications layout, then signs, notarizes and staples the DMG.
It verifies both artifacts with Gatekeeper and writes a separate DMG checksum.
The output directory must be new. Notarization logs stay there for local review;
-only the DMG and checksum are release assets. Never publish a development bundle
-as the signed download.
+only the DMG, checksum, versioned update ZIP and `latest-mac.yml` are release assets.
+Never publish a development bundle as the signed download.
+
+## Automatic updates
+
+Signed distribution builds check the public GitHub release feed shortly after
+launch and every six hours. Downloads happen in the background. The notification
+shows progress and offers **Restart to update**; downloading never stops a task,
+and closing the app does not silently install an update. The Codegraff menu has
+**Check for Updates…** and an **Automatically Download Updates** preference.
+Development builds, smoke tests and apps running from a mounted disk image do not
+check online. Install the app in Applications first.
+
+The updater verifies the archive checksum; macOS Squirrel verifies the application
+signature before replacement. The updater receives no conversation or workspace
+contents. HTTP requests still disclose ordinary connection information to the
+release host. Only stable, newer releases are eligible.
+
+`distribute.sh` adds the feed configuration before signing and creates the update
+ZIP after the app has been stapled. To attach all desktop assets together:
+
+```sh
+bash apps/native/electron/publish-updates.sh vVERSION zig-out/distribution
+```
+
+The release must remain a draft until its CI checks pass and all desktop assets
+are attached. Every latest stable release must carry `latest-mac.yml` and its
+versioned ZIP alongside the DMG; a CLI-only latest release cannot serve a desktop
+update. Publish the complete release atomically. Versions older than the first
+updater-enabled release need one manual DMG installation.
diff --git a/apps/native/electron/build.sh b/apps/native/electron/build.sh
index 6451291f..731e318b 100644
--- a/apps/native/electron/build.sh
+++ b/apps/native/electron/build.sh
@@ -2,7 +2,7 @@
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
root="$(cd "$here/../../.." && pwd)"
-version="${GRAFF_VERSION:-0.0.290}"
+version="${GRAFF_VERSION:-0.0.291}"
ui="$root/apps/native"
out="$root/zig-out/electron"
bundle="$out/Codegraff.app"
@@ -25,6 +25,7 @@ ditto "$ui/node_modules/electron/dist/Electron.app" "$bundle"
resources="$bundle/Contents/Resources"
mkdir -p "$resources/app" "$resources/native"
cp "$here/"*.cjs "$resources/app/"
+bun build "$here/updater-runtime.cjs" --target=node --format=cjs --external electron --outfile "$resources/app/updater-runtime.cjs"
printf '{"name":"codegraff","productName":"Codegraff","version":"%s","main":"main.cjs"}\n' "$version" > "$resources/app/package.json"
ditto "$ui/.next/standalone" "$resources/ui"
ditto "$ui/.next/static" "$resources/ui/.next/static"
diff --git a/apps/native/electron/distribute.sh b/apps/native/electron/distribute.sh
index 688e1a59..9959cdf6 100755
--- a/apps/native/electron/distribute.sh
+++ b/apps/native/electron/distribute.sh
@@ -17,6 +17,10 @@ mounted=0
cleanup() { if [[ "$mounted" == 1 ]]; then hdiutil detach "$work/mount" -quiet || true; fi; rm -rf "$work"; }
trap cleanup EXIT
ditto "$source_app" "$app"
+version="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist")"
+[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Distribution requires a stable version.' >&2; exit 1; }
+# Only distribution builds opt into online updates; include the feed in the signature.
+bun "$here/update-artifacts.cjs" config "$app/Contents/Resources/app-update.yml"
bun "$here/sign-bundle.mjs" "$app"
codesign --verify --deep --strict "$app"
ditto -c -k --keepParent "$app" "$work/app.zip"
@@ -25,6 +29,10 @@ bun -e 'if(JSON.parse(require("fs").readFileSync(process.argv[1])).status!=="Acc
xcrun stapler staple "$app"
xcrun stapler validate "$app"
spctl --assess --type execute --verbose=2 "$app"
+# Squirrel.Mac needs a ZIP of the signed, stapled app, not a disk image.
+archive="$out/Codegraff-$version-macos-arm64.zip"
+ditto -c -k --keepParent "$app" "$archive"
+bun "$here/update-artifacts.cjs" "$version" "$archive" "$out/latest-mac.yml"
mkdir "$work/staging"
ditto "$app" "$work/staging/Codegraff.app"
ln -s /Applications "$work/staging/Applications"
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index 74858d4a..32448836 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -25,6 +25,10 @@ if (process.env.GRAFF_ELECTRON_SMOKE) process.env.GRAFF_THEMES_DIR = path.join(a
let win, browser, backend, automation, computer, profiler;
let terminals;
let quitting = false;
+if (!require('./single-instance.cjs').claimDesktopInstance(app, () => win)) {
+ app.quit();
+ return;
+}
async function metrics() {
const { rssMiB, cpuPercent, processes } = await treeSample(process.pid);
@@ -128,8 +132,9 @@ app.whenReady().then(async () => {
installExternalLinks(win.webContents, backend.origin);
win.on('minimize', () => { if (browser.visible) browser.hide(browser.visible); });
win.on('restore', () => win.webContents.send('browser-event', { type: 'layout' }));
+ const updateMenu = require('./updates.cjs').installUpdates({ app, win, ipcMain, trusted, resources });
Menu.setApplicationMenu(Menu.buildFromTemplate([
- { label: 'Codegraff', submenu: [{ role: 'about' }, { label: 'Activity…', accelerator: 'CmdOrCtrl+,', click: () => void activity().catch(error => dialog.showErrorBox('Activity', error.message)) }, { label: 'Computer use…', click: () => void computer.configure().catch(error => dialog.showErrorBox('Computer use', error.message)) }, { type: 'separator' }, { role: 'quit' }] },
+ { label: 'Codegraff', submenu: [{ role: 'about' }, ...updateMenu, { type: 'separator' }, { label: 'Activity…', accelerator: 'CmdOrCtrl+,', click: () => void activity().catch(error => dialog.showErrorBox('Activity', error.message)) }, { label: 'Computer use…', click: () => void computer.configure().catch(error => dialog.showErrorBox('Computer use', error.message)) }, { type: 'separator' }, { role: 'quit' }] },
{ label: 'File', submenu: [
['New chat', 'CmdOrCtrl+N', 'new'], ['New tab', 'CmdOrCtrl+T', 'new'],
['Close chat', 'CmdOrCtrl+W', 'close'], ['Reopen closed chat', 'CmdOrCtrl+Shift+T', 'reopen'],
diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjs
index 60c525d0..ad4135c5 100644
--- a/apps/native/electron/navigation-visual.cjs
+++ b/apps/native/electron/navigation-visual.cjs
@@ -26,6 +26,7 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {
const galleryFetch=window.fetch;window.fetch=async(input,options)=>{const response=await galleryFetch(input,options);if(options?.body&&JSON.parse(options.body).method==='bootstrap')return new Response(JSON.stringify({sessionId:'demo',commands}),{headers:{'content-type':'application/json'}});if(String(input).includes('/api/models')){const data=await response.json();data.result.commands=commands;data.result.current.model='example-model-with-a-long-name';data.result.models[0].name=data.result.current.model;return new Response(JSON.stringify(data),{headers:{'content-type':'application/json'}});}return response;};`});
await wc.loadURL(origin);win.focus();await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
await require('./composer-visual.cjs').runComposerVisual({win,output});
+ await require('./split-composer-visual.cjs').runSplitComposerVisual({win,output,key});
await input('/compact');await wait(`!!document.querySelector('[role="option"]')`);assert.match(await js(`document.querySelector('[role="option"]').textContent`),/compact/);
await key('Escape');await key('n',{metaKey:true});assert.equal(await tabs(),2);
await input('/compact');await wait(`!!document.querySelector('[role="option"]')`);assert.match(await js(`document.querySelector('[role="option"]').textContent`),/compact/,'new chats inherit the command catalog');
diff --git a/apps/native/electron/preload.cjs b/apps/native/electron/preload.cjs
index 52f0f85c..88671eda 100644
--- a/apps/native/electron/preload.cjs
+++ b/apps/native/electron/preload.cjs
@@ -1,5 +1,11 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('graffDesktop', {
+ updates: action => ipcRenderer.invoke('updates', action),
+ updateSubscribe: callback => {
+ const listener = (_event, state) => callback(state);
+ ipcRenderer.on('update-state', listener);
+ return () => ipcRenderer.removeListener('update-state', listener);
+ },
browser: (chat, method, params) => ipcRenderer.invoke('browser', { chat, method, params }),
terminal: (action, params) => ipcRenderer.invoke('terminal', { action, params }),
terminalSubscribe: callback => {
diff --git a/apps/native/electron/publish-updates.sh b/apps/native/electron/publish-updates.sh
new file mode 100644
index 00000000..6631e828
--- /dev/null
+++ b/apps/native/electron/publish-updates.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+# Attach the complete desktop update set to a draft release. Publish only after CI.
+set -euo pipefail
+tag="${1:?Usage: publish-updates.sh vVERSION distribution-directory}"
+out="${2:?Provide the notarized distribution directory}"
+repo=justrach/codegraff
+[[ "$(gh release view "$tag" --repo "$repo" --json isDraft --jq .isDraft)" == true ]] || {
+ echo 'Desktop assets must be uploaded together to a draft release.' >&2; exit 1;
+}
+bun -e '
+const fs=require("node:fs"),path=require("node:path"),crypto=require("node:crypto");
+const [tag,out]=process.argv.slice(1),m=JSON.parse(fs.readFileSync(path.join(out,"latest-mac.yml")));
+if("v"+m.version!==tag||m.files.length!==1)throw Error("Release version mismatch");
+const f=m.files[0];if(f.url!==`Codegraff-${m.version}-macos-arm64.zip`)throw Error("Invalid archive name");
+const bytes=fs.readFileSync(path.join(out,f.url));
+if(bytes.length!==f.size||crypto.createHash("sha512").update(bytes).digest("base64")!==f.sha512)throw Error("Update checksum mismatch");
+' "$tag" "$out"
+assets=("$out/Codegraff-macos-arm64.dmg" "$out/Codegraff-DMG-SHA256SUMS" "$out/Codegraff-${tag#v}-macos-arm64.zip" "$out/latest-mac.yml")
+gh release upload "$tag" --repo "$repo" "${assets[@]}"
+echo 'Desktop assets uploaded. Keep the release in draft until all release checks pass.'
diff --git a/apps/native/electron/single-instance.cjs b/apps/native/electron/single-instance.cjs
new file mode 100644
index 00000000..f8e035bf
--- /dev/null
+++ b/apps/native/electron/single-instance.cjs
@@ -0,0 +1,17 @@
+// All installed/release copies using the same profile belong to one desktop.
+// Acquire this before starting Bun or Chromium sessions: a second server gets
+// a different origin and therefore a different set of saved UI preferences.
+function claimDesktopInstance(app, window) {
+ if (!app.requestSingleInstanceLock()) return false;
+ const focus = () => {
+ const win = window();
+ if (!win || win.isDestroyed()) return;
+ if (win.isMinimized()) win.restore();
+ win.show();
+ win.focus();
+ };
+ app.on('second-instance', focus);
+ app.on('activate', focus);
+ return true;
+}
+module.exports = { claimDesktopInstance };
diff --git a/apps/native/electron/single-instance.test.cjs b/apps/native/electron/single-instance.test.cjs
new file mode 100644
index 00000000..77f5e25c
--- /dev/null
+++ b/apps/native/electron/single-instance.test.cjs
@@ -0,0 +1,24 @@
+const { test, expect } = require('bun:test');
+const { EventEmitter } = require('node:events');
+const { claimDesktopInstance } = require('./single-instance.cjs');
+
+test('a second copy cannot start a separate desktop against the same profile', () => {
+ const app = new EventEmitter();
+ app.requestSingleInstanceLock = () => false;
+ expect(claimDesktopInstance(app, () => { throw Error('must not create a window'); })).toBe(false);
+ expect(app.listenerCount('second-instance')).toBe(0);
+});
+
+test('reopening the desktop restores the existing window, without starting another backend', () => {
+ const app = new EventEmitter(), actions = [];
+ app.requestSingleInstanceLock = () => true;
+ let win;
+ expect(claimDesktopInstance(app, () => win)).toBe(true);
+ app.emit('second-instance'); // Starting up: the first window is not ready yet.
+ win = { isDestroyed: () => false, isMinimized: () => true,
+ restore: () => actions.push('restore'), show: () => actions.push('show'), focus: () => actions.push('focus') };
+ app.emit('second-instance');
+ expect(actions).toEqual(['restore', 'show', 'focus']);
+ app.emit('activate');
+ expect(actions.length).toBe(6);
+});
diff --git a/apps/native/electron/split-composer-visual.cjs b/apps/native/electron/split-composer-visual.cjs
new file mode 100644
index 00000000..adfd2092
--- /dev/null
+++ b/apps/native/electron/split-composer-visual.cjs
@@ -0,0 +1,53 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+async function runSplitComposerVisual({ win, output, key }) {
+ const js = source => win.webContents.executeJavaScript(source);
+ await key('d', { metaKey: true });
+ await key('d', { metaKey: true });
+ await new Promise(resolve => setTimeout(resolve, 1600));
+ try {
+ assert.equal(await js(`document.querySelectorAll('[data-chat]').length`), 3);
+ win.setSize(1440, 900);
+ await new Promise(resolve => setTimeout(resolve, 150));
+ await js(`document.querySelectorAll('textarea[aria-label="Prompt"]').forEach(e=>{
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,'Please review the changes in this workspace and explain how the new application controls work when I resize the window.');
+ e.dispatchEvent(new Event('input',{bubbles:true}));
+ })`);
+ await new Promise(resolve => setTimeout(resolve, 150));
+ for (const width of [1440, 1100, 900]) {
+ win.setSize(width, 900);
+ await new Promise(resolve => setTimeout(resolve, 150));
+ const geometry = await js(`Array.from(document.querySelectorAll('[data-chat]')).map(pane => {
+ const p=pane.querySelector('[data-promptbar]'), area=p.getBoundingClientRect();
+ const buttons=Array.from(p.querySelectorAll('button[aria-label]')).filter(b=>b.offsetWidth);
+ const rects=buttons.map(b=>{const r=b.getBoundingClientRect();return {label:b.ariaLabel,x:r.x,y:r.y,right:r.right,bottom:r.bottom,width:r.width}});
+ const overlaps=[];
+ for(let i=0;i<rects.length;i++)for(let j=i+1;j<rects.length;j++){
+ const a=rects[i],b=rects[j];if(a.x<b.right&&a.right>b.x&&a.y<b.bottom&&a.bottom>b.y)overlaps.push([a.label,b.label]);
+ }
+ const input=p.querySelector('textarea');
+ return {width:area.width, overlaps, outside:rects.filter(r=>r.x<area.x-1||r.right>area.right+1),
+ clipped:input.scrollHeight>input.clientHeight+1&&getComputedStyle(input).overflowY==='hidden',
+ modelWidth:p.querySelector('[aria-label="Choose model"]').getBoundingClientRect().width};
+ })`);
+ fs.writeFileSync(path.join(output, `three-splits-${width}.png`), (await win.webContents.capturePage()).toPNG());
+ for (const pane of geometry) {
+ assert.deepEqual(pane.overlaps, [], `${width}px split: ${JSON.stringify(pane)}`);
+ assert.deepEqual(pane.outside, [], `${width}px split: ${JSON.stringify(pane)}`);
+ assert.ok(pane.modelWidth >= 44, `${width}px split model is usable: ${JSON.stringify(pane)}`);
+ assert.equal(pane.clipped, false, `${width}px resize hides part of the draft: ${JSON.stringify(pane)}`);
+ }
+ }
+ } finally {
+ await js(`Array.from(document.querySelectorAll('[aria-label="Close this split"]')).forEach(b=>b.click())`);
+ await key('w', { metaKey: true });
+ await key('w', { metaKey: true });
+ await js(`document.querySelectorAll('textarea[aria-label="Prompt"]').forEach(e=>{
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,'');e.dispatchEvent(new Event('input',{bubbles:true}));
+ })`);
+ win.setSize(1100, 760);
+ }
+}
+module.exports = { runSplitComposerVisual };
diff --git a/apps/native/electron/update-artifacts.cjs b/apps/native/electron/update-artifacts.cjs
new file mode 100644
index 00000000..6489c7b4
--- /dev/null
+++ b/apps/native/electron/update-artifacts.cjs
@@ -0,0 +1,20 @@
+const fs = require('node:fs');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const feed = { provider: 'generic', url: 'https://github.com/justrach/codegraff/releases/latest/download/', updaterCacheDirName: 'codegraff-updater' };
+function writeManifest(version, archive, output) {
+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw Error('Only stable versions can enter the desktop update feed.');
+ const url = path.basename(archive);
+ if (url !== `Codegraff-${version}-macos-arm64.zip`) throw Error('Update archive name must match its version and architecture.');
+ const bytes = fs.readFileSync(archive);
+ const sha512 = crypto.createHash('sha512').update(bytes).digest('base64');
+ const manifest = { version, files: [{ url, sha512, size: bytes.length }], path: url, sha512, releaseDate: new Date().toISOString() };
+ // JSON is valid YAML, and avoids escaping release-controlled filenames by hand.
+ fs.writeFileSync(output, JSON.stringify(manifest, null, 2) + '\n');
+ return manifest;
+}
+if (require.main === module) {
+ if (process.argv[2] === 'config') fs.writeFileSync(process.argv[3], JSON.stringify(feed, null, 2) + '\n');
+ else writeManifest(...process.argv.slice(2));
+}
+module.exports = { writeManifest, feed };
diff --git a/apps/native/electron/update-artifacts.test.cjs b/apps/native/electron/update-artifacts.test.cjs
new file mode 100644
index 00000000..32e648af
--- /dev/null
+++ b/apps/native/electron/update-artifacts.test.cjs
@@ -0,0 +1,20 @@
+const { test, expect } = require('bun:test');
+const fs = require('node:fs'), os = require('node:os'), path = require('node:path');
+const { load } = require('js-yaml');
+const { writeManifest, feed } = require('./update-artifacts.cjs');
+test('release metadata can be read by the updater and identifies the exact archive', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-update-metadata-'));
+ try {
+ const file = path.join(dir, 'Codegraff-1.2.3-macos-arm64.zip'), manifest = path.join(dir, 'latest-mac.yml');
+ fs.writeFileSync(file, 'archive fixture');
+ writeManifest('1.2.3', file, manifest);
+ const data = load(fs.readFileSync(manifest, 'utf8'));
+ expect(data.version).toBe('1.2.3');
+ expect(data.files[0].url).toBe(path.basename(file));
+ expect(data.files[0].size).toBe(fs.statSync(file).size);
+ expect(Buffer.from(data.files[0].sha512, 'base64').length).toBe(64);
+ expect(load(JSON.stringify(feed)).url).toBe('https://github.com/justrach/codegraff/releases/latest/download/');
+ expect(() => writeManifest('1.2.4', file, manifest)).toThrow('archive name');
+ expect(() => writeManifest('1.2.3-beta.1', file, manifest)).toThrow('stable');
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+});
diff --git a/apps/native/electron/updater-runtime.cjs b/apps/native/electron/updater-runtime.cjs
new file mode 100644
index 00000000..bfae7b54
--- /dev/null
+++ b/apps/native/electron/updater-runtime.cjs
@@ -0,0 +1,2 @@
+// Bundled with Bun for the packaged main process; Electron remains external.
+module.exports = require('electron-updater').autoUpdater;
diff --git a/apps/native/electron/updates-transport.cjs b/apps/native/electron/updates-transport.cjs
new file mode 100644
index 00000000..e7f5efe3
--- /dev/null
+++ b/apps/native/electron/updates-transport.cjs
@@ -0,0 +1,44 @@
+// Real updater HTTP/checksum path against a disposable loopback feed. This
+// deliberately tests transport only: it never asks Squirrel to install an app.
+const fs = require('node:fs'), os = require('node:os'), path = require('node:path');
+const http = require('node:http'), assert = require('node:assert/strict');
+const { writeManifest } = require('./update-artifacts.cjs');
+async function runUpdateTransport() {
+ if (process.platform !== 'darwin') return;
+ const { autoUpdater: updater } = require('electron-updater');
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-update-transport-'));
+ const archive = path.join(root, 'Codegraff-99.0.0-macos-arm64.zip');
+ const bytes = Buffer.alloc(22); bytes.writeUInt32LE(0x06054b50); // Valid empty ZIP.
+ fs.writeFileSync(archive, bytes);
+ const manifest = writeManifest('99.0.0', archive, path.join(root, 'latest-mac.yml'));
+ let corrupt = true, ready = 0;
+ const server = http.createServer((req, res) => {
+ if (req.url.split('?')[0] === '/latest-mac.yml') res.end(JSON.stringify(manifest));
+ else { res.setHeader('content-length', bytes.length); res.end(corrupt ? Buffer.alloc(bytes.length, 1) : bytes); }
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ updater.logger = null;
+ updater.autoInstallOnAppQuit = false;
+ updater.disableDifferentialDownload = true;
+ updater.forceDevUpdateConfig = true;
+ const config = { provider: 'generic', url: `http://127.0.0.1:${server.address().port}/`, updaterCacheDirName: 'cache' };
+ fs.writeFileSync(path.join(root, 'config.yml'), JSON.stringify(config));
+ updater.updateConfigPath = path.join(root, 'config.yml');
+ Object.defineProperty(updater.app, 'baseCachePath', { value: root });
+ updater.on('update-downloaded', () => ready++);
+ const first = await updater.checkForUpdates();
+ await assert.rejects(first.downloadPromise, /sha512 checksum mismatch/i);
+ assert.equal(ready, 0, 'corrupt bytes must never be ready to install');
+ corrupt = false;
+ const second = await updater.checkForUpdates();
+ await second.downloadPromise;
+ assert.equal(ready, 1);
+ assert.equal(updater.squirrelDownloadedUpdate, false, 'transport must not start native installation');
+ console.log('Updater transport passed: corrupt archive rejected, retry verified, no native installation.');
+ } finally {
+ updater.closeServerIfExists(); server.close();
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+}
+module.exports = { runUpdateTransport };
diff --git a/apps/native/electron/updates-visual.cjs b/apps/native/electron/updates-visual.cjs
new file mode 100644
index 00000000..eb4011d7
--- /dev/null
+++ b/apps/native/electron/updates-visual.cjs
@@ -0,0 +1,38 @@
+const { BrowserWindow } = require('electron');
+const assert = require('node:assert/strict'), fs = require('node:fs'), path = require('node:path');
+async function runUpdateVisuals({ origin, output }) {
+ const win = new BrowserWindow({ width: 900, height: 650, show: true, webPreferences: { sandbox: true, contextIsolation: true, backgroundThrottling: false } });
+ const wc = win.webContents, js = source => wc.executeJavaScript(source);
+ const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await new Promise(r => setTimeout(r, 30)); } throw Error(source); };
+ try {
+ wc.debugger.attach('1.3');
+ await wc.debugger.sendCommand('Page.enable');
+ await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `
+ window.__restarts=0;let listener;window.__update=state=>listener?.({currentVersion:'1.0.0',automatic:true,interactive:false,...state});
+ window.graffDesktop={updateSubscribe:fn=>{listener=fn;return()=>{}},updates:async action=>{if(action==='restart'){window.__restarts++;return {status:'installing'}}return {status:'idle'}}};` });
+ await win.loadURL(`${origin}/visual-tests`);
+ win.focus();
+ console.log('Update visual fixture loaded.');
+ await wait(`!!document.querySelector('[data-case="waiting"]')`);
+ for (const status of ['checking', 'error', 'current']) {
+ await js(`window.__update({status:'${status}',message:'Check your connection.'})`);
+ await new Promise(r => setTimeout(r, 50));
+ assert.equal(await js(`!!document.querySelector('[data-desktop-update]')`), false, 'background checks never interrupt the conversation');
+ }
+ await js(`window.__update({status:'downloading',version:'1.0.1',percent:42})`);
+ await wait(`document.querySelector('progress')?.value===42`);
+ await js(`document.querySelector('[aria-label="Dismiss update notification"]').click()`);
+ await js(`window.__update({status:'downloading',version:'1.0.1',percent:43})`);
+ await new Promise(r => setTimeout(r, 50));
+ assert.equal(await js(`!!document.querySelector('[data-desktop-update]')`), false, 'progress does not reopen a dismissed notification');
+ await js(`window.__update({status:'ready',version:'1.0.1'})`);
+ await wait(`document.querySelector('[data-desktop-update]')?.textContent.includes('Restart to update')`);
+ assert.equal(await js('window.__restarts'), 0);
+ fs.writeFileSync(path.join(output, 'update-ready.png'), (await wc.capturePage(undefined, { stayAwake: true })).toPNG());
+ await js(`Array.from(document.querySelectorAll('[data-desktop-update] button')).find(b=>b.textContent==='Restart to update').click()`);
+ await wait(`window.__restarts===1`);
+ await wait(`document.querySelector('[data-desktop-update]')?.textContent.includes('Preparing to restart')`);
+ console.log('Update UI passed: quiet checks/errors, download progress, explicit restart only.');
+ } finally { win.destroy(); }
+}
+module.exports = { runUpdateVisuals };
diff --git a/apps/native/electron/updates.cjs b/apps/native/electron/updates.cjs
new file mode 100644
index 00000000..03868f0f
--- /dev/null
+++ b/apps/native/electron/updates.cjs
@@ -0,0 +1,82 @@
+const fs = require('node:fs');
+const path = require('node:path');
+
+function createUpdates({ updater, version, available = true, automatic = true, notify, save = () => {} }) {
+ let state = { status: available ? 'idle' : 'unavailable', currentVersion: version, automatic, interactive: false };
+ let checking = false;
+ const emit = patch => { state = { ...state, ...patch }; notify({ ...state }); };
+ if (available) {
+ updater.autoDownload = true;
+ updater.autoInstallOnAppQuit = false;
+ updater.allowPrerelease = false;
+ updater.allowDowngrade = false;
+ updater.disableDifferentialDownload = true;
+ updater.logger = null;
+ updater.on('checking-for-update', () => emit({ status: 'checking', message: undefined }));
+ updater.on('update-available', info => emit({ status: 'downloading', version: info.version, percent: 0 }));
+ updater.on('download-progress', progress => {
+ const percent = Math.max(0, Math.min(100, Math.floor(progress.percent || 0)));
+ if (percent !== state.percent) emit({ status: 'downloading', percent });
+ });
+ updater.on('update-not-available', () => emit({ status: 'current', version: undefined, percent: undefined }));
+ updater.on('update-downloaded', info => emit({ status: 'ready', version: info.version, percent: 100 }));
+ updater.on('error', () => emit({ status: 'error', message: 'Could not update. Check your connection and try again.' }));
+ }
+ return {
+ state: () => ({ ...state }),
+ async check(interactive = false) {
+ if (checking || ['downloading', 'ready', 'installing'].includes(state.status)) {
+ if (interactive) emit({ interactive: true });
+ return;
+ }
+ if (!available) { emit({ interactive, message: 'Install a signed release in Applications to receive updates.' }); return; }
+ checking = true;
+ emit({ status: 'checking', interactive, message: undefined });
+ try {
+ const result = await updater.checkForUpdates();
+ // The check resolves before the background download. Always consume its
+ // rejection as well as the updater's error event (offline/checksum errors).
+ void result?.downloadPromise?.catch(() => emit({ status: 'error', message: 'Could not download the update. Please try again.' }));
+ }
+ catch { emit({ status: 'error', message: 'Could not check for updates. Check your connection and try again.' }); }
+ finally { checking = false; }
+ },
+ setAutomatic(value) { save(value); emit({ automatic: value }); },
+ restart() {
+ if (state.status !== 'ready') throw Error('No downloaded update is ready.');
+ emit({ status: 'installing' });
+ try { updater.quitAndInstall(); }
+ catch { emit({ status: 'error', message: 'Could not install the update. Try again from Applications.' }); }
+ },
+ };
+}
+
+function installUpdates({ app, win, ipcMain, trusted, resources }) {
+ const prefs = path.join(app.getPath('userData'), 'updates.json');
+ let automatic = true;
+ try { automatic = JSON.parse(fs.readFileSync(prefs, 'utf8')).automatic !== false; } catch {}
+ const available = app.isPackaged && process.platform === 'darwin' && !process.env.GRAFF_ELECTRON_SMOKE &&
+ !process.execPath.startsWith('/Volumes/') && fs.existsSync(path.join(resources, 'app-update.yml'));
+ const controller = createUpdates({ version: app.getVersion(), automatic, available,
+ updater: available ? require('./updater-runtime.cjs') : null,
+ save: value => { fs.mkdirSync(path.dirname(prefs), { recursive: true }); fs.writeFileSync(prefs, JSON.stringify({ automatic: value })); },
+ notify: state => { if (!win.isDestroyed()) { win.webContents.send('update-state', state); win.setProgressBar(state.status === 'downloading' ? (state.percent ?? 0) / 100 : -1); } },
+ });
+ ipcMain.handle('updates', async (event, action) => {
+ trusted(event);
+ if (action === 'check') await controller.check(true);
+ else if (action === 'restart') controller.restart();
+ else if (action !== 'state') throw Error('Unknown update action');
+ return controller.state();
+ });
+ const check = () => { if (controller.state().automatic) void controller.check(); };
+ const first = setTimeout(check, 30000), repeat = setInterval(check, 6 * 60 * 60 * 1000);
+ first.unref(); repeat.unref();
+ app.once('before-quit', () => { clearTimeout(first); clearInterval(repeat); });
+ return [
+ { label: 'Check for Updates…', click: () => void controller.check(true) },
+ { label: 'Automatically Download Updates', type: 'checkbox', checked: automatic,
+ click: item => controller.setAutomatic(item.checked) },
+ ];
+}
+module.exports = { createUpdates, installUpdates };
diff --git a/apps/native/electron/updates.test.cjs b/apps/native/electron/updates.test.cjs
new file mode 100644
index 00000000..62cf00da
--- /dev/null
+++ b/apps/native/electron/updates.test.cjs
@@ -0,0 +1,65 @@
+const { test, expect } = require('bun:test');
+const { EventEmitter } = require('node:events');
+const { createUpdates } = require('./updates.cjs');
+function fixture(options = {}) {
+ const updater = new EventEmitter(), events = [], saved = [];
+ let checks = 0, installs = 0;
+ updater.checkForUpdates = async () => { checks++; updater.emit('checking-for-update'); return null; };
+ updater.quitAndInstall = () => { installs++; };
+ const updates = createUpdates({ updater, version: '1.0.0', notify: state => events.push(state), save: value => saved.push(value), ...options });
+ return { updater, updates, events, saved, checks: () => checks, installs: () => installs };
+}
+test('downloads in the background but never interrupts a running task automatically', async () => {
+ const f = fixture();
+ await f.updates.check();
+ f.updater.emit('update-available', { version: '1.0.1' });
+ f.updater.emit('download-progress', { percent: 34.9 });
+ expect(f.updates.state().percent).toBe(34);
+ f.updater.emit('update-downloaded', { version: '1.0.1' });
+ await f.updates.check();
+ expect(f.checks()).toBe(1);
+ expect(f.installs()).toBe(0);
+ expect(f.updater.autoInstallOnAppQuit).toBe(false);
+ expect(f.updater.allowDowngrade).toBe(false);
+ expect(f.updater.allowPrerelease).toBe(false);
+ f.updates.restart();
+ expect(f.installs()).toBe(1);
+ expect(f.updates.state().status).toBe('installing');
+});
+test('development and disk-image builds do not make update requests', async () => {
+ const f = fixture({ available: false });
+ await f.updates.check(true);
+ expect(f.checks()).toBe(0);
+ expect(f.updates.state().status).toBe('unavailable');
+ expect(() => f.updates.restart()).toThrow('No downloaded update');
+});
+test('offline checks recover and do not expose raw request details in the UI', async () => {
+ const f = fixture();
+ f.updater.checkForUpdates = async () => { throw Error('private request context'); };
+ await f.updates.check(true);
+ expect(f.updates.state().status).toBe('error');
+ expect(f.updates.state().message).not.toContain('private');
+ f.updater.checkForUpdates = async () => { f.updater.emit('update-not-available'); };
+ await f.updates.check(true);
+ expect(f.updates.state().status).toBe('current');
+});
+test('a failed background download is handled and never becomes installable', async () => {
+ const f = fixture();
+ f.updater.checkForUpdates = async () => ({ downloadPromise: Promise.reject(Error('checksum mismatch')) });
+ await f.updates.check(true);
+ await Promise.resolve();
+ expect(f.updates.state().status).toBe('error');
+ expect(() => f.updates.restart()).toThrow();
+ expect(f.installs()).toBe(0);
+});
+test('concurrent checks are coalesced and automatic-download preference persists', async () => {
+ const f = fixture(); let finish, calls = 0;
+ f.updater.checkForUpdates = () => { calls++; return new Promise(resolve => { finish = resolve; }); };
+ const first = f.updates.check();
+ await f.updates.check(true);
+ expect(calls).toBe(1);
+ finish(); await first;
+ f.updates.setAutomatic(false);
+ expect(f.saved).toEqual([false]);
+ expect(f.updates.state().automatic).toBe(false);
+});
diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjs
index 43050d01..d1df5aff 100644
--- a/apps/native/electron/visual-tests.cjs
+++ b/apps/native/electron/visual-tests.cjs
@@ -1,4 +1,4 @@
-const { app, BrowserWindow } = require('electron');
+const { app, BrowserWindow, ipcMain } = require('electron');
const { spawn } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
@@ -11,6 +11,7 @@ app.setPath('userData', path.join(temporary, 'profile'));
let server, win;
const deadline = setTimeout(() => { console.error('Visual run exceeded 240 seconds'); finish(1); }, 240000);
app.whenReady().then(async () => {
+ ipcMain.handle('updates', () => ({ status: 'unavailable', currentVersion: '1.0.0', automatic: false, interactive: false }));
const root = path.resolve(__dirname, '..'), output = process.env.GRAFF_VISUAL_OUTPUT || path.resolve(root, '../../zig-out/visual-tests');
fs.mkdirSync(output, { recursive: true });
assert.ok(fs.existsSync(path.join(root, '.next/BUILD_ID')), 'Run bun run build before visual tests.');
@@ -29,6 +30,13 @@ app.whenReady().then(async () => {
if (url.origin === origin && url.pathname.startsWith('/api/')) apiRequests.push(url.pathname);
callback({ cancel: !details.url.startsWith(origin) && !details.url.startsWith('data:') || url.pathname.startsWith('/api/') });
});
+ if (process.env.GRAFF_VISUAL_SUITE === 'updates') {
+ await require('./updates-visual.cjs').runUpdateVisuals({ origin, output });
+ await require('./updates-transport.cjs').runUpdateTransport();
+ assert.deepEqual(apiRequests, [], 'Update fixtures never call engine or model APIs');
+ fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: ['update UI', 'update transport'], apiRequests }, null, 2));
+ return;
+ }
await win.loadURL(`${origin}/visual-tests`);
const js = source => win.webContents.executeJavaScript(source);
const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(50); } throw Error(`Visual check timed out: ${source}`); };
@@ -59,6 +67,8 @@ app.whenReady().then(async () => {
await require('./navigation-visual.cjs').runNavigationVisuals({ win, origin, output });
await require('./browser-visual.cjs').runBrowserVisuals({ win, origin, output });
await require('./agents-visual.cjs').runAgentVisuals({ win, origin, output });
+ await require('./updates-visual.cjs').runUpdateVisuals({ origin, output });
+ await require('./updates-transport.cjs').runUpdateTransport();
if (process.env.GRAFF_PERFORMANCE_TESTS) await require('./performance-scenarios.cjs').runPerformance({ win, origin, output });
assert.deepEqual(apiRequests, [], 'Visual fixtures must not call the engine or model APIs');
fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: results, apiRequests }, null, 2));
diff --git a/apps/native/lib/desktop.ts b/apps/native/lib/desktop.ts
index d5e6189a..df9fdc74 100644
--- a/apps/native/lib/desktop.ts
+++ b/apps/native/lib/desktop.ts
@@ -3,7 +3,10 @@ import type { PageInfo } from "./browser-client";
export type DesktopEvent = { type: string; chat?: string; info?: PageInfo; pin?: BrowserPin };
export type TerminalEvent = { id: string; seq: number; data?: string; exit?: number };
+export type UpdateState = { status: 'idle' | 'unavailable' | 'checking' | 'current' | 'downloading' | 'ready' | 'installing' | 'error'; currentVersion: string; version?: string; percent?: number; automatic: boolean; interactive: boolean; message?: string };
export type DesktopBridge = {
+ updates?(action: 'state' | 'check' | 'restart'): Promise<UpdateState>;
+ updateSubscribe?(callback: (state: UpdateState) => void): () => void;
terminal?(action: string, params?: Record<string, unknown>): Promise<{id: string; seq: number; history: string; exit: number | null}>;
terminalSubscribe?(callback: (event: TerminalEvent) => void): () => void;
windowControl?(action: "fullscreen" | "zoom-in" | "zoom-out" | "reset-zoom"): Promise<void>;
diff --git a/apps/native/package.json b/apps/native/package.json
index c0e7728f..795b4c7e 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -15,12 +15,14 @@
"test:electron": "bun test electron/policy.test.cjs",
"test:desktop": "bun test lib ./electron/*.test.cjs",
"test:visual": "bun scripts/test-visual.mjs",
+ "test:updates": "GRAFF_VISUAL_SUITE=updates bun scripts/test-visual.mjs",
"test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs"
},
"dependencies": {
"@streamdown/code": "^1.1.1",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
+ "electron-updater": "6.8.9",
"glimm": "^0.3.0",
"iconoir-react": "^7.11.1",
"liveline": "^0.0.7",
diff --git a/docs/adr/0079-desktop-updates-are-signed-and-user-restarted.md b/docs/adr/0079-desktop-updates-are-signed-and-user-restarted.md
new file mode 100644
index 00000000..3997b5dc
--- /dev/null
+++ b/docs/adr/0079-desktop-updates-are-signed-and-user-restarted.md
@@ -0,0 +1,28 @@
+# 0079. Desktop updates are signed and restarted explicitly
+
+Status: accepted
+
+## Decision
+
+The Electron desktop uses electron-updater with the public GitHub stable release
+feed. Distribution packaging embeds the feed before signing and produces a ZIP
+of the signed, notarized, stapled app with a SHA-512 update manifest. Native
+Squirrel.Mac verifies the app signature before replacement. All update assets
+must be attached to the draft before the release becomes the latest stable one.
+
+Checks run after startup and every six hours. Users can turn off automatic
+downloads or check manually. Background failures remain quiet. Installation
+requires the explicit Restart to update action, so a downloaded release cannot
+interrupt running tasks or terminals. The normal shutdown path owns backend and
+terminal cleanup. Development and smoke builds never use the online feed.
+
+One desktop process owns each profile. A second launch focuses it instead of
+starting another server with a different origin and separate UI preferences.
+
+## Validation
+
+Controller tests cover duplicate checks, offline recovery, download rejection,
+preferences, development builds and explicit restart. Visual tests exercise
+progress, quiet background checks and the restart action without a model.
+Distribution validation checks the signed app and DMG; the archive manifest
+identifies the exact stapled ZIP bytes.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 20f64950..8a764d5d 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -89,6 +89,7 @@ record only when you need the evidence or the edge cases.
| [0076](0076-local-agent-panel.md) | Verified local peer discovery, non-consuming history, explicit queued DMs and anonymous profiler slots. |
| [0077](0077-desktop-command-parity-and-bounded-disclosure.md) | ACP shares the complete REPL catalog; desktop menus, tool disclosure and initial history rendering stay bounded. |
| [0078](0078-workspace-terminals-are-lazy-pty-sessions.md) | Desktop workspace terminals start lazily, preserve hidden shells and bound output through a trusted PTY bridge. |
+| [0079](0079-desktop-updates-are-signed-and-user-restarted.md) | Signed desktop updates download in the background and install only on explicit restart; one process owns each profile. |
## When to write one
diff --git a/docs/releases/v0.0.291.md b/docs/releases/v0.0.291.md
new file mode 100644
index 00000000..886d8541
--- /dev/null
+++ b/docs/releases/v0.0.291.md
@@ -0,0 +1,9 @@
+Desktop updates download in the background and install when you choose Restart
+to update. The application menu also provides a manual update check and an option
+to turn off automatic downloads.
+
+The macOS download includes a signed, notarized drag-to-Applications installer.
+Earlier desktop builds need one manual installation to enable automatic updates.
+
+This release also keeps drafts readable when chat panes are resized and prevents
+duplicate desktop instances from opening separate copies of the workspace UI.