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.

9.4 KB
Raw Blame
import { describe, it, expect, beforeEach, vi } from 'vitest'

vi.mock('@/lib/backendStorage', () => ({
  backendStorage: {
    getItem: vi.fn().mockResolvedValue(null),
    setItem: vi.fn().mockResolvedValue(undefined),
    removeItem: vi.fn().mockResolvedValue(undefined),
  },
}))

import { useCoworkSessions } from '../useCoworkSessions'
import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'

const reset = () =>
  useCoworkSessions.setState({ sessions: [], currentId: null })

const sub = (runId: string, name: string): SubagentRun => ({
  runId,
  name,
  status: 'done',
  startedAt: 0,
  turns: [],
})

describe('useCoworkSessions', () => {
  beforeEach(reset)

  it('starts a session with an empty message list', () => {
    const id = useCoworkSessions.getState().createSession()
    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.messages).toEqual([])
    expect(s.folder).toBeNull()
  })

  it('rewinds a run back to the question that started it', () => {
    const id = useCoworkSessions.getState().createSession()
    const turns: CoworkTurn[] = [
      { role: 'user', content: 'first' },
      { role: 'assistant', content: 'done' },
      { role: 'user', content: 'second' },
      { role: 'tool', content: '', name: 'read', status: 'done' },
      { role: 'assistant', content: 'answer' },
    ]
    const msgs = [
      { id: 'm1', role: 'user', parts: [] },
      { id: 'm2', role: 'assistant', parts: [] },
      { id: 'm3', role: 'user', parts: [] },
      { id: 'm4', role: 'assistant', parts: [] },
    ] as never
    useCoworkSessions.getState().commitTurns(id, turns, msgs, [])
    useCoworkSessions.getState().rewindToLastUser(id)

    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    // The question survives; the chain of tool calls it produced does not.
    expect(s.turns.map((t) => t.content)).toEqual(['first', 'done', 'second'])
    expect(s.messages.map((m) => m.id)).toEqual(['m1', 'm2', 'm3'])
  })

  /// A subagent ping is a user message with no transcript row, so counting it
  /// as the question would cut the two histories at different points and
  /// resume the run from a note about a subagent.
  it('rewinds past a subagent ping to the real question', () => {
    const id = useCoworkSessions.getState().createSession()
    const turns: CoworkTurn[] = [
      { role: 'user', content: 'second' },
      { role: 'assistant', content: 'answer' },
    ]
    const msgs = [
      { id: 'm1', role: 'user', parts: [{ type: 'text', text: 'second' }] },
      { id: 'm2', role: 'assistant', parts: [] },
      {
        id: 'ping-2',
        role: 'user',
        parts: [{ type: 'text', text: '<SYSTEM>\nalpha done\n</SYSTEM>' }],
      },
      { id: 'm3', role: 'assistant', parts: [] },
    ] as never
    useCoworkSessions.getState().commitTurns(id, turns, msgs, [])
    useCoworkSessions.getState().rewindToLastUser(id)

    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.turns.map((t) => t.content)).toEqual(['second'])
    expect(s.messages.map((m) => m.id)).toEqual(['m1'])
  })

  /// Editing or deleting a question partway up the transcript cuts both lists
  /// at that question. The wire history has messages the transcript has no row
  /// for, so the cut is counted in questions, not in indices.
  it('drops a question and everything it produced', () => {
    const id = useCoworkSessions.getState().createSession()
    const turns: CoworkTurn[] = [
      { role: 'user', content: 'first' },
      { role: 'assistant', content: 'answer one' },
      { role: 'user', content: 'second' },
      { role: 'tool', content: '', name: 'read', status: 'done' },
      { role: 'assistant', content: 'answer two' },
    ]
    const msgs = [
      { id: 'm1', role: 'user', parts: [{ type: 'text', text: 'first' }] },
      { id: 'm2', role: 'assistant', parts: [] },
      {
        id: 'ping-2',
        role: 'user',
        parts: [{ type: 'text', text: '<SYSTEM>\nalpha done\n</SYSTEM>' }],
      },
      { id: 'm3', role: 'user', parts: [{ type: 'text', text: 'second' }] },
      { id: 'm4', role: 'assistant', parts: [] },
    ] as never
    useCoworkSessions.getState().commitTurns(id, turns, msgs, [])
    useCoworkSessions.getState().dropFromTurn(id, 2)

    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.turns.map((t) => t.content)).toEqual(['first', 'answer one'])
    // The ping belongs to the first question's run, so it survives with it.
    expect(s.messages.map((m) => m.id)).toEqual(['m1', 'm2', 'ping-2'])
  })

  /// The answers to a question cannot outlive it, so an assistant or tool turn
  /// is not a place the transcript can be cut.
  it('refuses to cut anywhere but a question', () => {
    const id = useCoworkSessions.getState().createSession()
    const turns: CoworkTurn[] = [
      { role: 'user', content: 'first' },
      { role: 'assistant', content: 'answer' },
    ]
    const msgs = [
      { id: 'm1', role: 'user', parts: [{ type: 'text', text: 'first' }] },
      { id: 'm2', role: 'assistant', parts: [] },
    ] as never
    useCoworkSessions.getState().commitTurns(id, turns, msgs, [])
    useCoworkSessions.getState().dropFromTurn(id, 1)
    useCoworkSessions.getState().dropFromTurn(id, 9)

    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.turns).toHaveLength(2)
    expect(s.messages).toHaveLength(2)
  })

  // Rewinding a session that has never had a turn would otherwise empty it.
  it('leaves a session with no user turn alone', () => {
    const id = useCoworkSessions.getState().createSession()
    useCoworkSessions.getState().rewindToLastUser(id)
    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.turns).toEqual([])
    expect(s.messages).toEqual([])
  })

  it('appends turns and replaces the message list on commit', () => {
    const id = useCoworkSessions.getState().createSession()
    const turn: CoworkTurn = { role: 'user', content: 'hi' }
    const msgs = [{ id: 'm1', role: 'user', parts: [] }] as never
    useCoworkSessions.getState().commitTurns(id, [turn], msgs, [])
    useCoworkSessions.getState().commitTurns(id, [turn], msgs, [])
    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.turns).toHaveLength(2)
    expect(s.messages).toHaveLength(1)
  })

  // A later run that dispatches no subagents must not erase what an earlier
  // run in the same session already finished.
  it('merges subagents by runId across runs instead of replacing', () => {
    const id = useCoworkSessions.getState().createSession()
    useCoworkSessions.getState().commitTurns(id, [], [], [sub('r1', 'alpha')])
    useCoworkSessions.getState().commitTurns(id, [], [], [])
    let s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.subagents?.map((r) => r.runId)).toEqual(['r1'])

    useCoworkSessions.getState().commitTurns(id, [], [], [sub('r1', 'renamed')])
    s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.subagents).toHaveLength(1)
    expect(s.subagents?.[0].name).toBe('renamed')
  })

  it('keeps the last usage when a run reports none', () => {
    const id = useCoworkSessions.getState().createSession()
    useCoworkSessions
      .getState()
      .commitTurns(id, [], [], [], { total_tokens: 42 })
    useCoworkSessions.getState().commitTurns(id, [], [], [])
    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.lastUsage?.total_tokens).toBe(42)
  })

  it('clears the transcript, messages and subagents together', () => {
    const id = useCoworkSessions.getState().createSession()
    useCoworkSessions
      .getState()
      .commitTurns(
        id,
        [{ role: 'user', content: 'hi' }],
        [{ id: 'm1', role: 'user', parts: [] }] as never,
        [sub('r1', 'alpha')],
        { total_tokens: 1 }
      )
    useCoworkSessions.getState().clearSession(id)
    const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.turns).toEqual([])
    expect(s.messages).toEqual([])
    expect(s.subagents).toEqual([])
    expect(s.lastUsage).toBeUndefined()
  })

  it('toggles plan mode and detaches a folder', () => {
    const id = useCoworkSessions.getState().createSession()
    useCoworkSessions.getState().setPlanMode(id, true)
    useCoworkSessions.getState().setFolder(id, '/tmp/project')
    let s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.planMode).toBe(true)
    expect(s.folder).toBe('/tmp/project')

    useCoworkSessions.getState().setFolder(id, null)
    s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
    expect(s.folder).toBeNull()
  })
})

describe('useCoworkSessions createSession reuse', () => {
  beforeEach(reset)

  it('reuses the current session when it is still empty', () => {
    const first = useCoworkSessions.getState().createSession()
    const second = useCoworkSessions.getState().createSession()
    expect(second).toBe(first)
    expect(useCoworkSessions.getState().sessions).toHaveLength(1)
  })

  it('creates a fresh session once the current one has turns', () => {
    const first = useCoworkSessions.getState().createSession()
    useCoworkSessions
      .getState()
      .commitTurns(first, [{ role: 'user', content: 'hi' }], [], [])
    const second = useCoworkSessions.getState().createSession()
    expect(second).not.toBe(first)
    expect(useCoworkSessions.getState().sessions).toHaveLength(2)
  })
})