import { QueryClientProvider } from '@tanstack/react-query' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { MemoryRouter, Route, Routes, useNavigate } from 'react-router' import { afterEach, describe, expect, it, vi } from 'vitest' import { queryKeys } from '@/api/queries' import { createQueryClient } from '@/api/query-client' import type { ApiRun, ChangesPayload, HealthResponse, RepoResponse } from '@open-mercato/cezar-api-client' import { Toaster, resetToasts } from '@/components/ui/toaster' import { GitActions, GitToolbar } from './git-toolbar' import { TaskChangesRoute } from './task-changes' import { __resetGitStepFlights } from './run-git-step' afterEach(() => { __resetGitStepFlights() act(() => resetToasts()) cleanup() vi.unstubAllGlobals() }) // ---- fixtures -------------------------------------------------------------------------------- const RUN: ApiRun = { id: 'r1', title: 'do the thing plz', titleSummary: 'Do the thing', workflow: 'quick-task', task: 'Summarize what this project does.', status: 'review', createdAt: '2026-07-15T08:00:00.000Z', tokensUsed: 0, archived: false, worktreePath: '/tmp/wt/r1', branch: 'cez/abc12345', baseBranch: 'main', steps: [ { id: 'task', name: 'Do the task', kind: 'agent', status: 'done', iterations: 1, tokensUsed: 0, sessionId: 's-1' }, ], } const HEALTH: HealthResponse = { version: '0.0.0-test', runtimeId: '00000000-0000-4000-8000-000000000001', projects: [], bootProject: 'default', repoRoot: '/repo', repo: { root: '/repo', branch: 'main', remote: 'git@github.com:acme/demo.git' }, checks: [], defaultRunner: 'claude', forge: { kind: 'github', available: true }, capabilities: { localHandoff: true, terminal: false, designMode: false, tokenMetrics: true, tokenUsageMetrics: true, costMetrics: true, followups: false, phonePairing: false, singleProject: false, automations: false, webhooks: false, dispatch: false }, } /** The PROJECT-scoped `/repo` answer. The remote that gates Push is read from here rather than * from `health.repo`, which describes the boot folder only (#791). */ const REPO: RepoResponse = { info: { root: '/repo', branch: 'main', remote: 'git@github.com:acme/demo.git' }, status: [], log: [], branches: ['main'], checkedOutElsewhere: {}, baseBranch: null, } const CHANGES: ChangesPayload = { files: [ { path: 'notes.md', status: 'added', adds: 2, dels: 0, binary: false, patch: 'diff --git a/notes.md b/notes.md\n--- /dev/null\n+++ b/notes.md\n@@ -0,0 +1,2 @@\n+one\n+two\n', }, { path: 'src/util/a.ts', status: 'modified', adds: 3, dels: 1, binary: false, patch: 'diff --git a/src/util/a.ts b/src/util/a.ts\n--- a/src/util/a.ts\n+++ b/src/util/a.ts\n@@ -1,2 +1,4 @@\n context\n-gone\n+one\n+two\n+three\n', }, ], stat: { adds: 5, dels: 1, files: 2 }, } interface SentRequest { path: string method: string body: unknown } const jsonResponse = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }) /** Fetch stub in the house style (review-panel.test.tsx): records requests, serves the run, * health and changes fixtures, and lets a test override specific `METHOD path` keys. */ function stubFetch(overrides: Record Response> = {}): SentRequest[] { const sent: SentRequest[] = [] vi.stubGlobal( 'fetch', vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => { const path = String(input) const method = init.method ?? 'GET' sent.push({ path, method, body: typeof init.body === 'string' ? JSON.parse(init.body) : undefined }) const override = overrides[`${method} ${path}`] if (override) return override() if (method === 'GET' && path === '/api/v1/runs/r1') return jsonResponse(RUN) if (method === 'GET' && path === '/api/v1/runs/r1/changes') return jsonResponse(CHANGES) if (method === 'GET' && path === '/api/v1/runs/r1/git/status') return jsonResponse({ uncommitted: 2, unpushed: null }) if (method === 'GET' && path === '/api/v1/health') return jsonResponse(HEALTH) if (method === 'GET' && path === '/api/v1/repo') return jsonResponse(REPO) if (method === 'GET' && path === '/api/v1/runs') return jsonResponse([]) return jsonResponse({}) }), ) return sent } function renderChangesRoute(entry = '/tasks/r1/changes') { render( } /> , ) } /** The run's git step, as the run header's title row paints it (desktop; phones read the same * step from the header's action menu). The Changes toolbar carries none of its own. */ const gitButton = () => document.querySelector('[data-slot="run-header"] [data-slot="git-button"]') as HTMLElement | null const toolbarAction = (id: string) => gitButton()?.querySelector(`[data-action="${id}"]`) as HTMLButtonElement | null /** The run record with a PR — the state in which Commit and Push are the one step. */ const WITH_PR: ApiRun = { ...RUN, status: 'done', pullRequestUrl: 'https://github.com/acme/demo/pull/9' } /** Usable = neither busy (`disabled`) nor blocked by the policy (`aria-disabled`). */ const usable = (el: HTMLButtonElement | null | undefined) => Boolean(el) && !el!.disabled && el!.getAttribute('aria-disabled') !== 'true' // ---- the route ------------------------------------------------------------------------------- describe('the Changes tab route', () => { it('a Markdown file offers the preview toggle, which renders the full worktree text', async () => { const sent = stubFetch({ 'GET /api/v1/runs/r1/files?path=notes.md': () => jsonResponse({ type: 'file', path: 'notes.md', size: 40, binary: false, tooLarge: false, content: '# From the worktree\n\nWhole file' }), }) renderChangesRoute() const toggle = await waitFor(() => { const element = document.querySelector('[data-slot="git-toolbar"] [data-slot="markdown-preview-toggle"]') expect(element).not.toBeNull() return element! }) expect(document.querySelector('[data-slot="diff-markdown-preview"]')).toBeNull() fireEvent.click(toggle) await waitFor(() => expect(document.querySelector('[data-slot="diff-markdown-preview"] h1')?.textContent).toBe('From the worktree'), ) expect(sent.some((request) => request.path === '/api/v1/runs/r1/files?path=notes.md')).toBe(true) // The TypeScript file stays a diff. expect(document.querySelector('[data-slot="diff-file"][data-path="src/util/a.ts"] [data-slot="diff-file-body"]')).not.toBeNull() }) it('no Markdown in the diff, no preview toggle', async () => { stubFetch({ 'GET /api/v1/runs/r1/changes': () => jsonResponse({ files: CHANGES.files.slice(1), stat: { adds: 3, dels: 1, files: 1 } }), }) renderChangesRoute() await waitFor(() => expect(document.querySelectorAll('[data-slot="diff-file"]')).toHaveLength(1)) expect(document.querySelector('[data-slot="markdown-preview-toggle"]')).toBeNull() }) // The tree and the diff scroll in columns of their own, which the shell's per-pathname reset of // `main` never touches. With both tasks already cached nothing unmounts on the way from one to // the other, so only the view's `key` guarantees a fresh pair of columns at the top. it('starts another task with fresh scroll columns, even when its data is cached', async () => { const R2 = { ...RUN, id: 'r2', title: 'the other task' } stubFetch({ 'GET /api/v1/runs/r2': () => jsonResponse(R2), 'GET /api/v1/runs/r2/changes': () => jsonResponse(CHANGES), }) const client = createQueryClient() client.setQueryData(queryKeys.runs.detail('r2'), R2) client.setQueryData(queryKeys.runs.changes('r2'), CHANGES) function GoToR2() { const navigate = useNavigate() return