File size: 9,304 Bytes
a1b6014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import type { HermesRepoStatus } from '@/global'

import {
  $repoStatus,
  $repoStatusByCwd,
  $repoStatusLoading,
  _resetCodingStatusForTests,
  refreshAllRepoStatuses,
  refreshRepoStatus,
  registerRepoStatusCwd,
  repoChangeKindForPath,
  repoStatusForCwd
} from './coding-status'
import { $currentCwd, $selectedStoredSessionId } from './session'

const sampleStatus: HermesRepoStatus = {
  branch: 'feature/login',
  defaultBranch: 'main',
  detached: false,
  ahead: 1,
  behind: 0,
  staged: 1,
  unstaged: 2,
  untracked: 0,
  conflicted: 0,
  changed: 3,
  added: 12,
  removed: 4,
  files: []
}

const otherStatus: HermesRepoStatus = {
  ...sampleStatus,
  branch: 'bb/other-worktree',
  added: 3,
  removed: 1,
  changed: 1,
  staged: 0,
  unstaged: 1
}

function stubProbe(impl: (cwd: string) => Promise<HermesRepoStatus | null>) {
  ;(window as unknown as { hermesDesktop?: unknown }).hermesDesktop = { git: { repoStatus: impl } }
}

describe('refreshRepoStatus', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    _resetCodingStatusForTests()
    $currentCwd.set('')
    $selectedStoredSessionId.set(null)
    // Drain the cwd/session subscribe side-effects the sets above kick off.
    vi.advanceTimersByTime(200)
    delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
    _resetCodingStatusForTests()
  })

  afterEach(() => {
    _resetCodingStatusForTests()
    vi.clearAllTimers()
    vi.useRealTimers()
    delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
  })

  it('populates the per-cwd cache and the primary computed for that cwd', async () => {
    stubProbe(async () => sampleStatus)
    $currentCwd.set('/repo')
    await refreshRepoStatus('/repo')
    expect(repoStatusForCwd('/repo').get()).toEqual(sampleStatus)
    expect($repoStatus.get()).toEqual(sampleStatus)
  })

  it('falls back to the active session cwd when none is passed', async () => {
    const probe = vi.fn(async () => sampleStatus)
    stubProbe(probe)
    $currentCwd.set('/active/repo')
    await refreshRepoStatus()
    expect(probe).toHaveBeenCalledWith('/active/repo')
    expect($repoStatus.get()).toEqual(sampleStatus)
  })

  it('leaves the cache alone (primary reads null) when there is no cwd', async () => {
    stubProbe(async () => sampleStatus)
    $currentCwd.set('/repo')
    await refreshRepoStatus('/repo')
    expect($repoStatus.get()).toEqual(sampleStatus)

    // Blank target is a no-op: other worktrees' cached truth must stay put.
    await refreshRepoStatus('   ')
    expect(repoStatusForCwd('/repo').get()).toEqual(sampleStatus)
    $currentCwd.set('')
    expect($repoStatus.get()).toBeNull()
  })

  it('clears every cached status when the probe is unavailable (remote backend)', async () => {
    $currentCwd.set('/repo')
    $repoStatusByCwd.set({ '/repo': sampleStatus, '/other': otherStatus })
    await refreshRepoStatus('/repo')
    expect($repoStatusByCwd.get()).toEqual({})
    expect($repoStatus.get()).toBeNull()
  })

  it('clears only the failing cwd when the probe throws', async () => {
    stubProbe(async cwd => {
      if (cwd === '/bad') {
        throw new Error('not a repo')
      }

      return sampleStatus
    })
    $currentCwd.set('/bad')
    $repoStatusByCwd.set({ '/bad': otherStatus, '/good': sampleStatus })
    await refreshRepoStatus('/bad')
    expect(repoStatusForCwd('/bad').get()).toBeNull()
    expect(repoStatusForCwd('/good').get()).toEqual(sampleStatus)
    expect($repoStatus.get()).toBeNull()
  })

  it('never publishes an old worktree status onto the primary after the active cwd moves', async () => {
    let resolveOld!: (status: HermesRepoStatus | null) => void
    stubProbe(
      () =>
        new Promise(resolve => {
          resolveOld = resolve
        })
    )

    // Explicit probe (not the debounced cwd edge) so the hang is fully under
    // our control — same race window the coding rail used to hit after a
    // session switch mid-probe.
    const inflight = refreshRepoStatus('/repo-a')
    $currentCwd.set('/repo-a')
    await Promise.resolve()

    $currentCwd.set('/repo-b')
    expect($repoStatus.get()).toBeNull()

    resolveOld(sampleStatus)
    await inflight

    // Primary follows the NEW cwd (empty). The old worktree may still cache the
    // late result under its own key — that's what lets a tile rail paint
    // instantly — but it must not leak onto the main rail via $repoStatus.
    expect($repoStatus.get()).toBeNull()
    expect(repoStatusForCwd('/repo-a').get()).toEqual(sampleStatus)
  })

  it('keeps independent statuses for two live worktrees', async () => {
    stubProbe(async cwd => (cwd === '/repo-a' ? sampleStatus : otherStatus))
    await refreshRepoStatus('/repo-a')
    await refreshRepoStatus('/repo-b')
    expect(repoStatusForCwd('/repo-a').get()).toEqual(sampleStatus)
    expect(repoStatusForCwd('/repo-b').get()).toEqual(otherStatus)

    $currentCwd.set('/repo-a')
    expect($repoStatus.get()).toEqual(sampleStatus)
    $currentCwd.set('/repo-b')
    expect($repoStatus.get()).toEqual(otherStatus)
  })

  it('runs one probe at a time and coalesces overlap into one trailing refresh per drain', async () => {
    const resolvers: Array<(status: HermesRepoStatus | null) => void> = []
    const calls: string[] = []
    let active = 0
    let maxActive = 0

    stubProbe(
      cwd =>
        new Promise(resolve => {
          calls.push(cwd)
          active++
          maxActive = Math.max(maxActive, active)
          resolvers.push(status => {
            active--
            resolve(status)
          })
        })
    )

    $currentCwd.set('/repo-c')
    const first = refreshRepoStatus('/repo-a')
    const second = refreshRepoStatus('/repo-b')
    const third = refreshRepoStatus('/repo-c')

    expect(calls).toEqual(['/repo-a'])
    expect(maxActive).toBe(1)
    expect($repoStatusLoading.get()).toBe(true)

    resolvers.shift()?.(sampleStatus)
    await Promise.resolve()
    await Promise.resolve()

    expect(maxActive).toBe(1)
    expect(calls.length).toBe(2)

    resolvers.shift()?.(otherStatus)
    await Promise.resolve()
    await Promise.resolve()
    resolvers.shift()?.(sampleStatus)
    await Promise.all([first, second, third])

    expect(maxActive).toBe(1)
    expect(calls).toEqual(['/repo-a', '/repo-b', '/repo-c'])
    expect(repoStatusForCwd('/repo-a').get()).toEqual(sampleStatus)
    expect(repoStatusForCwd('/repo-b').get()).toEqual(otherStatus)
    expect(repoStatusForCwd('/repo-c').get()).toEqual(sampleStatus)
    expect($repoStatus.get()).toEqual(sampleStatus)
    expect($repoStatusLoading.get()).toBe(false)
  })

  it('refreshes when the stored session id changes even if the cwd is unchanged', async () => {
    const probe = vi.fn(async () => sampleStatus)
    stubProbe(probe)

    $currentCwd.set('/repo')
    $selectedStoredSessionId.set('session-a')
    // The cwd subscription fires on the set above; drain the debounced refresh.
    vi.advanceTimersByTime(200)
    await vi.runAllTicks()

    probe.mockClear()

    // Switch to a different session in the SAME repo dir. The cwd atom value is
    // identical, so its subscription would not re-fire — but the stored-session
    // id did change, which must still trigger a probe so the branch label
    // tracks the new session's checked-out branch.
    $selectedStoredSessionId.set('session-b')
    vi.advanceTimersByTime(200)
    await vi.runAllTicks()

    expect(probe).toHaveBeenCalledWith('/repo')
  })

  it('registerRepoStatusCwd keeps that worktree in unscoped refreshes', async () => {
    const probe = vi.fn(async cwd => (cwd === '/tile' ? otherStatus : sampleStatus))
    stubProbe(probe)

    $currentCwd.set('/main')
    const release = registerRepoStatusCwd('/tile')
    // Drain the register kick + cwd edge so the assert only covers the
    // unscoped fan-out.
    vi.advanceTimersByTime(200)
    await refreshAllRepoStatuses()
    probe.mockClear()

    // Unscoped fan-out: every registered worktree + primary, not main only.
    await refreshAllRepoStatuses()

    const probed = [...new Set(probe.mock.calls.map(call => call[0]))].sort()
    expect(probed).toEqual(['/main', '/tile'])
    expect(repoStatusForCwd('/tile').get()).toEqual(otherStatus)
    expect(repoStatusForCwd('/main').get()).toEqual(sampleStatus)

    release?.()
  })
})

describe('repoChangeKindForPath', () => {
  it('does not notify a row when only another path changes', () => {
    $currentCwd.set('/repo')
    $repoStatusByCwd.set({ '/repo': { ...sampleStatus, files: [] } })
    const row = repoChangeKindForPath('/repo/a.ts')
    const listener = vi.fn()
    const unsubscribe = row.subscribe(listener)

    $repoStatusByCwd.set({
      '/repo': {
        ...sampleStatus,
        files: [{ path: 'b.ts', untracked: true } as HermesRepoStatus['files'][number]]
      }
    })
    expect(listener).toHaveBeenCalledTimes(1)

    $repoStatusByCwd.set({
      '/repo': {
        ...sampleStatus,
        files: [{ path: 'a.ts', untracked: true } as HermesRepoStatus['files'][number]]
      }
    })
    expect(listener).toHaveBeenCalledTimes(2)
    expect(listener.mock.calls.at(-1)?.[0]).toBe('added')

    unsubscribe()
  })
})