Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(web-app): show Cowork sessions the migration gave up on as not imported, with Try again and Export
thinhlpgeb7fc72a4425
diff --git a/web-app/src/containers/CoworkPage.tsx b/web-app/src/containers/CoworkPage.tsxindex cd83af5e2..07b8d2eda 100644--- a/web-app/src/containers/CoworkPage.tsx+++ b/web-app/src/containers/CoworkPage.tsx@@ -74,6 +74,7 @@ import {import { CoworkWorkspacePill } from '@/containers/CoworkWorkspacePill'import { CoworkPlanToggle } from '@/containers/CoworkPlanToggle'import { CoworkEmptyState } from '@/containers/CoworkEmptyState'+import { CoworkSessionNotice } from '@/containers/CoworkSessionNotice'import { usePrompt } from '@/hooks/usePrompt'import { useChatAttachments } from '@/hooks/useChatAttachments'import {@@ -1667,6 +1668,7 @@ export function CoworkPage() {<div className="flex flex-1 h-full overflow-hidden"><div className="flex min-w-0 flex-1 flex-col h-full overflow-hidden">+ <CoworkSessionNotice session={session} /><div className="flex-1 relative">{displayedTurns.length === 0 ? (<CoworkEmptyStatediff --git a/web-app/src/containers/CoworkSessionNotice.tsx b/web-app/src/containers/CoworkSessionNotice.tsxnew file mode 100644index 000000000..48cc3e9cb--- /dev/null+++ b/web-app/src/containers/CoworkSessionNotice.tsx@@ -0,0 +1,192 @@+import { useEffect, useState } from 'react'+import { AlertTriangle, Info, X } from 'lucide-react'+import { toast } from 'sonner'+import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'+import { Button } from '@/components/ui/button'+import { useTranslation } from '@/i18n/react-i18next-compat'+import type { CoworkSession } from '@/hooks/useCoworkSessions'+import { useThreads } from '@/hooks/useThreads'+import { getServiceHub } from '@/hooks/useServiceHub'+import { backendStorage } from '@/lib/backendStorage'+import { exportCoworkSession } from '@/lib/coworkExport'+import { retryCoworkImport } from '@/lib/coworkSync'++/** Ids whose "files left out" notice the user closed (JSON array). */+export const COWORK_LEFT_OUT_DISMISSED_KEY = 'cowork_left_out_dismissed'++type LeftOut = { skipped: number; unreadable: number }++const readDismissed = async (): Promise<string[]> => {+ try {+ const raw = await backendStorage.getItem(COWORK_LEFT_OUT_DISMISSED_KEY)+ const parsed: unknown = raw ? JSON.parse(raw as string) : []+ return Array.isArray(parsed)+ ? parsed.filter((x) => typeof x === 'string')+ : []+ } catch {+ return []+ }+}++const revealSessionFolder = async (id: string) => {+ const hub = getServiceHub()+ const dataFolder = await hub.app().getJanDataFolder()+ if (!dataFolder) throw new Error('no data folder')+ const folder = await sessionWorkspacePath(dataFolder, id)+ await hub.opener().revealItemInDir(folder)+}++/**+ * The banner above a Cowork conversation that cannot be used as usual, or+ * that the migration could not copy completely. Each case says what happened+ * in words, and what the user can do about it.+ */+export function CoworkSessionNotice({+ session,+}: {+ session: CoworkSession | null | undefined+}) {+ const { t } = useTranslation()+ const leftOut = useThreads(+ (s) =>+ (session &&+ (+ s.threads[session.id]?.metadata?.migratedFrom as+ | { leftOut?: LeftOut }+ | undefined+ )?.leftOut) ||+ undefined+ )+ const [dismissed, setDismissed] = useState<string[] | null>(null)+ const [busy, setBusy] = useState(false)++ useEffect(() => {+ if (!leftOut) return+ let live = true+ void readDismissed().then((ids) => live && setDismissed(ids))+ return () => {+ live = false+ }+ }, [leftOut])++ if (!session) return null++ const exportIt = async () => {+ try {+ const path = await exportCoworkSession(session)+ toast.success(t('common:coworkNotice.exported'), { description: path })+ await getServiceHub().opener().revealItemInDir(path)+ } catch (e) {+ toast.error(t('common:coworkNotice.exportFailed'), {+ description: String(e),+ })+ }+ }++ const retry = async () => {+ setBusy(true)+ try {+ const r = await retryCoworkImport(session.id)+ if (r.imported) toast.success(t('common:coworkNotice.imported'))+ else+ toast.error(t('common:coworkNotice.retryFailed'), {+ description: r.error,+ })+ } catch (e) {+ toast.error(t('common:coworkNotice.retryFailed'), {+ description: String(e),+ })+ } finally {+ setBusy(false)+ }+ }++ if (session.unavailable) {+ const reason = session.unavailable+ return (+ <div+ role="alert"+ data-testid="cowork-session-notice"+ className="mx-auto mt-3 flex w-full max-w-3xl gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm"+ >+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600" />+ <div className="min-w-0 flex-1 space-y-2">+ <p className="font-medium">+ {t(`common:coworkNotice.${reason}.title`)}+ </p>+ <p className="text-muted-foreground">+ {t(`common:coworkNotice.${reason}.body`)}+ </p>+ {reason === 'not-imported' && session.importError && (+ <p className="break-words font-mono text-xs text-muted-foreground">+ {t('common:coworkNotice.reason', { reason: session.importError })}+ </p>+ )}+ <div className="flex flex-wrap gap-2">+ {reason === 'not-imported' && (+ <Button size="sm" disabled={busy} onClick={() => void retry()}>+ {t(+ busy+ ? 'common:coworkNotice.retrying'+ : 'common:coworkNotice.retry'+ )}+ </Button>+ )}+ <Button size="sm" variant="outline" onClick={() => void exportIt()}>+ {t('common:coworkNotice.export')}+ </Button>+ </div>+ </div>+ </div>+ )+ }++ if (!leftOut || dismissed === null || dismissed.includes(session.id))+ return null+ const dismiss = () => {+ const next = [...dismissed, session.id]+ setDismissed(next)+ void backendStorage.setItem(+ COWORK_LEFT_OUT_DISMISSED_KEY,+ JSON.stringify(next)+ )+ }+ return (+ <div+ role="status"+ data-testid="cowork-left-out-notice"+ className="mx-auto mt-3 flex w-full max-w-3xl gap-3 rounded-lg border bg-muted/50 px-4 py-3 text-sm"+ >+ <Info className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1 space-y-2">+ <p className="font-medium">{t('common:coworkNotice.leftOut.title')}</p>+ <p className="text-muted-foreground">+ {t('common:coworkNotice.leftOut.body', {+ count: leftOut.skipped + leftOut.unreadable,+ })}+ </p>+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ void revealSessionFolder(session.id).catch((e) =>+ toast.error(t('common:coworkNotice.revealFailed'), {+ description: String(e),+ })+ )+ }+ >+ {t('common:coworkNotice.leftOut.show')}+ </Button>+ </div>+ <button+ type="button"+ aria-label={t('common:close')}+ onClick={dismiss}+ className="self-start rounded p-1 text-muted-foreground hover:bg-muted"+ >+ <X className="size-4" />+ </button>+ </div>+ )+}diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.tsindex 093ec60fd..7c4af3da8 100644--- a/web-app/src/hooks/useCoworkSessions.ts+++ b/web-app/src/hooks/useCoworkSessions.ts@@ -79,6 +79,9 @@ export type CoworkSession = {| 'unreadable-sidecar'| 'id-collision'| 'missing-thread'+ | 'not-imported'+ /** Why the migration gave up on a `not-imported` session (its last error). */+ importError?: stringupdated: number}diff --git a/web-app/src/lib/__tests__/coworkPersistenceMirror.test.ts b/web-app/src/lib/__tests__/coworkPersistenceMirror.test.tsindex 3b8a66d2e..8749b67fe 100644--- a/web-app/src/lib/__tests__/coworkPersistenceMirror.test.ts+++ b/web-app/src/lib/__tests__/coworkPersistenceMirror.test.ts@@ -297,7 +297,7 @@ describe('legacy sessions and the deletion journal', () => {expect(r.sessions.map((s) => s.id)).toEqual(['m-here'])})- it('an abandoned legacy session stays visible but read-only (never written)', async () => {+ it('an abandoned legacy session stays visible, read-only, and says why it was not imported', async () => {b.settings.set(CODE_SESSIONS_KEY,JSON.stringify({ state: { sessions: [session('bad')] }, version: 1 })@@ -308,13 +308,29 @@ describe('legacy sessions and the deletion journal', () => {)// Even a settled migration shows it: nothing disappears silently.const r = await loadCoworkSessions(b.invoke, { migrationSettled: true })- expect(r.sessions.map((s) => [s.id, s.unavailable])).toEqual([['bad', 'id-collision']])+ expect(r.sessions.map((s) => [s.id, s.unavailable, s.importError])).toEqual([+ ['bad', 'not-imported', 'PERMANENT: nope'],+ ])const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })p.schedule(r.sessions[0])await p.flush()expect(b.extras.has('bad')).toBe(false)})+ it('an abandoned session whose id a chat owns is a collision, not a failed import', async () => {+ b.threads.set('dup', { id: 'dup', title: 'A chat', metadata: {} })+ b.settings.set(+ CODE_SESSIONS_KEY,+ JSON.stringify({ state: { sessions: [session('dup')] }, version: 1 })+ )+ b.settings.set(+ COWORK_MIGRATION_ABANDONED_KEY,+ JSON.stringify([{ id: 'dup', error: 'a different conversation already uses this id' }])+ )+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: true })+ expect(r.sessions.map((s) => [s.id, s.unavailable])).toEqual([['dup', 'id-collision']])+ })+it('a PERMANENT write refusal stops retries and reports the session once', async () => {const onWriteRefused = vi.fn()const refusing = async (cmd: string, args: any) => {diff --git a/web-app/src/lib/__tests__/coworkSync.test.ts b/web-app/src/lib/__tests__/coworkSync.test.tsindex 322a97b1d..93b5095d9 100644--- a/web-app/src/lib/__tests__/coworkSync.test.ts+++ b/web-app/src/lib/__tests__/coworkSync.test.ts@@ -138,6 +138,7 @@ import {startCoworkSync,flushCoworkDeletes,flushCoworkStartupWarnings,+ retryCoworkImport,COWORK_MIGRATION_BUDGET_MS,COWORK_CLOSE_FAILURES_BEFORE_FORCE,__resetCoworkSyncForTests,@@ -359,6 +360,51 @@ describe('coworkSync', () => {})})+ describe('a session the migration gave up on', () => {+ it('shows as not imported with the reason, and Try again imports it once the cause is gone', async () => {+ putBlob(legacy('a'), legacy('b'))+ agentTools.copySessionWorkspaceToThread.mockRejectedValueOnce(+ new Error('PERMANENT: a already holds files of its own')+ )+ await startCoworkSync()+ const stuck = useCoworkSessions+ .getState()+ .sessions.find((s) => s.id === 'a')!+ expect([stuck.unavailable, stuck.importError]).toEqual([+ 'not-imported',+ 'PERMANENT: a already holds files of its own',+ ])+ expect(backend.threads.has('a')).toBe(false)++ await expect(retryCoworkImport('a')).resolves.toEqual({ imported: true })+ const fixed = useCoworkSessions+ .getState()+ .sessions.find((s) => s.id === 'a')!+ expect(fixed.unavailable).toBeUndefined()+ expect(backend.threads.get('a')!.metadata.mode).toBe('cowork')+ expect(useThreads.getState().threads['a']).toBeTruthy()+ expect(backend.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')+ })++ it('a retry that fails again keeps the session read-only and reports the new reason', async () => {+ putBlob(legacy('a'))+ agentTools.copySessionWorkspaceToThread+ .mockRejectedValueOnce(new Error('PERMANENT: first'))+ .mockRejectedValueOnce(new Error('PERMANENT: second'))+ await startCoworkSync()+ await expect(retryCoworkImport('a')).resolves.toEqual({+ imported: false,+ error: 'PERMANENT: second',+ })+ const s = useCoworkSessions.getState().sessions[0]+ expect([s.unavailable, s.importError]).toEqual([+ 'not-imported',+ 'PERMANENT: second',+ ])+ expect(backend.threads.has('a')).toBe(false)+ })+ })+describe('deletion', () => {it('deleting a session removes its thread and sandbox, and the thread list row', async () => {await startCoworkSync()diff --git a/web-app/src/lib/coworkExport.ts b/web-app/src/lib/coworkExport.tsnew file mode 100644index 000000000..99ef1ed2c--- /dev/null+++ b/web-app/src/lib/coworkExport.ts@@ -0,0 +1,47 @@+import type { CoworkSession } from '@/hooks/useCoworkSessions'+import { getServiceHub } from '@/hooks/useServiceHub'+import type { Invoke } from '@/lib/migrateCoworkSessions'++/** Data-folder-relative directory exports land in. */+export const COWORK_EXPORT_DIR = 'cowork-exports'++/**+ * Save one Cowork session, exactly as the app holds it, to+ * `<data>/cowork-exports/<id>.json` and return the absolute path. Meant for a+ * session that cannot be opened normally (not imported, unreadable data): the+ * file keeps the transcript readable outside Jan and can be attached to a bug+ * report. The file commands only write inside the data folder, so the export+ * goes there and is then shown in the file manager.+ */+export async function exportCoworkSession(+ session: CoworkSession,+ invoke: Invoke = (cmd, args) => getServiceHub().core().invoke(cmd, args)+): Promise<string> {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) throw new Error('no data folder')+ // An abandoned session's id may be one the backend refused (that can be the+ // reason it was abandoned): never let it shape the path.+ const safe =+ session.id.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 100) || 'session'+ // Windows reserves device names even with an extension (con.json).+ const name = /^(con|prn|aux|nul|com\d|lpt\d)$/i.test(safe) ? `_${safe}` : safe+ const relative = `${COWORK_EXPORT_DIR}/${name}.json`+ await invoke('mkdir', { args: [COWORK_EXPORT_DIR] })+ const body = JSON.stringify(+ {+ exportedFrom: 'jan-cowork',+ exportedAt: new Date().toISOString(),+ session,+ },+ null,+ 2+ )+ await invoke('write_file_sync', { args: [relative, body] })+ return joinDataPath(dataFolder, relative)+}++function joinDataPath(dataFolder: string, relative: string): string {+ const sep =+ dataFolder.includes('\\') && !dataFolder.includes('/') ? '\\' : '/'+ return `${dataFolder.replace(/[\\/]+$/, '')}${sep}${relative.split('/').join(sep)}`+}diff --git a/web-app/src/lib/coworkPersistence.ts b/web-app/src/lib/coworkPersistence.tsindex 40a5a18e3..1064d7f41 100644--- a/web-app/src/lib/coworkPersistence.ts+++ b/web-app/src/lib/coworkPersistence.ts@@ -241,14 +241,16 @@ export async function loadCoworkSessions(// leaves blob sessions to show. The blob itself can be huge, so it is only// read when it matters.let abandonedIds = new Set<string>()+ const abandonedErrors = new Map<string, string>()try {- abandonedIds = new Set(- readAbandoned(- await invoke<string | null>('settings_get', {- key: COWORK_MIGRATION_ABANDONED_KEY,- })- ).map((a) => a.id)- )+ for (const a of readAbandoned(+ await invoke<string | null>('settings_get', {+ key: COWORK_MIGRATION_ABANDONED_KEY,+ })+ )) {+ abandonedErrors.set(a.id, a.error)+ }+ abandonedIds = new Set(abandonedErrors.keys())} catch (e) {console.warn('[cowork] could not read the abandoned list:', e)}@@ -350,8 +352,17 @@ export async function loadCoworkSessions(if (deleted) {for (const s of mergeable) {if (deleted.has(s.id)) continue- if (chatIds.has(s.id) || abandonedIds.has(s.id)) {+ if (chatIds.has(s.id)) {sessions.push({ ...s, unavailable: 'id-collision' })+ } else if (abandonedIds.has(s.id)) {+ // No other conversation owns the id: the migration gave up on it+ // (a refused copy, too many failed launches). Say why, and let the+ // user export it or try again.+ sessions.push({+ ...s,+ unavailable: 'not-imported',+ importError: abandonedErrors.get(s.id),+ })} else {sessions.push(s)legacyIds.add(s.id)diff --git a/web-app/src/lib/coworkSync.ts b/web-app/src/lib/coworkSync.tsindex 497478e6f..a60ee6b55 100644--- a/web-app/src/lib/coworkSync.ts+++ b/web-app/src/lib/coworkSync.ts@@ -27,8 +27,12 @@ import {type ThreadRecord,} from '@/lib/coworkPersistence'import {+ COWORK_MIGRATION_ABANDONED_KEY,+ COWORK_MIGRATION_ATTEMPTS_KEY,+ COWORK_MIGRATION_FLAG_KEY,isCoworkMigrationSettled,migrateCoworkSessionsOnStartup,+ readAbandoned,readDeletedIds,type CoworkMigrationResult,type Invoke,@@ -303,20 +307,25 @@ async function doStart() {}for (const id of removed) {const snapshot = prev.sessions.find((session) => session.id === id)- const collision = snapshot?.unavailable === 'id-collision'+ // Neither placeholder owns what sits under its id: a collision shares+ // it with an unrelated chat, and a session the migration gave up on may+ // have been refused because threads/<id> holds files of its own.+ const placeholder =+ snapshot?.unavailable === 'id-collision' ||+ snapshot?.unavailable === 'not-imported'const removal = (async () => {await p.remove(id, {// While the legacy blob can still be read, deletion intent must// survive in the journal or the blob brings the session back. An- // abandoned legacy session (shown as id-collision) stays in the- // blob forever, so it is journaled even after the migration settled.- recordDeleted: !migrationSettled || collision,- // A collision shares its id with an unrelated chat: never delete it.- preserveThread: collision,+ // abandoned legacy session stays in the blob forever, so it is+ // journaled even after the migration settled.+ recordDeleted: !migrationSettled || placeholder,+ // Never delete a thread or workspace a placeholder does not own.+ preserveThread: placeholder,})// Workspace reclamation cannot turn a successful durable deletion back// into a visible session. It is best-effort and retried by the sweep.- if (!collision) await cleanupThreadWorkspace(id)+ if (!placeholder) await cleanupThreadWorkspace(id)})()pendingDeletes.add(removal)void removal@@ -428,6 +437,77 @@ async function finishLateMigration(}}+export type CoworkImportRetry =+ | { imported: true }+ | { imported: false; error: string }++/**+ * Try again to import one session the migration gave up on (`not-imported`).+ * Its abandoned entry and attempt count are cleared and the migration runs+ * again; it skips everything already migrated, so only this session (and any+ * other still-pending one) is copied. On success the placeholder is replaced by+ * the imported thread; on failure it stays, with the new error.+ */+export async function retryCoworkImport(+ id: string+): Promise<CoworkImportRetry> {+ await startCoworkSync()+ const invoke = getInvoke()+ const abandoned = readAbandoned(+ await invoke<string | null>('settings_get', {+ key: COWORK_MIGRATION_ABANDONED_KEY,+ })+ ).filter((a) => a.id !== id)+ await invoke('settings_set', {+ key: COWORK_MIGRATION_ABANDONED_KEY,+ value: JSON.stringify(abandoned),+ })+ const rawAttempts = await invoke<string | null>('settings_get', {+ key: COWORK_MIGRATION_ATTEMPTS_KEY,+ })+ if (rawAttempts) {+ try {+ const attempts = JSON.parse(rawAttempts) as Record<string, number>+ delete attempts[id]+ await invoke('settings_set', {+ key: COWORK_MIGRATION_ATTEMPTS_KEY,+ value: JSON.stringify(attempts),+ })+ } catch {+ // An unreadable count only means this session starts again from 0.+ }+ }+ // Until this run settles the legacy blob is live again: deletions journal.+ migrationSettled = false+ await invoke('settings_remove', { key: COWORK_MIGRATION_FLAG_KEY })+ const result = await migrateCoworkSessionsOnStartup()+ migrationSettled = await settledAfter(invoke, result)++ if (result?.migrated.includes(id)) {+ const loaded = await loadCoworkSessions(invoke, { migrationSettled })+ const thread = loaded.threads.find((t) => t.id === id)+ const session = loaded.sessions.find((s) => s.id === id)+ if (thread && session) {+ persistence?.adopt([thread])+ useCoworkSessions.setState((s) => ({+ sessions: s.sessions.map((x) => (x.id === id ? session : x)),+ }))+ upsertThread(thread)+ return { imported: true }+ }+ }+ const error =+ result?.abandoned.find((a) => a.id === id)?.error ??+ result?.failed.find((f) => f.id === id || f.id === '*')?.error ??+ 'unknown error'+ useCoworkSessions.setState((s) => ({+ sessions: s.sessions.map((x) =>+ x.id === id ? { ...x, importError: error } : x+ ),+ }))+ return { imported: false, error }+}+/*** 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 pathdiff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 4e11f063c..7a0be936a 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -902,5 +902,42 @@"artifactsLibraryCount_one": "{{count}} file","artifactsLibraryCount_other": "{{count}} files","artifactsLibraryFilter": "Filter by file type",- "artifactsLibraryReset": "Clear filters"+ "artifactsLibraryReset": "Clear filters",+ "coworkNotice": {+ "not-imported": {+ "title": "This task could not be imported",+ "body": "Jan could not move this task over from the previous version and stopped trying. Nothing was lost: the original is still kept. You can try again, or export it to a file."+ },+ "id-collision": {+ "title": "This task could not be imported",+ "body": "Another conversation already uses the same id, so this task is shown read-only and the other conversation is left untouched. Export it to keep a copy."+ },+ "missing-sidecar": {+ "title": "This task's history is missing",+ "body": "The saved history of this task could not be found, so it is shown read-only. Its files on disk are kept as they are."+ },+ "unreadable-sidecar": {+ "title": "This task's history cannot be read",+ "body": "The saved history of this task is damaged or from a newer version of Jan, so it is shown read-only and never overwritten."+ },+ "missing-thread": {+ "title": "This task was removed from storage",+ "body": "This task's conversation is no longer on disk. What is shown is the copy still in memory; export it to keep it."+ },+ "reason": "Reason: {{reason}}",+ "retry": "Try again",+ "retrying": "Trying...",+ "export": "Export",+ "exported": "Task exported",+ "exportFailed": "Could not export the task",+ "imported": "Task imported",+ "retryFailed": "The task still could not be imported",+ "revealFailed": "Could not open the folder",+ "leftOut": {+ "title": "Some files were not copied",+ "body_one": "{{count}} item from this task's old folder (a link, or a file Jan was not allowed to read) was not copied. The original folder is kept as it was.",+ "body_other": "{{count}} items from this task's old folder (links, or files Jan was not allowed to read) were not copied. The original folder is kept as it was.",+ "show": "Show original folder"+ }+ }}