Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Automatically install and restart desktop updates

Regan Bellbcee65270328
diff --git a/desktop/README.md b/desktop/README.md
index b97c4c968..8c3a9ecec 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -15,7 +15,7 @@ QM_DESKTOP_URL=http://localhost:3000 npm start
npm run package
```
-Packaging writes a native app for the current platform into `desktop/dist/`, registering the `qm-desktop` URL scheme. Use the packaged app for browser sign-in. The macOS build is an unsigned local prototype, with no automatic updates. It connects to a running server; it does not bundle the QM backend or provide offline agent execution.
+Packaging writes a native app for the current platform into `desktop/dist/`, registering the `qm-desktop` URL scheme. Use the packaged app for browser sign-in. The macOS build is an unsigned local prototype, without automatic updates in development. It connects to a running server; it does not bundle the QM backend or provide offline agent execution.
## Browser sign-in
@@ -37,13 +37,16 @@ Same-instance links opened in a new tab use a separate sandboxed window sharing
## Mac release
-`npm run package` builds the unsigned local app. For a signed and notarized build, install a Developer ID Application certificate in the Mac keychain and store notarization credentials using Apple's `notarytool`. Then run:
+`npm run package` builds the unsigned local app. For a signed and notarized build, install a Developer ID Application certificate in the Mac keychain and sign in to that team in Xcode Settings → Accounts. Then run:
```sh
-QM_MAC_SIGN_IDENTITY="Developer ID Application: Your Organization (TEAMID)" \
-QM_MAC_NOTARY_PROFILE="qm-notary" npm run package:release
+QM_MAC_SIGN_IDENTITY="Developer ID Application: Your Organization (TEAMID)" npm run package:release
```
-The release command requires both values and fails if signing or notarization fails. Neither credentials nor certificates belong in this repository. Builds target the current machine's architecture. Automatic updates are not implemented.
+The release command signs the app, submits an archive using the signed-in Xcode account, waits for notarization, and verifies the stapled ticket and Gatekeeper assessment. It produces the notarized ZIP, SHA256SUMS.txt, and RELEASES.json in desktop/dist. Credentials and certificates stay outside this repository. Builds target the current machine's architecture.
+
+Packaged Apple Silicon builds check the desktop-only feed on startup and every five minutes. Updates download in the background and restart QM automatically without a confirmation dialog. Restart waits while a composer has a pending submission, file processing, staged attachments, or an open paste editor. Older servers without the update-readiness handshake defer automatic restarts until their web UI is upgraded. Open non-web previews, such as PDFs, also defer restart until closed. Interaction pauses briefly while the app saves restart state. Before restarting, QM flushes saved text drafts and pane layout, saves the current instance page, and flushes its persistent browser session. Server-side agent work continues during restart. QM → Check for Updates triggers an immediate check. Development, Intel, Windows, and Linux builds do not use this Mac feed. Versions 0.1.0 and 0.1.1 require one manual upgrade to receive the updater.
+
+Publish the verified ZIP and checksum as desktop-v<VERSION>, then upload RELEASES.json to the dedicated desktop-updates GitHub release using gh release upload desktop-updates desktop/dist/RELEASES.json --clobber --repo yc-software/qm. Update the feed only after the versioned download is published and verified. The feed uses Squirrel.Mac's static JSON format and points to the immutable versioned ZIP; backend and dependency releases never enter it.
`npm run test:electron` exercises actual Electron preview windows, POST popups, session sharing, sandboxing, and browser handoff against a temporary local server.
diff --git a/desktop/main.mjs b/desktop/main.mjs
index da40d8c7e..2fc213e1f 100644
--- a/desktop/main.mjs
+++ b/desktop/main.mjs
@@ -1,8 +1,9 @@
import { app, BrowserWindow, dialog, ipcMain, Menu, shell, session as electronSession } from "electron";
-import { readFile, writeFile } from "node:fs/promises";
+import { readFile, writeFile, rename } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createLogin, loginCallback } from "./login.mjs";
+import { startUpdates } from "./updates.mjs";
import { tabStep } from "./shortcuts.mjs";
import { instanceUrl, externalUrl, browserLoginUrl, loginDestination, internalUrl } from "./url.mjs";
@@ -253,6 +254,37 @@ async function start() {
if (error.code !== "ENOENT") dialog.showErrorBox("QM settings could not be read", error.message);
}
if (process.env.QM_DESKTOP_URL) target = instanceUrl(process.env.QM_DESKTOP_URL);
+ const saveInstance = async (url) => {
+ await writeFile(`${configPath}.tmp`, JSON.stringify({ url }), { mode: 0o600 });
+ await rename(`${configPath}.tmp`, configPath);
+ };
+ const checkForUpdates = startUpdates(
+ async () => {
+ for (const page of workspaceWindows) if (!page.isDestroyed()) page.setEnabled(false);
+ for (const page of workspaceWindows) {
+ if (page.isDestroyed()) continue;
+ const ready = await page.webContents.executeJavaScript(`(() => {
+ const event = new CustomEvent("qm:prepare-update", { cancelable: true, detail: { ready: false } });
+ return window.dispatchEvent(event) && event.detail.ready;
+ })()`);
+ if (!ready) return false;
+ }
+ for (const page of workspaceWindows) {
+ if (page.isDestroyed()) continue;
+ await page.webContents.executeJavaScript('window.dispatchEvent(new Event("pagehide"))');
+ page.webContents.session.flushStorageData();
+ await page.webContents.session.cookies.flushStore();
+ }
+ if (target) {
+ const current = mainWindow?.webContents.getURL();
+ await saveInstance(loginDestination(target, target, current));
+ }
+ return true;
+ },
+ () => {
+ for (const page of workspaceWindows) if (!page.isDestroyed()) page.setEnabled(true);
+ },
+ );
const assertSetup = (event) => {
if (event.sender !== setupWindow?.webContents || event.senderFrame?.url !== setupUrl) {
throw new Error("Untrusted settings request");
@@ -287,7 +319,7 @@ async function start() {
assertSetup(event);
try {
const url = instanceUrl(value);
- await writeFile(configPath, JSON.stringify({ url }), { mode: 0o600 });
+ await saveInstance(url);
target = url;
void showInstance(url);
setupWindow.close();
@@ -302,6 +334,7 @@ async function start() {
label: "QM",
submenu: [
{ role: "about" },
+ { label: "Check for Updates", enabled: Boolean(checkForUpdates), click: checkForUpdates },
{ label: "Change Instance…", accelerator: "CmdOrCtrl+,", click: showSetup },
{
label: "Open in Browser",
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 9f25785d9..6e58d8e9e 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -1,12 +1,15 @@
{
"name": "qm-desktop",
- "version": "0.1.1",
+ "version": "0.1.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "qm-desktop",
- "version": "0.1.1",
+ "version": "0.1.2",
+ "dependencies": {
+ "update-electron-app": "3.3.0"
+ },
"devDependencies": {
"@electron/packager": "20.3.0",
"electron": "44.4.3",
@@ -165,6 +168,7 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=20.19.0"
},
@@ -213,6 +217,7 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=20.19.0"
}
@@ -668,6 +673,15 @@
"node": ">=22.12.0"
}
},
+ "node_modules/github-url-to-object": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/github-url-to-object/-/github-url-to-object-4.0.6.tgz",
+ "integrity": "sha512-NaqbYHMUAlPcmWFdrAB7bcxrNIiiJWJe8s/2+iOc9vlcHlwHqSGrPk+Yi3nu6ebTwgsZEa7igz+NH2vEq3gYwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "is-url": "^1.1.0"
+ }
+ },
"node_modules/glob": {
"version": "13.0.6",
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
@@ -713,6 +727,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/is-url": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz",
+ "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==",
+ "license": "MIT"
+ },
"node_modules/isbinaryfile": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",
@@ -834,7 +854,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true,
"license": "MIT"
},
"node_modules/parse5": {
@@ -1137,6 +1156,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/update-electron-app": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/update-electron-app/-/update-electron-app-3.3.0.tgz",
+ "integrity": "sha512-5s73OcyNhAvogjxzAy8pbephY+bP6aXpXFv68OT1dNiEbcUpIUCv/ZZPalqGclnXUgx3oyn+yVdAIIVUpn/C1g==",
+ "license": "MIT",
+ "dependencies": {
+ "github-url-to-object": "^4.0.4",
+ "ms": "^2.1.1"
+ }
+ },
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
diff --git a/desktop/package.json b/desktop/package.json
index 7ab5c8697..b5b5fe824 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "qm-desktop",
"productName": "QM",
- "version": "0.1.1",
+ "version": "0.1.2",
"private": true,
"type": "module",
"main": "main.mjs",
@@ -16,5 +16,8 @@
"@electron/packager": "20.3.0",
"electron": "44.4.3",
"jsdom": "^29.1.1"
+ },
+ "dependencies": {
+ "update-electron-app": "3.3.0"
}
}
diff --git a/desktop/package.mjs b/desktop/package.mjs
index 2e62735fd..38afa98ea 100644
--- a/desktop/package.mjs
+++ b/desktop/package.mjs
@@ -1,13 +1,16 @@
import { packager } from "@electron/packager";
import path from "node:path";
+import { execFile as execFileCallback } from "node:child_process";
+import { promisify } from "node:util";
+import { mkdir, readFile, writeFile, rm } from "node:fs/promises";
+import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
const directory = path.dirname(fileURLToPath(import.meta.url));
const release = process.argv.includes("--release");
const identity = process.env.QM_MAC_SIGN_IDENTITY;
-const keychainProfile = process.env.QM_MAC_NOTARY_PROFILE;
-if (release && (process.platform !== "darwin" || !identity || !keychainProfile)) {
- throw new Error("Mac releases require macOS, QM_MAC_SIGN_IDENTITY and QM_MAC_NOTARY_PROFILE.");
+if (release && (process.platform !== "darwin" || process.arch !== "arm64" || !identity)) {
+ throw new Error("Mac releases require Apple Silicon macOS, QM_MAC_SIGN_IDENTITY and a signed-in Xcode account.");
}
const apps = await packager({
dir: directory,
@@ -19,6 +22,104 @@ const apps = await packager({
overwrite: true,
asar: true,
ignore: /^\/(dist|test|README\.md|package\.mjs)/,
- ...(release ? { osxSign: { identity }, osxNotarize: { keychainProfile } } : {}),
+ ...(release ? { osxSign: { identity } } : {}),
});
for (const app of apps) console.log(app);
+
+if (release) {
+ const execFile = promisify(execFileCallback);
+ const output = path.join(directory, "dist");
+ const archive = path.join(output, "QM.xcarchive");
+ const app = path.join(apps[0], "QM.app");
+ const { version } = JSON.parse(await readFile(path.join(directory, "package.json"), "utf8"));
+ const signature = await execFile("codesign", ["-dv", "--verbose=4", app]);
+ const team = signature.stderr
+ .split("\n")
+ .find((line) => line.startsWith("TeamIdentifier="))
+ ?.split("=")[1];
+ if (!team) throw new Error("Signed app has no team identifier");
+ for (const name of ["QM.xcarchive", "submission", "notarized"]) {
+ await rm(path.join(output, name), { recursive: true, force: true });
+ }
+ await mkdir(path.join(archive, "Products", "Applications"), { recursive: true });
+ await execFile("ditto", [app, path.join(archive, "Products", "Applications", "QM.app")]);
+ const plist = async (file, data) => {
+ await writeFile(file, JSON.stringify(data));
+ await execFile("plutil", ["-convert", "xml1", file]);
+ };
+ await plist(path.join(archive, "Info.plist"), {
+ ArchiveVersion: 2,
+ Name: "QM",
+ SchemeName: "QM",
+ ApplicationProperties: {
+ ApplicationPath: "Applications/QM.app",
+ CFBundleIdentifier: "com.qm.desktop",
+ CFBundleShortVersionString: version,
+ CFBundleVersion: version,
+ SigningIdentity: identity,
+ Team: team,
+ Architectures: [process.arch],
+ },
+ });
+ const options = path.join(output, "export.plist");
+ await plist(options, {
+ method: "developer-id",
+ destination: "upload",
+ signingStyle: "manual",
+ signingCertificate: identity,
+ teamID: team,
+ });
+ await execFile("xcodebuild", [
+ "-exportArchive",
+ "-archivePath",
+ archive,
+ "-exportOptionsPlist",
+ options,
+ "-exportPath",
+ path.join(output, "submission"),
+ ]);
+ console.log("Uploaded to Apple; waiting for notarization");
+ const notarized = path.join(output, "notarized");
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await execFile("xcodebuild", ["-exportNotarizedApp", "-archivePath", archive, "-exportPath", notarized]);
+ break;
+ } catch (error) {
+ if (attempt >= 20 || !`${error.stdout} ${error.stderr}`.includes("is processing and not ready")) throw error;
+ await new Promise((resolve) => setTimeout(resolve, 30_000));
+ }
+ }
+ const signedApp = path.join(notarized, "QM.app");
+ await execFile("codesign", ["--verify", "--deep", "--strict", signedApp]);
+ await execFile("xcrun", ["stapler", "validate", signedApp]);
+ await execFile("spctl", ["--assess", "--type", "execute", signedApp]);
+ const filename = `QM-mac-${process.arch}.zip`;
+ await execFile("ditto", ["-c", "-k", "--sequesterRsrc", "--keepParent", signedApp, path.join(output, filename)]);
+ const bytes = await readFile(path.join(output, filename));
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
+ await writeFile(path.join(output, "SHA256SUMS.txt"), `${sha256} ${filename}\n`);
+ await writeFile(
+ path.join(output, "RELEASES.json"),
+ JSON.stringify(
+ {
+ currentRelease: version,
+ releases: [
+ {
+ version,
+ updateTo: {
+ version,
+ name: `QM ${version}`,
+ pub_date: new Date().toISOString(),
+ url: `https://github.com/yc-software/qm/releases/download/desktop-v${version}/${filename}`,
+ sha256,
+ size: bytes.length,
+ },
+ },
+ ],
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ console.log(`Verified release files: ${output}`);
+}
diff --git a/desktop/test/main.test.mjs b/desktop/test/main.test.mjs
index f4bb7e451..54b93fced 100644
--- a/desktop/test/main.test.mjs
+++ b/desktop/test/main.test.mjs
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
-import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { mock, test } from "node:test";
@@ -21,6 +21,16 @@ test(
getPath: () => directory,
setAsDefaultProtocolClient() {},
});
+ let prepareUpdate;
+ let resumeUpdate;
+ mock.module(new URL("../updates.mjs", import.meta.url).href, {
+ namedExports: {
+ startUpdates: (prepare, resume) => {
+ prepareUpdate = prepare;
+ resumeUpdate = resume;
+ },
+ },
+ });
const handlers = new Map();
const windows = [];
const initialLoad = Promise.withResolvers();
@@ -35,6 +45,7 @@ test(
setPermissionCheckHandler(handler) {
this.checkPermission = handler;
},
+ flushStorageData() {},
cookies: {
flushStore: async () => {
flushes++;
@@ -60,6 +71,9 @@ test(
this.url = url;
initialLoad.resolve();
}
+ setEnabled(value) {
+ this.enabled = value;
+ }
show() {
this.visible = true;
}
@@ -80,6 +94,7 @@ test(
mock.module("electron", {
namedExports: {
app,
+ autoUpdater: {},
BrowserWindow,
ipcMain: { handle: (name, handler) => handlers.set(name, handler) },
Menu: { buildFromTemplate: (template) => template, setApplicationMenu() {} },
@@ -211,6 +226,20 @@ test(
assert.equal(opened[1].includes("test-token"), false);
assert.equal(windows[3].isDestroyed(), true);
const active = windows.at(-1);
+ const ready = Promise.withResolvers();
+ active.webContents.executeJavaScript = async (source) =>
+ source.includes("qm:prepare-update") ? ready.promise : true;
+ const preparing = prepareUpdate();
+ assert.equal(active.enabled, false, "input is disabled before asking the renderer for readiness");
+ ready.resolve(false);
+ assert.equal(await preparing, false);
+ resumeUpdate();
+ assert.equal(active.enabled, true, "a deferred update restores input");
+ active.webContents.executeJavaScript = async () => true;
+ assert.equal(await prepareUpdate(), true);
+ assert.equal(active.enabled, false, "prepared windows remain quiescent until restart");
+ assert.equal(JSON.parse(await readFile(path.join(directory, "instance.json"), "utf8")).url, active.url);
+ resumeUpdate();
const child = new BrowserWindow({});
child.url = "https://new.example/file.pdf";
active.webContents.emit("did-create-window", child);
diff --git a/desktop/test/updates.test.mjs b/desktop/test/updates.test.mjs
new file mode 100644
index 000000000..bd259cd88
--- /dev/null
+++ b/desktop/test/updates.test.mjs
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import { mock, test } from "node:test";
+
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+
+test("updates restart only after preparation succeeds, without prompting", async () => {
+ const app = { isPackaged: false, on() {} };
+ let options;
+ let checks = 0;
+ let restarts = 0;
+ let stopped = 0;
+ const errors = [];
+ let onError;
+ mock.method(console, "error", (...args) => errors.push(args));
+ mock.module("electron", {
+ namedExports: {
+ app,
+ autoUpdater: {
+ on: (_event, callback) => (onError = callback),
+ checkForUpdates: () => checks++,
+ quitAndInstall: () => restarts++,
+ },
+ },
+ });
+ mock.module("update-electron-app", {
+ namedExports: {
+ UpdateSourceType: { StaticStorage: 1 },
+ updateElectronApp: (value) => {
+ options = value;
+ return { stopUpdates: () => stopped++ };
+ },
+ },
+ });
+ try {
+ const { startUpdates } = await import("../updates.mjs");
+ assert.equal(
+ startUpdates(() => {}),
+ undefined,
+ );
+ assert.equal(options, undefined);
+ if (process.platform !== "darwin" || process.arch !== "arm64") return;
+ app.isPackaged = true;
+ const prepared = Promise.withResolvers();
+ const check = startUpdates(() => prepared.promise);
+ check();
+ assert.equal(checks, 1);
+ assert.equal(options.updateSource.type, 1);
+ assert.equal(options.updateInterval, "5 minutes");
+ options.onNotifyUser();
+ options.onNotifyUser();
+ await tick();
+ assert.equal(restarts, 0);
+ assert.equal(stopped, 2);
+ check();
+ assert.equal(checks, 1, "manual checks must retain an already downloaded update");
+ prepared.resolve(true);
+ await tick();
+ assert.equal(restarts, 1);
+ onError();
+ options.onNotifyUser();
+ await tick();
+ assert.equal(restarts, 2);
+ startUpdates(() => Promise.reject(new Error("disk full")));
+ options.onNotifyUser();
+ await tick();
+ assert.equal(restarts, 2);
+ assert.match(errors.find((args) => args[1] instanceof Error)[1].message, /disk full/);
+ } finally {
+ mock.restoreAll();
+ }
+});
diff --git a/desktop/updates.mjs b/desktop/updates.mjs
new file mode 100644
index 000000000..9370c8f1d
--- /dev/null
+++ b/desktop/updates.mjs
@@ -0,0 +1,44 @@
+import { app, autoUpdater } from "electron";
+import { updateElectronApp, UpdateSourceType } from "update-electron-app";
+
+export function startUpdates(prepareRestart, resume = () => {}) {
+ if (!app.isPackaged || process.platform !== "darwin" || process.arch !== "arm64") return undefined;
+ let restarting = false;
+ let downloaded = false;
+ autoUpdater.on("error", () => {
+ restarting = false;
+ resume();
+ });
+ const install = async () => {
+ if (!downloaded || restarting) return;
+ restarting = true;
+ try {
+ if (!(await prepareRestart())) {
+ restarting = false;
+ resume();
+ return;
+ }
+ autoUpdater.quitAndInstall();
+ } catch (error) {
+ restarting = false;
+ resume();
+ console.error("QM could not prepare to install its update", error);
+ }
+ };
+ const retry = setInterval(() => void install(), 5000);
+ retry.unref();
+ app.on("will-quit", () => clearInterval(retry));
+ const updater = updateElectronApp({
+ updateSource: {
+ type: UpdateSourceType.StaticStorage,
+ baseUrl: "https://github.com/yc-software/qm/releases/download/desktop-updates",
+ },
+ updateInterval: "5 minutes",
+ onNotifyUser: () => {
+ updater.stopUpdates();
+ downloaded = true;
+ void install();
+ },
+ });
+ return () => (downloaded ? void install() : autoUpdater.checkForUpdates());
+}
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index 385e01fb3..10486f2da 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -1511,7 +1511,31 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {
ctx.chat.resumeIfIdle();
}
+ let pendingSubmissions = 0;
+ let disposed = false;
+ const preventUnsafeUpdate = (event: Event): void => {
+ if (
+ pendingSubmissions ||
+ composerState.attachments.length ||
+ composerState.processingFiles ||
+ composerState.pasteView
+ ) {
+ event.preventDefault();
+ }
+ };
+ window.addEventListener("qm:prepare-update", preventUnsafeUpdate);
+
async function sendPrompt(agent: Agent): Promise<void> {
+ pendingSubmissions++;
+ try {
+ await sendPromptNow(agent);
+ } finally {
+ pendingSubmissions--;
+ if (disposed && !pendingSubmissions) window.removeEventListener("qm:prepare-update", preventUnsafeUpdate);
+ }
+ }
+
+ async function sendPromptNow(agent: Agent): Promise<void> {
if (!composerCanSend()) return;
if (composerState.pasteView) closePasteView(agent);
if (agent.state.isStreaming) return queueDraft(agent);
@@ -1969,6 +1993,8 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {
}
function dispose(): void {
+ disposed = true;
+ if (!pendingSubmissions) window.removeEventListener("qm:prepare-update", preventUnsafeUpdate);
window.removeEventListener("model-account-changed", refreshAccount);
document.removeEventListener("visibilitychange", revalidateRuntime);
modelPicker.dispose();
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index 22bfb782b..921ced95c 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -1225,3 +1225,7 @@ export async function boot(): Promise<void> {
mainConversation().newChat();
}
}
+
+window.addEventListener("qm:prepare-update", (event) => {
+ (event as CustomEvent<{ ready: boolean }>).detail.ready = true;
+});
diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.ts
index 09f57cb69..eec22e402 100644
--- a/plugins/web-ui/src/split.ts
+++ b/plugins/web-ui/src/split.ts
@@ -163,6 +163,11 @@ function pushRemoteSoon(payload: { updatedAt: number }): void {
}
function flushRemoteNow(): void {
+ if (persistTimer !== null) {
+ window.clearTimeout(persistTimer);
+ persistTimer = null;
+ persist();
+ }
if (remoteTimer !== null) {
window.clearTimeout(remoteTimer);
remoteTimer = null;
diff --git a/plugins/web-ui/test/inbox-upload-draft.test.ts b/plugins/web-ui/test/inbox-upload-draft.test.ts
index 794e1528b..266e9190d 100644
--- a/plugins/web-ui/test/inbox-upload-draft.test.ts
+++ b/plugins/web-ui/test/inbox-upload-draft.test.ts
@@ -85,10 +85,20 @@ test("a submission freezes the edited draft before upload and never retries a co
state.inboxTestComposer!.state.attachments = [
{ id: "file", type: "document", fileName: "notes.txt", mimeType: "text/plain", size: 1, content: "eA==" },
];
+ assert.equal(
+ window.dispatchEvent(new CustomEvent("qm:prepare-update", { cancelable: true, detail: { ready: false } })),
+ false,
+ "staged attachments block restart",
+ );
const saving = inbox.persistDraft(item);
await until(() => Boolean(releaseEdit));
host.querySelector<HTMLButtonElement>(".inbox-suggest-chip.primary")!.click();
await until(() => Boolean(releaseUpload));
+ assert.equal(
+ window.dispatchEvent(new CustomEvent("qm:prepare-update", { cancelable: true, detail: { ready: false } })),
+ false,
+ "in-flight upload blocks restart after clearing composer",
+ );
releaseEdit!();
await saving;
releaseUpload!();