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): convert a Cowork transcript into main chat's thread messages

Akarshan Biswasdb71a86a8ee4
diff --git a/web-app/src/lib/__tests__/coworkThreadMessages.test.ts b/web-app/src/lib/__tests__/coworkThreadMessages.test.ts
new file mode 100644
index 000000000..994942f83
--- /dev/null
+++ b/web-app/src/lib/__tests__/coworkThreadMessages.test.ts
@@ -0,0 +1,237 @@
+import { describe, it, expect } from 'vitest'
+import { ContentType, MessageStatus } from '@janhq/core'
+import type { ThreadMessage } from '@janhq/core'
+import type { CoworkSession } from '@/hooks/useCoworkSessions'
+import { convertThreadMessageToUIMessage } from '@/lib/messages'
+import { STOPPED_TOOL_ERROR } from '@/lib/stopped-tool-calls'
+import { coworkSessionToThreadMessages } from '../coworkThreadMessages'
+
+const UPDATED_MS = 1_700_000_000_000
+
+type Part = Record<string, unknown>
+const msg = (id: string, role: string, parts: Part[]) => ({ id, role, parts })
+
+const session = (
+ messages: unknown[],
+ extra: Partial<CoworkSession> = {}
+): CoworkSession =>
+ ({
+ id: 'sess-1',
+ title: 'T',
+ folder: null,
+ turns: [{ role: 'user', content: 'x' }],
+ messages,
+ updated: UPDATED_MS,
+ ...extra,
+ }) as unknown as CoworkSession
+
+const toolPart = (name: string, id: string, extra: Part = {}): Part => ({
+ type: `tool-${name}`,
+ toolCallId: id,
+ input: { path: 'a.txt' },
+ ...extra,
+})
+
+// A representative conversation: text, reasoning, a finished call, a failed
+// call, an unfinished call and an image.
+const conversation = () =>
+ session([
+ msg('u-1', 'user', [
+ { type: 'text', text: 'read a.txt' },
+ { type: 'file', mediaType: 'image/png', url: 'data:image/png;base64,AAAA' },
+ ]),
+ msg('a-1', 'assistant', [
+ { type: 'reasoning', text: 'I should read it' },
+ { type: 'text', text: 'Reading.' },
+ toolPart('read', 'call-ok', { state: 'output-available', output: 'hello' }),
+ toolPart('read', 'call-bad', {
+ state: 'output-error',
+ errorText: 'ENOENT',
+ }),
+ toolPart('shell', 'call-hung', { state: 'input-available' }),
+ ]),
+ msg('u-2', 'user', [{ type: 'text', text: 'thanks' }]),
+ ])
+
+const toolContents = (m: ThreadMessage) =>
+ m.content.filter((c) => c.type === ContentType.ToolCall)
+
+describe('coworkSessionToThreadMessages', () => {
+ it('derives ids from the session id and index, never from the clock', () => {
+ const out = coworkSessionToThreadMessages(conversation())
+ expect(out.map((m) => m.id)).toEqual([
+ 'sess-1-msg-0',
+ 'sess-1-msg-1',
+ 'sess-1-msg-2',
+ ])
+ expect(out.every((m) => m.thread_id === 'sess-1')).toBe(true)
+ })
+
+ it('stamps timestamps from the session, ending at its last update', () => {
+ const out = coworkSessionToThreadMessages(conversation())
+ expect(out.map((m) => m.created_at)).toEqual([
+ UPDATED_MS - 2,
+ UPDATED_MS - 1,
+ UPDATED_MS,
+ ])
+ expect(out.every((m) => m.completed_at === m.created_at)).toBe(true)
+ })
+
+ it('accepts a session updated in seconds', () => {
+ const out = coworkSessionToThreadMessages(
+ session(conversation().messages, { updated: 1_700_000_000 })
+ )
+ expect(out.at(-1)?.created_at).toBe(UPDATED_MS)
+ })
+
+ it('is a pure function of the session: same input, same deep value and bytes', () => {
+ const s = conversation()
+ const before = JSON.stringify(s)
+ const a = coworkSessionToThreadMessages(s)
+ const b = coworkSessionToThreadMessages(JSON.parse(before))
+ expect(b).toEqual(a)
+ expect(JSON.stringify(b)).toBe(JSON.stringify(a))
+ // The session is not mutated by converting it.
+ expect(JSON.stringify(s)).toBe(before)
+ })
+
+ it('writes the shape main chat persists for each part', () => {
+ const [user, assistant] = coworkSessionToThreadMessages(conversation())
+ expect(user).toMatchObject({
+ object: 'thread.message',
+ type: 'text',
+ role: 'user',
+ status: MessageStatus.Ready,
+ })
+ expect(user.content).toEqual([
+ { type: 'text', text: { value: 'read a.txt', annotations: [] } },
+ {
+ type: 'image_url',
+ image_url: { url: 'data:image/png;base64,AAAA', detail: 'auto' },
+ },
+ ])
+ // Reasoning is its own content item, not <think> inside the text.
+ expect(assistant.content.slice(0, 2)).toEqual([
+ {
+ type: 'reasoning',
+ text: { value: 'I should read it', annotations: [] },
+ },
+ { type: 'text', text: { value: 'Reading.', annotations: [] } },
+ ])
+ expect(JSON.stringify(assistant.content)).not.toContain('<think>')
+ })
+
+ it('keeps tool call ids and pairs every call with a result or an error', () => {
+ const assistant = coworkSessionToThreadMessages(conversation())[1]
+ const calls = toolContents(assistant)
+ expect(calls.map((c) => c.tool_call_id)).toEqual([
+ 'call-ok',
+ 'call-bad',
+ 'call-hung',
+ ])
+ expect(calls[0]).toMatchObject({ tool_name: 'read', output: 'hello' })
+ expect(assistant.metadata).toEqual({
+ toolErrors: { 'call-bad': 'ENOENT', 'call-hung': STOPPED_TOOL_ERROR },
+ })
+
+ // Through main's loader: no call is left "running".
+ const ui = convertThreadMessageToUIMessage(assistant)
+ const tools = ui.parts.filter((p) => p.type.startsWith('tool-')) as Array<{
+ state: string
+ toolCallId: string
+ }>
+ expect(tools.map((t) => [t.toolCallId, t.state])).toEqual([
+ ['call-ok', 'output-available'],
+ ['call-bad', 'output-error'],
+ ['call-hung', 'output-error'],
+ ])
+ })
+
+ it('keeps an empty tool output as a result, not as a call still running', () => {
+ const [m] = coworkSessionToThreadMessages(
+ session([
+ msg('a', 'assistant', [
+ toolPart('shell', 'c1', { state: 'output-available', output: '' }),
+ ]),
+ ])
+ )
+ const part = convertThreadMessageToUIMessage(m).parts[0] as {
+ state: string
+ }
+ expect(part.state).toBe('output-available')
+ })
+
+ it('gives an error with no text a non-empty one so it reloads as an error', () => {
+ const [m] = coworkSessionToThreadMessages(
+ session([
+ msg('a', 'assistant', [
+ toolPart('shell', 'c1', { state: 'output-error', errorText: '' }),
+ ]),
+ ])
+ )
+ const part = convertThreadMessageToUIMessage(m).parts[0] as {
+ state: string
+ }
+ expect(part.state).toBe('output-error')
+ })
+
+ it('mints deterministic ids for calls without one and for repeated ones', () => {
+ const s = session([
+ msg('a', 'assistant', [
+ { type: 'tool-read', input: {}, state: 'output-available', output: 'x' },
+ toolPart('read', 'dup', { state: 'output-available', output: 'y' }),
+ toolPart('read', 'dup', { state: 'output-available', output: 'z' }),
+ ]),
+ ])
+ const ids = (out: ThreadMessage[]) =>
+ toolContents(out[0]).map((c) => c.tool_call_id)
+ const first = ids(coworkSessionToThreadMessages(s))
+ expect(first).toEqual(['sess-1-call-0-0', 'dup', 'sess-1-call-0-2'])
+ expect(ids(coworkSessionToThreadMessages(s))).toEqual(first)
+ })
+
+ it('drops messages that carry nothing and still numbers by source index', () => {
+ const out = coworkSessionToThreadMessages(
+ session([
+ msg('u', 'user', [{ type: 'text', text: 'hi' }]),
+ msg('a', 'assistant', [{ type: 'text', text: '' }]),
+ msg('u2', 'user', [{ type: 'text', text: 'again' }]),
+ ])
+ )
+ expect(out.map((m) => m.id)).toEqual(['sess-1-msg-0', 'sess-1-msg-2'])
+ })
+
+ it('rebuilds from turns when a session has no messages', () => {
+ const out = coworkSessionToThreadMessages(
+ session([], {
+ turns: [
+ { role: 'user', content: 'hi' },
+ { role: 'assistant', content: 'hello' },
+ ],
+ })
+ )
+ expect(out.map((m) => m.role)).toEqual(['user', 'assistant'])
+ })
+
+ it('does not add trimming or whitespace changes of its own', () => {
+ const [m] = coworkSessionToThreadMessages(
+ session([msg('u', 'user', [{ type: 'text', text: ' keep \n' }])])
+ )
+ expect(m.content[0].text?.value).toBe(' keep \n')
+ })
+
+ it('reloads to the same UI messages every time', () => {
+ const out = coworkSessionToThreadMessages(conversation())
+ const once = out.map(convertThreadMessageToUIMessage)
+ const twice = coworkSessionToThreadMessages(conversation()).map(
+ convertThreadMessageToUIMessage
+ )
+ expect(twice).toEqual(once)
+ expect(JSON.stringify(twice)).toBe(JSON.stringify(once))
+ // And a record that went through the file (JSON) loads the same.
+ const viaFile = JSON.parse(JSON.stringify(out)).map(
+ convertThreadMessageToUIMessage
+ )
+ expect(viaFile).toEqual(once)
+ })
+})
diff --git a/web-app/src/lib/coworkThreadMessages.ts b/web-app/src/lib/coworkThreadMessages.ts
new file mode 100644
index 000000000..0150b2d12
--- /dev/null
+++ b/web-app/src/lib/coworkThreadMessages.ts
@@ -0,0 +1,236 @@
+import { ContentType, MessageStatus, ChatCompletionRole } from '@janhq/core'
+import type { ThreadContent, ThreadMessage } from '@janhq/core'
+import type { CoworkSession } from '@/hooks/useCoworkSessions'
+import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'
+import { STOPPED_TOOL_ERROR } from '@/lib/stopped-tool-calls'
+
+/**
+ * Converts a Cowork session's transcript into the records main chat persists
+ * in messages.jsonl, so a migrated thread opens with its history.
+ *
+ * The result is re-sent to providers as the prompt prefix on every turn, so it
+ * must be a pure function of the session: ids come from the session id and the
+ * message index, timestamps from `session.updated`, tool call ids are the ones
+ * the session already holds, and object keys are sorted. Nothing reads the
+ * clock or a random source, which is what lets a retried migration rewrite a
+ * byte-identical file and keeps the provider's prefix cache valid.
+ *
+ * The shapes follow `extractContentPartsFromUIMessage` / `toolErrorsOf`
+ * (lib/messages.ts), the writer main chat itself uses, with the differences
+ * noted inline.
+ */
+
+/**
+ * Stored when a failed call carries no error text. `convertThreadMessageToUIMessage`
+ * reloads a call as an error only when its error text is non-empty, so an
+ * empty one would come back as a call that never finished.
+ */
+export const EMPTY_TOOL_ERROR = 'The tool failed without reporting an error.'
+
+type Part = {
+ type?: unknown
+ text?: unknown
+ reasoning?: unknown
+ mediaType?: unknown
+ url?: unknown
+ toolCallId?: unknown
+ toolName?: unknown
+ state?: unknown
+ input?: unknown
+ output?: unknown
+ errorText?: unknown
+}
+
+type SourceMessage = {
+ role?: unknown
+ parts?: Part[]
+ metadata?: unknown
+}
+
+const isRecord = (v: unknown): v is Record<string, unknown> =>
+ typeof v === 'object' && v !== null && !Array.isArray(v)
+
+/** Recursively sorts object keys and drops `undefined`, as JSON would. */
+function stable<T>(value: T): T {
+ if (Array.isArray(value)) return value.map(stable) as T
+ if (isRecord(value)) {
+ const out: Record<string, unknown> = {}
+ for (const key of Object.keys(value).sort()) {
+ if (value[key] !== undefined) out[key] = stable(value[key])
+ }
+ return out as T
+ }
+ return value
+}
+
+/** Cowork stores `updated` in ms, older data in seconds; threads want ms here. */
+const updatedMs = (updated: number) => (updated > 1e12 ? updated : updated * 1000)
+
+const textItem = (type: ContentType, value: string): ThreadContent => ({
+ type,
+ text: { value, annotations: [] },
+})
+
+/** The base64 payload of a data URL, or the url itself when it is not one. */
+const dataOf = (url: string) =>
+ url.startsWith('data:') ? url.slice(url.indexOf(',') + 1) : url
+
+function fileItem(part: Part): ThreadContent | null {
+ if (typeof part.mediaType !== 'string' || typeof part.url !== 'string') {
+ return null
+ }
+ const { mediaType, url } = part
+ if (mediaType.startsWith('image/')) {
+ return {
+ type: ContentType.Image,
+ image_url: { url, detail: 'auto' },
+ }
+ }
+ if (mediaType === 'audio/wav' || mediaType === 'audio/mpeg') {
+ return {
+ type: ContentType.InputAudio,
+ input_audio: {
+ data: dataOf(url),
+ format: mediaType === 'audio/wav' ? 'wav' : 'mp3',
+ },
+ }
+ }
+ if (mediaType.startsWith('video/')) {
+ return {
+ type: ContentType.InputVideo,
+ input_video: { data: dataOf(url), format: mediaType },
+ }
+ }
+ // Main chat has no content type for other files either; it drops them too.
+ return null
+}
+
+function toolName(part: Part): string | null {
+ if (typeof part.type !== 'string') return null
+ if (part.type === 'dynamic-tool') {
+ return typeof part.toolName === 'string' ? part.toolName : null
+ }
+ return part.type.startsWith('tool-') ? part.type.slice('tool-'.length) : null
+}
+
+/**
+ * Cowork can end a run with a call that never got a result (stopped, crashed).
+ * Providers reject a call without a result, and main chat's own Stop settles
+ * such a call as an error, so the migration does the same.
+ */
+function convertMessage(
+ source: SourceMessage,
+ sessionId: string,
+ index: number,
+ usedCallIds: Set<string>
+): { content: ThreadContent[]; toolErrors: Record<string, string> } {
+ const content: ThreadContent[] = []
+ const toolErrors: Record<string, string> = {}
+
+ ;(source.parts ?? []).forEach((part, partIndex) => {
+ if (!isRecord(part)) return
+ if (part.type === 'text') {
+ if (typeof part.text === 'string' && part.text) {
+ content.push(textItem(ContentType.Text, part.text))
+ }
+ return
+ }
+ if (part.type === 'reasoning') {
+ const text = part.text ?? part.reasoning
+ if (typeof text === 'string' && text) {
+ content.push(textItem(ContentType.Reasoning, text))
+ }
+ return
+ }
+ if (part.type === 'file') {
+ const item = fileItem(part)
+ if (item) content.push(item)
+ return
+ }
+
+ const name = toolName(part)
+ if (name === null) return
+ // A reused or missing id would pair two calls with one result, so it is
+ // replaced by an id that depends only on where the call sits.
+ const given = typeof part.toolCallId === 'string' ? part.toolCallId : ''
+ const id =
+ given && !usedCallIds.has(given)
+ ? given
+ : `${sessionId}-call-${index}-${partIndex}`
+ usedCallIds.add(id)
+
+ const item: ThreadContent = {
+ type: ContentType.ToolCall,
+ tool_call_id: id,
+ tool_name: name,
+ ...(part.input !== undefined && { input: part.input }),
+ }
+ if (part.state === 'output-available') {
+ // Not `part.output || ...`: an empty output is still a result.
+ item.output = part.output ?? ''
+ } else if (part.state === 'output-error') {
+ toolErrors[id] =
+ typeof part.errorText === 'string' && part.errorText
+ ? part.errorText
+ : EMPTY_TOOL_ERROR
+ } else {
+ toolErrors[id] = STOPPED_TOOL_ERROR
+ }
+ content.push(item)
+ })
+
+ return { content, toolErrors }
+}
+
+export function coworkSessionToThreadMessages(
+ session: CoworkSession
+): ThreadMessage[] {
+ const source: SourceMessage[] = (
+ session.messages?.length
+ ? session.messages
+ : coworkTurnsToUIMessages(session.turns ?? [], session.id)
+ ) as unknown as SourceMessage[]
+
+ // 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 usedCallIds = new Set<string>()
+ const out: ThreadMessage[] = []
+
+ source.forEach((message, index) => {
+ // A system row is a display note; the model saw it as a user ping that is
+ // already in `messages`. A system message mid-history breaks providers.
+ if (message.role !== 'user' && message.role !== 'assistant') return
+ const { content, toolErrors } = convertMessage(
+ message,
+ session.id,
+ index,
+ usedCallIds
+ )
+ if (content.length === 0) return
+
+ const metadata = {
+ ...(isRecord(message.metadata) ? message.metadata : {}),
+ ...(Object.keys(toolErrors).length > 0 && { toolErrors }),
+ }
+ const createdAt = base + index
+ out.push(
+ stable({
+ type: 'text',
+ role:
+ message.role === 'user'
+ ? ChatCompletionRole.User
+ : ChatCompletionRole.Assistant,
+ content,
+ id: `${session.id}-msg-${index}`,
+ object: 'thread.message',
+ thread_id: session.id,
+ status: MessageStatus.Ready,
+ created_at: createdAt,
+ completed_at: createdAt,
+ ...(Object.keys(metadata).length > 0 && { metadata }),
+ })
+ )
+ })
+ return out
+}