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.

feat(web-app): honor a Cowork deletion journal and anchor mirrored message stamps

Akarshan Biswas7794890447d6
diff --git a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
index 5b0411706..00717b7ec 100644
--- a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
+++ b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
@@ -7,6 +7,9 @@ import {
COWORK_MIGRATED_IDS_KEY,
COWORK_MIGRATION_ATTEMPTS_KEY,
COWORK_MAX_ATTEMPTS,
+ COWORK_DELETED_IDS_KEY,
+ readDeletedIds,
+ isCoworkMigrationSettled,
sameJson,
type Invoke,
} from '../migrateCoworkSessions'
@@ -745,3 +748,65 @@ describe('read-back cost', () => {
}
})
})
+
+describe('deletion journal (cowork_deleted_ids)', () => {
+ let b: ReturnType<typeof makeBackend>
+ beforeEach(() => {
+ b = makeBackend()
+ })
+
+ it('readDeletedIds: absent is empty, a valid array is read, anything else throws', async () => {
+ expect([...(await readDeletedIds(b.invoke))]).toEqual([])
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['a', 'b']))
+ expect([...(await readDeletedIds(b.invoke))]).toEqual(['a', 'b'])
+ for (const bad of ['', '{x', '{"a":1}', JSON.stringify([1])]) {
+ b.settings.set(COWORK_DELETED_IDS_KEY, bad)
+ await expect(readDeletedIds(b.invoke)).rejects.toThrow()
+ }
+ })
+
+ it('skips a session the user deleted while the blob was live, and still settles', async () => {
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('gone'), session('keep')]))
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['gone']))
+ const r = await migrateCoworkSessionsToThreads(b.invoke)
+ expect(r.status).toBe('complete')
+ expect(r.migrated).toEqual(['keep'])
+ expect(r.skipped).toContain('gone')
+ expect(b.threads.has('gone')).toBe(false)
+ expect(b.extras.has('gone/cowork')).toBe(false)
+ })
+
+ it('a deletion that lands mid-run (after the run started) is honored for the sessions not yet copied', async () => {
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('first'), session('second')]))
+ const inner = b.invoke
+ const racing: typeof b.invoke = async (cmd, args) => {
+ const out = await inner(cmd, args)
+ // The user deletes `second` while `first` is being copied.
+ if (cmd === 'create_thread') {
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['second']))
+ }
+ return out
+ }
+ const r = await migrateCoworkSessionsToThreads(racing)
+ expect(r.migrated).toEqual(['first'])
+ expect(b.threads.has('second')).toBe(false)
+ })
+
+ it('an unreadable journal fails the run closed: nothing copied, marker unset, attempts not burned, bytes untouched', async () => {
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('a')]))
+ b.settings.set(COWORK_DELETED_IDS_KEY, '{corrupt')
+ const r = await migrateCoworkSessionsToThreads(b.invoke)
+ expect(r.status).toBe('partial')
+ expect(b.threads.size).toBe(0)
+ expect(b.extras.size).toBe(0)
+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)
+ expect(b.settings.has(COWORK_MIGRATION_ATTEMPTS_KEY)).toBe(false)
+ expect(b.settings.get(COWORK_DELETED_IDS_KEY)).toBe('{corrupt')
+ })
+
+ it('isCoworkMigrationSettled follows the completion marker', async () => {
+ expect(await isCoworkMigrationSettled(b.invoke)).toBe(false)
+ b.settings.set(COWORK_MIGRATION_FLAG_KEY, 'true')
+ expect(await isCoworkMigrationSettled(b.invoke)).toBe(true)
+ })
+})
diff --git a/web-app/src/lib/coworkThreadMessages.ts b/web-app/src/lib/coworkThreadMessages.ts
index f4587b024..a2bd41ae7 100644
--- a/web-app/src/lib/coworkThreadMessages.ts
+++ b/web-app/src/lib/coworkThreadMessages.ts
@@ -188,8 +188,39 @@ function convertMessage(
return { content, toolErrors }
}
+export type ThreadMessagesOptions = {
+ /**
+ * Anchor for `created_at`, in ms: message `i` is stamped `anchorMs + i`.
+ * Without it the stamps end at `session.updated`, which is right for a
+ * one-shot conversion but moves EVERY message each time the session is
+ * updated. A live session that is re-converted on each turn passes its
+ * thread's immutable `created` here, so the stamps of the messages already
+ * written never change when one is appended and the replayed prompt prefix
+ * stays byte-identical.
+ */
+ anchorMs?: number
+}
+
+/**
+ * The anchor a one-shot conversion of `session` uses (see `anchorMs`). The
+ * migration stamped its messages with it, so a live session that adopts a
+ * migrated thread keeps those exact stamps by reusing it. `updatedOverrideMs`
+ * is the exact `updated` the migration saw (its record keeps it in
+ * `metadata.migratedFrom.updated`; the thread's own `updated` is only seconds).
+ */
+export function defaultAnchorMs(
+ session: CoworkSession,
+ updatedOverrideMs?: number
+): number {
+ const length = session.messages?.length
+ ? session.messages.length
+ : coworkTurnsToUIMessages(session.turns ?? [], session.id).length
+ return updatedMs(updatedOverrideMs ?? session.updated) - (length - 1)
+}
+
export function coworkSessionToThreadMessages(
- session: CoworkSession
+ session: CoworkSession,
+ options: ThreadMessagesOptions = {}
): ThreadMessage[] {
const source: SourceMessage[] = (
session.messages?.length
@@ -199,7 +230,10 @@ export function coworkSessionToThreadMessages(
// Strictly increasing and ending at the last update, so the order survives
// the sort-by-created_at main chat applies when it merges stored messages.
- const base = updatedMs(session.updated) - (source.length - 1)
+ const base =
+ options.anchorMs !== undefined && Number.isFinite(options.anchorMs)
+ ? options.anchorMs
+ : updatedMs(session.updated) - (source.length - 1)
const usedCallIds = new Set<string>()
const out: ThreadMessage[] = []
diff --git a/web-app/src/lib/migrateCoworkSessions.ts b/web-app/src/lib/migrateCoworkSessions.ts
index a541f7cbb..b48ae32d9 100644
--- a/web-app/src/lib/migrateCoworkSessions.ts
+++ b/web-app/src/lib/migrateCoworkSessions.ts
@@ -60,6 +60,14 @@ export const COWORK_SIDECAR = 'cowork'
export const COWORK_MIGRATION_ABANDONED_KEY =
'cowork_threads_migration_abandoned_v1'
+/**
+ * Ids the user deleted from the Cowork UI while the legacy `code-sessions`
+ * blob was still being read (JSON array of strings). The blob is never edited
+ * (it is the rollback source), so without this journal a deleted session that
+ * only exists in the blob would come back on the next launch.
+ */
+export const COWORK_DELETED_IDS_KEY = 'cowork_deleted_ids'
+
/** Ids whose thread this migration has committed (JSON array of strings). */
export const COWORK_MIGRATED_IDS_KEY = 'cowork_threads_migrated_ids_v1'
/** Launches in which a session failed transiently: JSON `{ [id]: count }`. */
@@ -97,6 +105,13 @@ export type CoworkMigrationResult = {
failed: { id: string; error: string }[]
}
+/** The deletion journal could not be read; see `readDeletedIds`. */
+class JournalUnreadableError extends Error {
+ constructor(cause: unknown) {
+ super(`deletion journal unreadable: ${toErrorMessage(cause)}`)
+ }
+}
+
/** A failure retrying cannot fix. */
class PermanentMigrationError extends Error {}
@@ -166,7 +181,40 @@ function toErrorMessage(e: unknown): string {
return String(e)
}
-function readAbandoned(raw: string | null): { id: string; error: string }[] {
+/**
+ * Read the deletion journal STRICTLY. Only an absent key is an empty journal;
+ * an empty string or a non-array is damage, and reading it as empty could
+ * resurrect deleted sessions, so it throws. Every caller fails closed: the
+ * migration stays `partial` and the load path skips the legacy-blob merge.
+ * Writers must never replace an unreadable journal with a fresh empty set.
+ */
+export async function readDeletedIds(invoke: Invoke): Promise<Set<string>> {
+ const raw = await invoke<string | null>('settings_get', {
+ key: COWORK_DELETED_IDS_KEY,
+ })
+ const parsed: unknown = raw == null ? [] : JSON.parse(raw)
+ if (!Array.isArray(parsed) || !parsed.every((id) => typeof id === 'string')) {
+ throw new Error(
+ 'Invalid Cowork deletion journal: expected an array of strings'
+ )
+ }
+ return new Set(parsed)
+}
+
+/**
+ * Whether the legacy blob may stop being read: the migration finished (every
+ * session migrated or abandoned), or there never was anything to migrate.
+ */
+export async function isCoworkMigrationSettled(
+ invoke: Invoke
+): Promise<boolean> {
+ const flag = await invoke<string | null>('settings_get', {
+ key: COWORK_MIGRATION_FLAG_KEY,
+ })
+ return flag === 'true'
+}
+
+export function readAbandoned(raw: string | null): { id: string; error: string }[] {
if (!raw) return []
try {
const parsed: unknown = JSON.parse(raw)
@@ -181,7 +229,7 @@ function readAbandoned(raw: string | null): { id: string; error: string }[] {
}
}
-function readIds(raw: string | null): string[] {
+export function readIds(raw: string | null): string[] {
if (!raw) return []
try {
const parsed: unknown = JSON.parse(raw)
@@ -360,6 +408,20 @@ export async function migrateCoworkSessionsToThreads(
`session id ${JSON.stringify(session.id)} is not a valid thread id`
)
}
+ // Deleted in the Cowork UI while this blob was still live. Re-read per
+ // session, not once: the migration can run in the background while the
+ // user deletes, and a copy must not bring a deleted session back. An
+ // unreadable journal throws here and fails the run closed (partial).
+ let deleted: Set<string>
+ try {
+ deleted = await readDeletedIds(invoke)
+ } catch (e) {
+ throw new JournalUnreadableError(e)
+ }
+ if (deleted.has(session.id)) {
+ result.skipped.push(session.id)
+ continue
+ }
const committed = existing.get(session.id)
if (committed) {
// A cowork thread with this id is already ours (copied by an earlier
@@ -431,6 +493,9 @@ export async function migrateCoworkSessionsToThreads(
attemptsChanged = true
}
} catch (e) {
+ // Not this session's fault and not countable against it: fail the whole
+ // run closed (outer catch -> partial) without burning its attempts.
+ if (e instanceof JournalUnreadableError) throw e
const entry = { id: String(session.id), error: toErrorMessage(e) }
if (e instanceof PermanentMigrationError || isPermanentBackendError(e)) {
result.abandoned.push(entry)