Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(web-app): keep the app running when closing the window only hides it

thinhlpg3f4d9ccf0229
diff --git a/web-app/src/lib/__tests__/coworkClose.test.ts b/web-app/src/lib/__tests__/coworkClose.test.ts
index d008e849d..28e4fb349 100644
--- a/web-app/src/lib/__tests__/coworkClose.test.ts
+++ b/web-app/src/lib/__tests__/coworkClose.test.ts
@@ -131,7 +131,8 @@ describe('Cowork close with the installed Tauri API', () => {
registerCoworkRunForClose(otherRun)
vi.spyOn(console, 'warn').mockImplementation(() => {})
const closing = dispatchClose(closeEvent)
- expect(badRun).toHaveBeenCalledOnce()
+ // The handler first asks Rust whether this close only hides the window.
+ await vi.waitFor(() => expect(badRun).toHaveBeenCalledOnce())
expect(otherRun).toHaveBeenCalledOnce()
await Promise.resolve()
expect(storage.flush).not.toHaveBeenCalled()
diff --git a/web-app/src/lib/__tests__/coworkSync.test.ts b/web-app/src/lib/__tests__/coworkSync.test.ts
index 74ef0f96a..673d74038 100644
--- a/web-app/src/lib/__tests__/coworkSync.test.ts
+++ b/web-app/src/lib/__tests__/coworkSync.test.ts
@@ -12,6 +12,8 @@ const backend = vi.hoisted(() => {
const logs = new Map<string, any[]>()
const log: string[] = []
const hooks: { before?: (cmd: string, args: Record<string, any>) => Promise<void> } = {}
+ // What Rust answers for `main_window_hides_on_close`.
+ const window = { hidesOnClose: false }
const invoke = async (cmd: string, args: Record<string, any> = {}) => {
log.push(cmd)
await hooks.before?.(cmd, args)
@@ -54,11 +56,13 @@ const backend = vi.hoisted(() => {
extras.delete(args.threadId)
logs.delete(args.threadId)
return
+ case 'main_window_hides_on_close':
+ return window.hidesOnClose
default:
throw new Error(`unexpected ${cmd}`)
}
}
- return { settings, threads, extras, logs, log, hooks, invoke }
+ return { settings, threads, extras, logs, log, hooks, window, invoke }
})
const messageStore = vi.hoisted(() => ({
@@ -166,6 +170,7 @@ describe('coworkSync', () => {
backend.logs.clear()
backend.log.length = 0
backend.hooks.before = undefined
+ backend.window.hidesOnClose = false
agentTools.cleanupThreadWorkspace.mockClear()
sonner.warning.mockClear()
sonner.dismiss.mockClear()
@@ -487,6 +492,26 @@ describe('coworkSync', () => {
expect(backend.threads.has(id)).toBe(true)
})
+ it('a close that only hides the window keeps live runs going and the app alive, and still saves', async () => {
+ backend.window.hidesOnClose = true
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'keep' }], legacy('x').messages, [])
+ const quiesce = vi.fn(async () => {})
+ registerCoworkRunForClose(quiesce)
+ const event = closeEvent()
+ await closeWindow.callback!(event)
+ // preventDefault stops the Tauri API from destroying the last window,
+ // which would quit the app.
+ expect(event.preventDefault).toHaveBeenCalled()
+ expect(quiesce).not.toHaveBeenCalled()
+ expect(isCoworkClosing()).toBe(false)
+ await vi.waitFor(() =>
+ expect(backend.extras.get(id)?.turns).toEqual([{ role: 'user', content: 'keep' }])
+ )
+ expect(sonner.error).not.toHaveBeenCalled()
+ })
+
it('prevents the close when a write cannot be flushed, keeps the unsaved session, and a retry succeeds', async () => {
await startCoworkSync()
const id = useCoworkSessions.getState().createSession()
diff --git a/web-app/src/lib/coworkSync.ts b/web-app/src/lib/coworkSync.ts
index 4ac4913b7..be2913f42 100644
--- a/web-app/src/lib/coworkSync.ts
+++ b/web-app/src/lib/coworkSync.ts
@@ -428,6 +428,20 @@ async function finishLateMigration(
}
}
+/**
+ * Whether Rust hides the main window on this close instead of closing it
+ * (`main_window_hides_on_close`). On error assume a real close: that path
+ * saves everything before the window goes.
+ */
+async function hidesOnClose(): Promise<boolean> {
+ try {
+ return (await getInvoke()<boolean>('main_window_hides_on_close')) === true
+ } catch (e) {
+ console.warn('[cowork] could not read the close behaviour:', e)
+ return false
+ }
+}
+
async function installCloseHandlers() {
if (closeListenersInstalled) return
closeListenersInstalled = true
@@ -456,9 +470,23 @@ async function installCloseHandlers() {
const { getCurrentWindow } = await import('@tauri-apps/api/window')
const appWindow = getCurrentWindow()
await appWindow.onCloseRequested(async (event) => {
- // Awaiting here holds the close until every queued 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.
+ // When Rust only hides the window (macOS, or the background API server
+ // on Windows/Linux) the app keeps running: keep live runs going, save in
+ // the background, and prevent the destroy() that would quit the app.
+ if (await hidesOnClose()) {
+ event.preventDefault()
+ void flushAllWrites().then((writes) => {
+ const failed = writes.find((r) => r.status === 'rejected')
+ if (failed?.status === 'rejected') {
+ console.warn('[cowork] flush on hide failed:', failed.reason)
+ }
+ })
+ return
+ }
+ // A real close quits the app. Awaiting here holds it until every queued
+ // 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