Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): save Cowork and chat writes before the app quits
thinhlpg2f08f5bb3cf7
diff --git a/web-app/src/lib/__tests__/coworkClose.test.ts b/web-app/src/lib/__tests__/coworkClose.test.tsindex 28e4fb349..c212db9d8 100644--- a/web-app/src/lib/__tests__/coworkClose.test.ts+++ b/web-app/src/lib/__tests__/coworkClose.test.ts@@ -61,14 +61,15 @@ describe('Cowork close with the installed Tauri API', () => {storage.create.mockImplementation(() => storage)storage.flush.mockResolvedValue(undefined)storage.remove.mockResolvedValue(undefined)+ const callbacks: Array<typeof dispatchClose> = []vi.stubGlobal('__TAURI_INTERNALS__', {metadata: { currentWindow: { label: 'main' } },- transformCallback: (callback: typeof dispatchClose) => {- dispatchClose = callback- return 42- },+ transformCallback: (callback: typeof dispatchClose) => callbacks.push(callback) - 1,invoke: invoke.mockImplementation(async (command, args) => {- if (command === 'plugin:event|listen') return 1+ if (command === 'plugin:event|listen') {+ if (args.event === closeEvent.event) dispatchClose = callbacks[args.handler]+ return 1+ }if (command === 'plugin:window|destroy') {// Deliberately only an assertion of file/API alignment, not an ACL// emulator. Rust is responsible for enforcing the actual permission.@@ -100,7 +101,7 @@ describe('Cowork close with the installed Tauri API', () => {it('dispatches destroy only after queued writes AND pending deletes settle', async () => {await startCoworkSync()expect(invoke).toHaveBeenCalledWith('plugin:event|listen', {- event: closeEvent.event, target: { kind: 'Window', label: 'main' }, handler: 42,+ event: closeEvent.event, target: { kind: 'Window', label: 'main' }, handler: expect.any(Number),}, undefined)const writes = deferred()const deletes = deferred()diff --git a/web-app/src/lib/__tests__/coworkSync.test.ts b/web-app/src/lib/__tests__/coworkSync.test.tsindex 673d74038..469ac7874 100644--- a/web-app/src/lib/__tests__/coworkSync.test.ts+++ b/web-app/src/lib/__tests__/coworkSync.test.ts@@ -58,6 +58,9 @@ const backend = vi.hoisted(() => {returncase 'main_window_hides_on_close':return window.hidesOnClose+ case 'exit_after_save':+ case 'cancel_exit_save':+ returndefault:throw new Error(`unexpected ${cmd}`)}@@ -100,6 +103,8 @@ vi.mock('@/i18n/react-i18next-compat', () => ({}))const closeWindow = vi.hoisted(() => ({callback: null as null | ((event: { preventDefault: () => void }) => Promise<void>),+ // The `app-exit-requested` listener Rust fires on tray Quit / Cmd+Q.+ onExitRequested: null as null | (() => Promise<void>),destroy: vi.fn(async () => {}),}))vi.mock('@tauri-apps/api/window', () => ({@@ -109,6 +114,10 @@ vi.mock('@tauri-apps/api/window', () => ({closeWindow.callback = callbackreturn () => {}}),+ listen: vi.fn(async (event: string, callback: () => Promise<void>) => {+ if (event === 'app-exit-requested') closeWindow.onExitRequested = callback+ return () => {}+ }),}),}))@@ -630,5 +639,54 @@ describe('coworkSync', () => {expect(event.preventDefault).not.toHaveBeenCalled()expect(backend.extras.has(id)).toBe(true)})++ describe('quit (tray Quit, Cmd+Q)', () => {+ it('stops live runs and saves, then lets Rust finish the held exit', async () => {+ await startCoworkSync()+ const id = useCoworkSessions.getState().createSession()+ let commit!: () => void+ const committed = new Promise<void>((r) => (commit = r))+ registerCoworkRunForClose(async () => {+ await committed+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'last words' }], legacy('x').messages, [])+ })+ const quitting = closeWindow.onExitRequested!()+ await Promise.resolve()+ expect(backend.log).not.toContain('exit_after_save')+ commit()+ await quitting+ expect(backend.extras.get(id).turns).toEqual([{ role: 'user', content: 'last words' }])+ // Exit is released only after the save landed.+ expect(backend.log.indexOf('exit_after_save')).toBeGreaterThan(+ backend.log.lastIndexOf('write_thread_extra')+ )+ expect(backend.log).not.toContain('cancel_exit_save')+ })++ it('cancels the exit when a write fails, and offers quit-without-saving after repeated failures', async () => {+ await startCoworkSync()+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'keep' }], legacy('x').messages, [])+ backend.hooks.before = async (cmd) => {+ if (cmd === 'write_thread_extra') throw new Error('disk full')+ }+ const errorOptions = () => sonner.error.mock.calls.map((call) => call[1])+ for (let attempt = 1; attempt <= COWORK_CLOSE_FAILURES_BEFORE_FORCE; attempt += 1) {+ await closeWindow.onExitRequested!()+ expect(backend.log.filter((c) => c === 'cancel_exit_save')).toHaveLength(attempt)+ expect(errorOptions().at(-1)?.description).toBe(+ attempt < COWORK_CLOSE_FAILURES_BEFORE_FORCE+ ? 'common:coworkSync.quitFailedDescription'+ : 'common:coworkSync.closeForceDescription'+ )+ }+ expect(backend.log).not.toContain('exit_after_save')+ expect(isCoworkClosing()).toBe(false)+ const action = errorOptions().at(-1).action+ expect(action.label).toBe('common:coworkSync.quitAnyway')+ action.onClick()+ await vi.waitFor(() => expect(backend.log).toContain('exit_after_save'))+ })+ })})})diff --git a/web-app/src/lib/coworkSync.ts b/web-app/src/lib/coworkSync.tsindex be2913f42..497478e6f 100644--- a/web-app/src/lib/coworkSync.ts+++ b/web-app/src/lib/coworkSync.ts@@ -487,58 +487,91 @@ async function installCloseHandlers() {// and in-flight write has settled. On failure keep the window (and the// unsaved state) alive; another close request retries storage rather// than losing the run.- try {- // A live run has not committed its transcript or wire history yet: stop- // it and await its final commit BEFORE draining storage, or the last- // turn would be written after the flush. Still flush the other sessions- // if one participant fails to settle cleanly.- await withChatCloseDeadline(- (async () => {- const runs = await Promise.allSettled([quiesceCoworkRuns(), quiesceChats()])- const writes = await flushAllWrites()- const failed = [...runs, ...writes].find((r) => r.status === 'rejected')- if (failed?.status === 'rejected') throw failed.reason- })()- )- closeFailures = 0- toast.dismiss(CLOSE_FAILED_TOAST_ID)- } catch (e) {- event.preventDefault()- resumeCoworkAfterPreventedClose()- resumeChatsAfterPreventedClose()- console.warn('[cowork] flush on close failed:', e)- closeFailures += 1- // Keeping the window is the default (data loss is worse than a stuck- // window), but the user must always see why it did not close, and after- // repeated failures get an explicit way out that names the cost.- const canForce = closeFailures >= COWORK_CLOSE_FAILURES_BEFORE_FORCE- toast.error(i18n.t('common:coworkSync.closeFailedTitle'), {- id: CLOSE_FAILED_TOAST_ID,- duration: Infinity,- description: i18n.t(- canForce- ? 'common:coworkSync.closeForceDescription'- : 'common:coworkSync.closeFailedDescription'- ),- action: canForce- ? {- label: i18n.t('common:coworkSync.closeAnyway'),- // destroy() skips the close-requested event that would block it.- onClick: () => {- void appWindow.destroy().catch((error) => {- console.warn('[cowork] could not close the window:', error)- })- },- }- : undefined,+ if (await saveBeforeExit()) return+ event.preventDefault()+ reportExitSaveFailure('close', () => {+ // destroy() skips the close-requested event that would block it.+ void appWindow.destroy().catch((error) => {+ console.warn('[cowork] could not close the window:', error)})+ })+ })+ // Quit (tray, Cmd+Q): Rust holds the exit until this answers.+ await appWindow.listen('app-exit-requested', async () => {+ const invoke = getInvoke()+ if (await saveBeforeExit()) {+ await invoke('exit_after_save')+ return}+ await invoke('cancel_exit_save')+ reportExitSaveFailure('quit', () => {+ void invoke('exit_after_save').catch((error) => {+ console.warn('[cowork] could not quit:', error)+ })+ })})} catch (e) {console.warn('[cowork] could not register the close handler:', e)}}+/**+ * Stop live runs and save every pending write before the app exits. A live run+ * has not committed its transcript or wire history yet: stop it and await its+ * final commit BEFORE draining storage, or the last turn would be written after+ * the flush. Still flush the other sessions if one participant fails to settle+ * cleanly. Returns false (runs resumed) when anything could not be saved.+ */+async function saveBeforeExit(): Promise<boolean> {+ try {+ await withChatCloseDeadline(+ (async () => {+ const runs = await Promise.allSettled([quiesceCoworkRuns(), quiesceChats()])+ const writes = await flushAllWrites()+ const failed = [...runs, ...writes].find((r) => r.status === 'rejected')+ if (failed?.status === 'rejected') throw failed.reason+ })()+ )+ closeFailures = 0+ toast.dismiss(CLOSE_FAILED_TOAST_ID)+ return true+ } catch (e) {+ resumeCoworkAfterPreventedClose()+ resumeChatsAfterPreventedClose()+ console.warn('[cowork] flush on close failed:', e)+ return false+ }+}++/**+ * Keeping the app open is the default (data loss is worse than a stuck+ * window), but the user must always see why it did not close or quit, and+ * after repeated failures get an explicit way out that names the cost.+ */+function reportExitSaveFailure(kind: 'close' | 'quit', force: () => void) {+ closeFailures += 1+ const canForce = closeFailures >= COWORK_CLOSE_FAILURES_BEFORE_FORCE+ toast.error(i18n.t('common:coworkSync.closeFailedTitle'), {+ id: CLOSE_FAILED_TOAST_ID,+ duration: Infinity,+ description: i18n.t(+ canForce+ ? 'common:coworkSync.closeForceDescription'+ : kind === 'quit'+ ? 'common:coworkSync.quitFailedDescription'+ : 'common:coworkSync.closeFailedDescription'+ ),+ action: canForce+ ? {+ label: i18n.t(+ kind === 'quit' ? 'common:coworkSync.quitAnyway' : 'common:coworkSync.closeAnyway'+ ),+ onClick: force,+ }+ : undefined,+ })+}+/** Test seam: forget all module state. */export function __resetCoworkSyncForTests() {__resetCoworkRunCloseForTests()diff --git a/web-app/src/locales/de-DE/common.json b/web-app/src/locales/de-DE/common.jsonindex 18945459b..045c4c6cd 100644--- a/web-app/src/locales/de-DE/common.json+++ b/web-app/src/locales/de-DE/common.json@@ -425,7 +425,9 @@"closeFailedTitle": "Jan konnte nicht alles speichern und bleibt daher geöffnet","closeFailedDescription": "Ihre letzten Änderungen befinden sich noch im Arbeitsspeicher. Schließen Sie das Fenster erneut, um das Speichern zu wiederholen.","closeForceDescription": "Das Speichern schlägt weiterhin fehl. Sie können ohne Speichern schließen; dabei gehen die Änderungen verloren, die nicht geschrieben werden konnten.",- "closeAnyway": "Ohne Speichern schließen"+ "closeAnyway": "Ohne Speichern schließen",+ "quitFailedDescription": "Ihre letzten Änderungen befinden sich noch im Arbeitsspeicher. Beenden Sie Jan erneut, um das Speichern zu wiederholen.",+ "quitAnyway": "Ohne Speichern beenden"},"messageWrites": {"failedTitle": "Einige Nachrichten konnten nicht gespeichert werden",diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 551be4f82..4e11f063c 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -809,7 +809,9 @@"closeFailedTitle": "Jan could not save everything, so it stayed open","closeFailedDescription": "Your latest changes are still in memory. Close the window again to retry saving.","closeForceDescription": "Saving keeps failing. You can close without saving, which loses the changes that could not be written.",- "closeAnyway": "Close without saving"+ "closeAnyway": "Close without saving",+ "quitFailedDescription": "Your latest changes are still in memory. Quit again to retry saving.",+ "quitAnyway": "Quit without saving"},"messageWrites": {"failedTitle": "Some messages could not be saved",diff --git a/web-app/src/locales/fr/common.json b/web-app/src/locales/fr/common.jsonindex 2979f35dd..a53cf5377 100644--- a/web-app/src/locales/fr/common.json+++ b/web-app/src/locales/fr/common.json@@ -428,7 +428,9 @@"closeFailedTitle": "Jan n'a pas pu tout enregistrer et est resté ouvert","closeFailedDescription": "Vos dernières modifications sont encore en mémoire. Fermez à nouveau la fenêtre pour réessayer l'enregistrement.","closeForceDescription": "L'enregistrement échoue toujours. Vous pouvez fermer sans enregistrer, ce qui perd les modifications qui n'ont pas pu être écrites.",- "closeAnyway": "Fermer sans enregistrer"+ "closeAnyway": "Fermer sans enregistrer",+ "quitFailedDescription": "Vos dernières modifications sont encore en mémoire. Quittez à nouveau pour réessayer l'enregistrement.",+ "quitAnyway": "Quitter sans enregistrer"},"messageWrites": {"failedTitle": "Certains messages n'ont pas pu être enregistrés",diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.jsonindex 36ed96943..da8790b2c 100644--- a/web-app/src/locales/ja/common.json+++ b/web-app/src/locales/ja/common.json@@ -542,7 +542,9 @@"closeFailedTitle": "Janはすべてを保存できなかったため、開いたままです","closeFailedDescription": "最新の変更はまだメモリ上にあります。もう一度ウィンドウを閉じると、保存を再試行します。","closeForceDescription": "保存が失敗し続けています。保存せずに閉じることもできますが、書き込めなかった変更は失われます。",- "closeAnyway": "保存せずに閉じる"+ "closeAnyway": "保存せずに閉じる",+ "quitFailedDescription": "最新の変更はまだメモリ上にあります。もう一度終了すると保存を再試行します。",+ "quitAnyway": "保存せずに終了"},"messageWrites": {"failedTitle": "保存できなかったメッセージがあります",diff --git a/web-app/src/locales/zh-CN/common.json b/web-app/src/locales/zh-CN/common.jsonindex 56ff8996a..2ff7c1146 100644--- a/web-app/src/locales/zh-CN/common.json+++ b/web-app/src/locales/zh-CN/common.json@@ -604,7 +604,9 @@"closeFailedTitle": "Jan 未能保存全部内容,因此保持打开","closeFailedDescription": "您最近的更改仍在内存中。再次关闭窗口即可重试保存。","closeForceDescription": "保存持续失败。您可以不保存直接关闭,但无法写入的更改将会丢失。",- "closeAnyway": "不保存并关闭"+ "closeAnyway": "不保存并关闭",+ "quitFailedDescription": "您最近的更改仍在内存中。再次退出以重试保存。",+ "quitAnyway": "不保存并退出"},"messageWrites": {"failedTitle": "部分消息未能保存",