@cat-factory/app 0.72.0 → 0.73.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/app/components/board/nodes/TaskCard.vue +12 -2
  2. package/app/components/bootstrap/BootstrapModal.vue +23 -7
  3. package/app/components/brainstorm/BrainstormWindow.vue +2 -0
  4. package/app/components/clarity/ClarityReviewWindow.vue +2 -0
  5. package/app/components/consensus/ConsensusSessionWindow.vue +2 -0
  6. package/app/components/focus/BlockFocusView.vue +2 -0
  7. package/app/components/followUp/FollowUpWindow.vue +2 -0
  8. package/app/components/gates/GateResultView.vue +2 -0
  9. package/app/components/humanTest/HumanTestWindow.vue +2 -0
  10. package/app/components/layout/ConnectionStatusBanner.vue +81 -0
  11. package/app/components/layout/NotificationsInbox.vue +15 -0
  12. package/app/components/panels/GenericStructuredResultView.vue +2 -0
  13. package/app/components/panels/InspectorPanel.vue +30 -1
  14. package/app/components/panels/inspector/TaskExecution.vue +25 -1
  15. package/app/components/pipeline/PipelineBuilder.vue +110 -7
  16. package/app/components/requirements/RequirementsReviewWindow.vue +2 -0
  17. package/app/components/spec/ServiceSpecWindow.vue +2 -0
  18. package/app/components/testing/TestReportWindow.vue +91 -0
  19. package/app/composables/useKeyboardShortcuts.ts +10 -2
  20. package/app/pages/index.vue +6 -4
  21. package/app/stores/board.spec.ts +58 -1
  22. package/app/stores/board.ts +59 -15
  23. package/app/stores/brainstorm.spec.ts +35 -0
  24. package/app/stores/brainstorm.ts +11 -2
  25. package/app/stores/clarity.spec.ts +33 -0
  26. package/app/stores/clarity.ts +11 -2
  27. package/app/stores/execution.spec.ts +71 -13
  28. package/app/stores/execution.ts +44 -6
  29. package/app/stores/pipelines.ts +53 -0
  30. package/app/stores/recurringPipelines.ts +5 -1
  31. package/app/stores/requirements.spec.ts +21 -0
  32. package/app/stores/requirements.ts +11 -2
  33. package/app/stores/workspace.ts +1 -1
  34. package/app/utils/catalog.ts +9 -0
  35. package/i18n/locales/en.json +56 -5
  36. package/i18n/locales/es.json +56 -5
  37. package/i18n/locales/fr.json +56 -5
  38. package/i18n/locales/he.json +56 -5
  39. package/i18n/locales/ja.json +56 -5
  40. package/i18n/locales/pl.json +56 -5
  41. package/i18n/locales/tr.json +56 -5
  42. package/i18n/locales/uk.json +56 -5
  43. package/package.json +2 -2
@@ -47,6 +47,12 @@ const testState = computed(() => step.value?.test ?? null)
47
47
  // ended), newest first, so the otherwise-opaque fixer sub-jobs have a surface here.
48
48
  const fixerAttempts = computed(() => [...(testState.value?.attemptLog ?? [])].reverse())
49
49
 
50
+ // Test quality-control companion state: the coverage audit the QC reviewer ran on each report
51
+ // (before the greenlight/fixer decision) plus its loop budget. Verdicts newest-first, so the
52
+ // most recent audit leads. Absent when the companion is disabled or never ran.
53
+ const quality = computed(() => step.value?.testerQuality ?? null)
54
+ const qualityVerdicts = computed(() => [...(quality.value?.verdicts ?? [])].reverse())
55
+
50
56
  // Infrastructure observability — parity with the Coder's generic step detail, so the
51
57
  // Tester window surfaces WHERE its job runs (the container lifecycle: spinning up /
52
58
  // running phase / id+url / errored), the ephemeral environment it tests against, and the
@@ -551,6 +557,91 @@ const GROUP_STATUS_META: Record<ScenarioGroup['status'], { icon: string; text: s
551
557
  </ol>
552
558
  </section>
553
559
 
560
+ <!-- Test quality-control companion: the coverage audit(s) the QC reviewer ran on
561
+ the report before the greenlight/fixer decision. Each verdict says whether the
562
+ report adequately covered what the task needed tested, with the gaps that
563
+ looped the Tester for a focused additional pass. -->
564
+ <section
565
+ v-if="quality && qualityVerdicts.length"
566
+ data-testid="tester-quality"
567
+ class="space-y-2"
568
+ >
569
+ <div class="flex items-center gap-2">
570
+ <h3 class="text-[11px] font-semibold uppercase tracking-wide text-slate-500">
571
+ {{ t('testing.quality.heading') }}
572
+ </h3>
573
+ <span
574
+ v-if="quality.attempts"
575
+ class="text-[11px] text-slate-400"
576
+ :title="t('testing.quality.reruns')"
577
+ >
578
+ {{
579
+ t('testing.quality.rerunCount', {
580
+ attempts: quality.attempts,
581
+ max: quality.maxAttempts,
582
+ })
583
+ }}
584
+ </span>
585
+ <UBadge
586
+ v-if="quality.exceeded"
587
+ color="warning"
588
+ variant="subtle"
589
+ size="sm"
590
+ data-testid="tester-quality-exceeded"
591
+ >
592
+ {{ t('testing.quality.exceeded') }}
593
+ </UBadge>
594
+ </div>
595
+ <ol class="space-y-2">
596
+ <li
597
+ v-for="(vd, vi) in qualityVerdicts"
598
+ :key="`qc${vi}`"
599
+ data-testid="tester-quality-verdict"
600
+ class="rounded-lg border border-slate-800 bg-slate-900/60 px-3 py-2"
601
+ >
602
+ <div class="flex items-center gap-2">
603
+ <UIcon
604
+ :name="vd.adequate ? 'i-lucide-shield-check' : 'i-lucide-shield-alert'"
605
+ class="h-3.5 w-3.5 shrink-0"
606
+ :class="vd.adequate ? 'text-emerald-400' : 'text-amber-300'"
607
+ />
608
+ <span class="text-[13px] font-medium text-slate-200">
609
+ {{
610
+ vd.adequate
611
+ ? t('testing.quality.adequate')
612
+ : t('testing.quality.inadequate')
613
+ }}
614
+ </span>
615
+ <span v-if="vd.model" class="ms-auto font-mono text-[10px] text-slate-500">{{
616
+ vd.model
617
+ }}</span>
618
+ <span class="text-[11px] text-slate-500" :class="{ 'ms-auto': !vd.model }">{{
619
+ d(new Date(vd.at), 'short')
620
+ }}</span>
621
+ </div>
622
+ <p v-if="vd.feedback" class="mt-1 text-[12px] leading-snug text-slate-400">
623
+ {{ vd.feedback }}
624
+ </p>
625
+ <div v-if="vd.gaps.length" class="mt-1.5">
626
+ <p class="text-[11px] text-slate-500">{{ t('testing.quality.gaps') }}</p>
627
+ <ul class="mt-1 space-y-0.5">
628
+ <li
629
+ v-for="(gap, gi) in vd.gaps"
630
+ :key="`qc${vi}-g${gi}`"
631
+ class="flex items-start gap-1.5 text-[12px] text-slate-300"
632
+ >
633
+ <UIcon
634
+ name="i-lucide-dot"
635
+ class="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-400"
636
+ />
637
+ <span>{{ gap }}</span>
638
+ </li>
639
+ </ul>
640
+ </div>
641
+ </li>
642
+ </ol>
643
+ </section>
644
+
554
645
  <div
555
646
  v-if="!report"
556
647
  class="flex flex-col items-center justify-center gap-2 py-12 text-center text-slate-400"
@@ -20,9 +20,17 @@ export function useKeyboardShortcuts(): void {
20
20
  const board = useBoardStore()
21
21
  const { deleteBlock } = useBlockDeletion()
22
22
 
23
- /** A modal (UModal) is on screen — let it own the keyboard; don't run global shortcuts. */
23
+ /** A modal / full-screen window is on screen — let it own the keyboard; don't run global
24
+ * shortcuts (else e.g. Delete would delete the selected block hidden BEHIND the window). The
25
+ * hand-rolled result-view + focus windows now carry `role="dialog"`, so the DOM check catches
26
+ * them; the store flags are belt-and-suspenders for the same windows. */
24
27
  function modalOpen(): boolean {
25
- return ui.commandBarOpen || !!document.querySelector('[role="dialog"]')
28
+ return (
29
+ ui.commandBarOpen ||
30
+ !!ui.resultView ||
31
+ !!ui.focusBlockId ||
32
+ !!document.querySelector('[role="dialog"]')
33
+ )
26
34
  }
27
35
 
28
36
  /** The event originates from a text field, so printable/Delete keys are edits, not shortcuts. */
@@ -3,6 +3,7 @@ import BoardCanvas from '~/components/board/BoardCanvas.vue'
3
3
  import SideBar from '~/components/layout/SideBar.vue'
4
4
  import BoardToolbar from '~/components/layout/BoardToolbar.vue'
5
5
  import SpendWarningBanner from '~/components/layout/SpendWarningBanner.vue'
6
+ import ConnectionStatusBanner from '~/components/layout/ConnectionStatusBanner.vue'
6
7
  import TranslationWarningBanner from '~/components/layout/TranslationWarningBanner.vue'
7
8
  import GitHubPatBanner from '~/components/layout/GitHubPatBanner.vue'
8
9
  import AiProvidersBanner from '~/components/layout/AiProvidersBanner.vue'
@@ -275,7 +276,7 @@ watch(
275
276
  class="m-auto flex flex-col items-center gap-3 text-slate-400"
276
277
  >
277
278
  <UIcon name="i-lucide-loader" class="h-8 w-8 animate-spin" />
278
- <span class="text-sm">Loading…</span>
279
+ <span class="text-sm">{{ $t('app.loading') }}</span>
279
280
  </div>
280
281
 
281
282
  <!-- App enabled but not installed on this workspace: hard onboarding gate. -->
@@ -312,6 +313,7 @@ watch(
312
313
  />
313
314
  <BoardToolbar />
314
315
  <SpendWarningBanner />
316
+ <ConnectionStatusBanner :connected="streamConnected" />
315
317
  <InspectorPanel />
316
318
  <!-- Code-split focus view. The fade lives here (not inside the component) so the
317
319
  leave animation still plays when `focusBlockId` clears and the v-if unmounts
@@ -368,17 +370,17 @@ watch(
368
370
  <!-- Backend unreachable / bootstrap failed -->
369
371
  <div v-else-if="workspace.error" class="m-auto max-w-md p-8 text-center">
370
372
  <UIcon name="i-lucide-plug-zap" class="mx-auto mb-3 h-10 w-10 text-amber-400" />
371
- <h1 class="mb-1 text-lg font-semibold">Can’t reach the backend</h1>
373
+ <h1 class="mb-1 text-lg font-semibold">{{ $t('app.backendUnreachable') }}</h1>
372
374
  <p class="mb-4 text-sm text-slate-400">{{ workspace.error }}</p>
373
375
  <UButton color="primary" icon="i-lucide-rotate-ccw" @click="workspace.init()">
374
- Retry
376
+ {{ $t('common.retry') }}
375
377
  </UButton>
376
378
  </div>
377
379
 
378
380
  <!-- Initial load -->
379
381
  <div v-else class="m-auto flex flex-col items-center gap-3 text-slate-400">
380
382
  <UIcon name="i-lucide-loader" class="h-8 w-8 animate-spin" />
381
- <span class="text-sm">Loading board…</span>
383
+ <span class="text-sm">{{ $t('app.loadingBoard') }}</span>
382
384
  </div>
383
385
  </div>
384
386
  </template>
@@ -1,6 +1,8 @@
1
- import { describe, it, expect, beforeEach } from 'vitest'
1
+ import { describe, it, expect, beforeEach, vi } from 'vitest'
2
+ import { setActivePinia, createPinia } from 'pinia'
2
3
  import type { Block, BlockStatus } from '~/types/domain'
3
4
  import { useBoardStore } from '~/stores/board'
5
+ import { useWorkspaceStore } from '~/stores/workspace'
4
6
 
5
7
  /** Minimal Block factory — only the fields the read getters care about. */
6
8
  function block(id: string, over: Partial<Block> = {}): Block {
@@ -224,6 +226,22 @@ describe('board store read getters', () => {
224
226
  expect(() => store.previewMove('missing', { x: 1, y: 1 })).not.toThrow()
225
227
  })
226
228
 
229
+ it('updateBlock restores the patched fields and toasts when the write fails', async () => {
230
+ // Capture the toast the store surfaces on failure. Re-stub before creating the store so it
231
+ // binds this spy (the store resolves `useToast()` once at setup).
232
+ const addSpy = vi.fn()
233
+ vi.stubGlobal('useToast', () => ({ add: addSpy }))
234
+ setActivePinia(createPinia())
235
+ const s = useBoardStore()
236
+ s.hydrate([frame('f1', { title: 'Original', description: 'orig' })])
237
+ // With no active workspace, `requireId()` throws inside updateBlock's try — the same catch
238
+ // that a rejected API write hits — so this exercises the optimistic-rollback + toast path.
239
+ await s.updateBlock('f1', { title: 'Edited', description: 'changed' })
240
+ expect(s.getBlock('f1')?.title).toBe('Original')
241
+ expect(s.getBlock('f1')?.description).toBe('orig')
242
+ expect(addSpy).toHaveBeenCalledWith(expect.objectContaining({ color: 'error' }))
243
+ })
244
+
227
245
  it('hydrate replaces and upsert inserts/updates cached blocks', () => {
228
246
  store.hydrate([frame('f1')])
229
247
  store.upsert(task('t1', 'f1', { title: 'first' }))
@@ -233,3 +251,42 @@ describe('board store read getters', () => {
233
251
  expect(store.allTasks).toHaveLength(1)
234
252
  })
235
253
  })
254
+
255
+ describe('board store optimistic rollback', () => {
256
+ // These instantiate their own store AFTER stubbing the api (the store captures
257
+ // `useApi()` at setup), unlike the read-getter suite above.
258
+ beforeEach(() => {
259
+ useWorkspaceStore().workspaceId = 'ws1'
260
+ })
261
+
262
+ it('moveBlock restores the pre-drag position when the API rejects', async () => {
263
+ vi.stubGlobal('useApi', () => ({
264
+ moveBlock: () => Promise.reject(new Error('conflict')),
265
+ }))
266
+ const store = useBoardStore()
267
+ store.hydrate([frame('f1'), task('t1', 'f1', { position: { x: 10, y: 20 } })])
268
+ await store.moveBlock('t1', { x: 500, y: 600 })
269
+ expect(store.getBlock('t1')?.position).toEqual({ x: 10, y: 20 })
270
+ })
271
+
272
+ it('moveBlock keeps the new position on success', async () => {
273
+ vi.stubGlobal('useApi', () => ({
274
+ moveBlock: async () => task('t1', 'f1', { position: { x: 500, y: 600 } }),
275
+ }))
276
+ const store = useBoardStore()
277
+ store.hydrate([frame('f1'), task('t1', 'f1', { position: { x: 10, y: 20 } })])
278
+ await store.moveBlock('t1', { x: 500, y: 600 })
279
+ expect(store.getBlock('t1')?.position).toEqual({ x: 500, y: 600 })
280
+ })
281
+
282
+ it('updateBlock restores only the patched fields when the API rejects', async () => {
283
+ vi.stubGlobal('useApi', () => ({
284
+ updateBlock: () => Promise.reject(new Error('validation')),
285
+ }))
286
+ const store = useBoardStore()
287
+ store.hydrate([frame('f1'), task('t1', 'f1', { title: 'orig', description: 'keep' })])
288
+ await store.updateBlock('t1', { title: 'renamed' })
289
+ expect(store.getBlock('t1')?.title).toBe('orig')
290
+ expect(store.getBlock('t1')?.description).toBe('keep')
291
+ })
292
+ })
@@ -29,6 +29,11 @@ interface RemovalSnapshot {
29
29
  export const useBoardStore = defineStore('board', () => {
30
30
  const api = useApi()
31
31
  const toast = useToast()
32
+ // Stores run outside a component `setup`, so resolve translations through the Nuxt app's
33
+ // global i18n instance (the same handle `plugins/locale.client.ts` uses) rather than
34
+ // `useI18n()`, which requires an active component instance.
35
+ const nuxtApp = useNuxtApp()
36
+ const tr = (key: string): string => (nuxtApp.$i18n as { t: (k: string) => string }).t(key)
32
37
  const blocks = ref<Block[]>([])
33
38
 
34
39
  // Pure derivations (hierarchy, status/progress, sizing) live in the composable.
@@ -162,7 +167,7 @@ export const useBoardStore = defineStore('board', () => {
162
167
  } catch (e) {
163
168
  t.epicId = prev
164
169
  toast.add({
165
- title: 'Could not change epic',
170
+ title: tr('board.toast.epicFailed'),
166
171
  description: e instanceof Error ? e.message : String(e),
167
172
  icon: 'i-lucide-triangle-alert',
168
173
  color: 'error',
@@ -216,7 +221,7 @@ export const useBoardStore = defineStore('board', () => {
216
221
  b.parentId = prevParentId
217
222
  b.position = prevPosition
218
223
  toast.add({
219
- title: 'Could not move',
224
+ title: tr('board.toast.moveFailed'),
220
225
  description: e instanceof Error ? e.message : String(e),
221
226
  icon: 'i-lucide-triangle-alert',
222
227
  color: 'error',
@@ -289,7 +294,7 @@ export const useBoardStore = defineStore('board', () => {
289
294
  } catch (e) {
290
295
  reattach(snap)
291
296
  toast.add({
292
- title: 'Could not delete',
297
+ title: tr('board.toast.deleteFailed'),
293
298
  description: e instanceof Error ? e.message : String(e),
294
299
  icon: 'i-lucide-triangle-alert',
295
300
  color: 'error',
@@ -313,26 +318,65 @@ export const useBoardStore = defineStore('board', () => {
313
318
  async function moveBlock(id: string, position: { x: number; y: number }) {
314
319
  const b = getBlock(id)
315
320
  if (!b) return
321
+ const prevPosition = b.position
316
322
  b.position = position // optimistic: keep the drag feeling instant
317
- // A mounted service frame's position is a PER-WORKSPACE layout override on the mount, not
318
- // on the (shared) block so route a frame drag there. Other moves write the block.
319
- const services = useServicesStore()
320
- const mount = services.serviceByFrameBlock[id]
321
- ? services.byServiceId[services.serviceByFrameBlock[id]!.id]
322
- : undefined
323
- if (mount) {
324
- await services.updateLayout(mount.serviceId, position)
325
- return
323
+ try {
324
+ // A mounted service frame's position is a PER-WORKSPACE layout override on the mount, not
325
+ // on the (shared) block — so route a frame drag there. Other moves write the block.
326
+ const services = useServicesStore()
327
+ const mount = services.serviceByFrameBlock[id]
328
+ ? services.byServiceId[services.serviceByFrameBlock[id]!.id]
329
+ : undefined
330
+ if (mount) {
331
+ await services.updateLayout(mount.serviceId, position)
332
+ return
333
+ }
334
+ upsert(await api.moveBlock(useWorkspaceStore().requireId(), id, { position }))
335
+ } catch (e) {
336
+ // Restore the pre-drag position — a rejected move must not leave the block at a
337
+ // spot the server never stored (a lie that survives until the next re-hydrate).
338
+ b.position = prevPosition
339
+ toast.add({
340
+ title: 'Could not move',
341
+ description: e instanceof Error ? e.message : String(e),
342
+ icon: 'i-lucide-triangle-alert',
343
+ color: 'error',
344
+ })
326
345
  }
327
- upsert(await api.moveBlock(useWorkspaceStore().requireId(), id, { position }))
328
346
  }
329
347
 
330
348
  /** Patch the user-editable fields of a block (title, features, threshold…). */
331
349
  async function updateBlock(id: string, patch: UpdateBlockInput) {
332
350
  const b = getBlock(id)
333
351
  if (!b) return
352
+ // Snapshot ONLY the fields this patch touches so a rejected write restores them exactly
353
+ // (a patch may set several at once) rather than leaving a stale optimistic value stuck on
354
+ // screen with no feedback — the same rollback contract the other mutations here follow.
355
+ const prev: Record<string, unknown> = {}
356
+ const patchRecord = patch as Record<string, unknown>
357
+ const record = b as unknown as Record<string, unknown>
358
+ for (const key of Object.keys(patch)) prev[key] = record[key]
334
359
  Object.assign(b, patch) // optimistic
335
- upsert(await api.updateBlock(useWorkspaceStore().requireId(), id, patch))
360
+ try {
361
+ upsert(await api.updateBlock(useWorkspaceStore().requireId(), id, patch))
362
+ } catch (e) {
363
+ // Re-resolve the block: a live event may have replaced its object reference (`upsert`
364
+ // swaps in a fresh one) while the write was in flight, so `b` can be stale. Only revert
365
+ // fields that still hold OUR optimistic value, so a newer server value that landed
366
+ // mid-flight isn't clobbered by the rollback.
367
+ const cur = getBlock(id) as unknown as Record<string, unknown> | undefined
368
+ if (cur) {
369
+ for (const key of Object.keys(patch)) {
370
+ if (cur[key] === patchRecord[key]) cur[key] = prev[key]
371
+ }
372
+ }
373
+ toast.add({
374
+ title: tr('board.toast.updateFailed'),
375
+ description: e instanceof Error ? e.message : String(e),
376
+ icon: 'i-lucide-triangle-alert',
377
+ color: 'error',
378
+ })
379
+ }
336
380
  }
337
381
 
338
382
  /**
@@ -346,7 +390,7 @@ export const useBoardStore = defineStore('board', () => {
346
390
  upsert(await api.toggleDependency(useWorkspaceStore().requireId(), targetId, { sourceId }))
347
391
  } catch (e) {
348
392
  toast.add({
349
- title: 'Could not link tasks',
393
+ title: tr('board.toast.linkFailed'),
350
394
  description: e instanceof Error ? e.message : String(e),
351
395
  icon: 'i-lucide-triangle-alert',
352
396
  color: 'error',
@@ -0,0 +1,35 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import type { BrainstormSession } from '~/types/brainstorm'
3
+ import { useBrainstormStore } from '~/stores/brainstorm'
4
+
5
+ /** Minimal session factory — only the fields the upsert guard touches. */
6
+ function session(over: Partial<BrainstormSession> = {}): BrainstormSession {
7
+ return {
8
+ id: 'bs1',
9
+ blockId: 'b1',
10
+ stage: 'requirements',
11
+ status: 'ready',
12
+ options: [],
13
+ updatedAt: 1000,
14
+ ...over,
15
+ } as BrainstormSession
16
+ }
17
+
18
+ describe('brainstorm store live-event upsert guard', () => {
19
+ it('an out-of-order stream event cannot revert a newer cached session', () => {
20
+ const store = useBrainstormStore()
21
+ store.upsert(session({ updatedAt: 2000, status: 'merged' }))
22
+ store.upsert(session({ updatedAt: 1000, status: 'ready' })) // stale event → ignored
23
+ expect(store.sessionFor('b1', 'requirements')?.status).toBe('merged')
24
+ store.upsert(session({ updatedAt: 3000, status: 'incorporated' }))
25
+ expect(store.sessionFor('b1', 'requirements')?.status).toBe('incorporated')
26
+ })
27
+
28
+ it('sessions are keyed per block+stage — one stage cannot clobber another', () => {
29
+ const store = useBrainstormStore()
30
+ store.upsert(session({ updatedAt: 2000 }))
31
+ store.upsert(session({ id: 'bs2', stage: 'architecture', updatedAt: 1000 }))
32
+ expect(store.sessionFor('b1', 'requirements')?.id).toBe('bs1')
33
+ expect(store.sessionFor('b1', 'architecture')?.id).toBe('bs2')
34
+ })
35
+ })
@@ -84,6 +84,16 @@ export const useBrainstormStore = defineStore('brainstorm', () => {
84
84
  sessions.value = { ...sessions.value, [key(session.blockId, session.stage)]: session }
85
85
  }
86
86
 
87
+ /** Patch the cache from a live `brainstorm` stream event (newest wins per block+stage). */
88
+ function upsert(session: BrainstormSession) {
89
+ const existing = sessions.value[key(session.blockId, session.stage)]
90
+ // Keep the freshest by updatedAt (the consensus-store guard): `store()` also runs on
91
+ // API responses, so a slightly-older event racing a just-submitted answer over the
92
+ // separate WS transport must not revert the session the response already delivered.
93
+ if (existing && existing.id === session.id && existing.updatedAt > session.updatedAt) return
94
+ store(session)
95
+ }
96
+
87
97
  /** Drop all cached sessions + in-flight state (called on workspace switch). */
88
98
  function reset() {
89
99
  available.value = null
@@ -215,7 +225,6 @@ export const useBrainstormStore = defineStore('brainstorm', () => {
215
225
  proceed,
216
226
  resolveExceeded,
217
227
  reset,
218
- // Patch the cache from a live `brainstorm` stream event.
219
- upsert: store,
228
+ upsert,
220
229
  }
221
230
  })
@@ -0,0 +1,33 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import type { ClarityReview } from '~/types/clarity'
3
+ import { useClarityStore } from '~/stores/clarity'
4
+
5
+ /** Minimal review factory — only the fields the upsert guard touches. */
6
+ function review(over: Partial<ClarityReview> = {}): ClarityReview {
7
+ return {
8
+ id: 'cr1',
9
+ blockId: 'b1',
10
+ status: 'ready',
11
+ items: [],
12
+ updatedAt: 1000,
13
+ ...over,
14
+ } as ClarityReview
15
+ }
16
+
17
+ describe('clarity store live-event upsert guard', () => {
18
+ it('an out-of-order stream event cannot revert a newer cached review', () => {
19
+ const store = useClarityStore()
20
+ store.upsert(review({ updatedAt: 2000, status: 'merged' }))
21
+ store.upsert(review({ updatedAt: 1000, status: 'ready' })) // stale event → ignored
22
+ expect(store.reviewFor('b1')?.status).toBe('merged')
23
+ store.upsert(review({ updatedAt: 3000, status: 'incorporated' }))
24
+ expect(store.reviewFor('b1')?.status).toBe('incorporated')
25
+ })
26
+
27
+ it('a NEW review (different id) for the block replaces regardless of updatedAt', () => {
28
+ const store = useClarityStore()
29
+ store.upsert(review({ updatedAt: 2000 }))
30
+ store.upsert(review({ id: 'cr2', updatedAt: 1000 }))
31
+ expect(store.reviewFor('b1')?.id).toBe('cr2')
32
+ })
33
+ })
@@ -87,6 +87,16 @@ export const useClarityStore = defineStore('clarity', () => {
87
87
  reviews.value = { ...reviews.value, [review.blockId]: review }
88
88
  }
89
89
 
90
+ /** Patch the cache from a live `clarity` stream event (newest wins per block). */
91
+ function upsert(review: ClarityReview) {
92
+ const existing = reviews.value[review.blockId]
93
+ // Keep the freshest by updatedAt (the consensus-store guard): `store()` also runs on
94
+ // API responses, so a slightly-older event racing a just-submitted answer over the
95
+ // separate WS transport must not revert the review the response already delivered.
96
+ if (existing && existing.id === review.id && existing.updatedAt > review.updatedAt) return
97
+ store(review)
98
+ }
99
+
90
100
  /** Drop all cached reviews + in-flight state (called on workspace switch). */
91
101
  function reset() {
92
102
  available.value = null
@@ -205,7 +215,6 @@ export const useClarityStore = defineStore('clarity', () => {
205
215
  proceed,
206
216
  resolveExceeded,
207
217
  reset,
208
- // Patch the cache from a live `clarity` stream event.
209
- upsert: store,
218
+ upsert,
210
219
  }
211
220
  })
@@ -18,26 +18,84 @@ describe('execution store gate grouping', () => {
18
18
  })
19
19
 
20
20
  it('decisionsByBlock groups open (unchosen) decisions by block', () => {
21
- store.hydrate([
22
- instance('e1', 'b1', [
23
- { agentKind: 'coder', decision: { id: 'd1', chosen: null } },
24
- { agentKind: 'coder', decision: { id: 'd2', chosen: 'yes' } }, // chosen ⇒ excluded
25
- ]),
26
- instance('e2', 'b2', [{ agentKind: 'architect', decision: { id: 'd3', chosen: null } }]),
27
- ])
21
+ store.hydrate(
22
+ [
23
+ instance('e1', 'b1', [
24
+ { agentKind: 'coder', decision: { id: 'd1', chosen: null } },
25
+ { agentKind: 'coder', decision: { id: 'd2', chosen: 'yes' } }, // chosen ⇒ excluded
26
+ ]),
27
+ instance('e2', 'b2', [{ agentKind: 'architect', decision: { id: 'd3', chosen: null } }]),
28
+ ],
29
+ 'ws1',
30
+ )
28
31
  expect(store.decisionsByBlock.get('b1')?.map((d) => d.decision.id)).toEqual(['d1'])
29
32
  expect(store.decisionsByBlock.get('b2')?.map((d) => d.decision.id)).toEqual(['d3'])
30
33
  expect(store.decisionsByBlock.has('missing')).toBe(false)
31
34
  })
32
35
 
33
36
  it('approvalsByBlock groups pending approvals by block', () => {
34
- store.hydrate([
35
- instance('e1', 'b1', [
36
- { agentKind: 'merger', approval: { id: 'a1', status: 'pending' } },
37
- { agentKind: 'merger', approval: { id: 'a2', status: 'approved' } }, // not pending ⇒ excluded
38
- ]),
39
- ])
37
+ store.hydrate(
38
+ [
39
+ instance('e1', 'b1', [
40
+ { agentKind: 'merger', approval: { id: 'a1', status: 'pending' } },
41
+ { agentKind: 'merger', approval: { id: 'a2', status: 'approved' } }, // not pending ⇒ excluded
42
+ ]),
43
+ ],
44
+ 'ws1',
45
+ )
40
46
  expect(store.approvalsByBlock.get('b1')?.map((a) => a.approval.id)).toEqual(['a1'])
41
47
  expect(store.approvalsByBlock.get('b2')).toBeUndefined()
42
48
  })
43
49
  })
50
+
51
+ /** A run fixture carrying the fields the reconcile guards read (`id`, `rev`, `status`). */
52
+ function run(id: string, rev: number, status: string): ExecutionInstance {
53
+ return { id, blockId: `blk_${id}`, steps: [], status, rev } as unknown as ExecutionInstance
54
+ }
55
+
56
+ describe('execution store snapshot/event reconcile', () => {
57
+ let store: ReturnType<typeof useExecutionStore>
58
+ beforeEach(() => {
59
+ store = useExecutionStore()
60
+ })
61
+
62
+ it('a lagging snapshot cannot regress a run a live event already advanced (REGRESS)', () => {
63
+ store.hydrate([run('e1', 3, 'running')], 'ws1')
64
+ // Live event: the run reached a terminal state (rev 4). It emits nothing further.
65
+ store.upsert(run('e1', 4, 'done'))
66
+ // A snapshot read BEFORE the event resolves after it — same run at the older rev.
67
+ store.hydrate([run('e1', 3, 'running')], 'ws1')
68
+ expect(store.getInstance('e1')?.status).toBe('done')
69
+ })
70
+
71
+ it('keeps a live-added run a lagging snapshot never saw (DROP)', () => {
72
+ store.hydrate([run('e1', 1, 'running')], 'ws1')
73
+ store.upsert(run('e2', 1, 'running'))
74
+ store.hydrate([run('e1', 2, 'running')], 'ws1') // stale read: predates e2
75
+ expect(store.getInstance('e2')).toBeTruthy()
76
+ expect(store.getInstance('e1')?.rev).toBe(2)
77
+ })
78
+
79
+ it('a workspace switch replaces the cache outright (no cross-board leak)', () => {
80
+ store.hydrate([run('e1', 1, 'running')], 'ws1')
81
+ store.upsert(run('e2', 1, 'running'))
82
+ store.hydrate([run('e3', 1, 'running')], 'ws2')
83
+ expect(store.getInstance('e1')).toBeUndefined()
84
+ expect(store.getInstance('e2')).toBeUndefined()
85
+ expect(store.getInstance('e3')).toBeTruthy()
86
+ })
87
+
88
+ it('an out-of-order live event cannot regress a newer cached run; same-rev replaces', () => {
89
+ store.upsert(run('e1', 5, 'done'))
90
+ store.upsert(run('e1', 4, 'running')) // stale event → ignored
91
+ expect(store.getInstance('e1')?.status).toBe('done')
92
+ store.upsert(run('e1', 5, 'failed')) // equal rev → latest event wins
93
+ expect(store.getInstance('e1')?.status).toBe('failed')
94
+ })
95
+
96
+ it('treats a missing rev as 0 (legacy rows still hydrate)', () => {
97
+ store.hydrate([{ id: 'e1', blockId: 'b1', steps: [], status: 'running' } as never], 'ws1')
98
+ store.upsert(run('e1', 1, 'done'))
99
+ expect(store.getInstance('e1')?.status).toBe('done')
100
+ })
101
+ })
@@ -25,17 +25,55 @@ export const useExecutionStore = defineStore('execution', () => {
25
25
  // gets identical handling, including the fire-and-forget ones that never caught.
26
26
  const runErrors = usePipelineErrorToast()
27
27
  const instances = ref<ExecutionInstance[]>([])
28
+ // The workspace whose snapshot last hydrated the cache. Scopes the DROP-preservation
29
+ // below: a board SWITCH replaces the cache outright instead of leaking the previous
30
+ // board's runs (an ExecutionInstance carries no workspaceId of its own).
31
+ let hydratedWorkspaceId: string | null = null
28
32
 
29
- /** Replace the cached executions with a server snapshot. */
30
- function hydrate(next: ExecutionInstance[]) {
31
- instances.value = next
33
+ /** A run's monotonic server revision (bumped on every persisted write; absent = 0). */
34
+ function revOf(e: ExecutionInstance): number {
35
+ return e.rev ?? 0
32
36
  }
33
37
 
34
- /** Insert or replace a single execution instance pushed by the event stream. */
38
+ /**
39
+ * Reconcile the cached executions with a server snapshot for `workspaceId`. A snapshot
40
+ * is authoritative EXCEPT where a live `execution` event already advanced (or ADDED) a
41
+ * run past what this (possibly stale) read observed — the same two clobber hazards the
42
+ * `agentRuns` store guards, keyed here on the run's monotonic `rev`:
43
+ * - REGRESS: a run present in BOTH — keep the newer-by-`rev` version, so a lagging
44
+ * refresh (the stream's on-(re)connect resync, the debounced `board`-event refetch)
45
+ * can't revert a just-terminal run to `running`. A terminal run emits nothing
46
+ * further, so a regression here would strand the UI until an unrelated refresh.
47
+ * - DROP: a run a live event just ADDED that the (older) snapshot never saw — keep it
48
+ * rather than silently dropping it.
49
+ */
50
+ function hydrate(next: ExecutionInstance[], workspaceId: string) {
51
+ const sameWorkspace = hydratedWorkspaceId === workspaceId
52
+ hydratedWorkspaceId = workspaceId
53
+ if (!sameWorkspace) {
54
+ instances.value = next
55
+ return
56
+ }
57
+ const incomingIds = new Set(next.map((e) => e.id))
58
+ const held = new Map(instances.value.map((e) => [e.id, e]))
59
+ const reconciled = next.map((incoming) => {
60
+ const current = held.get(incoming.id)
61
+ return current && revOf(current) > revOf(incoming) ? current : incoming
62
+ })
63
+ const preserved = [...held.values()].filter((e) => !incomingIds.has(e.id))
64
+ instances.value = [...reconciled, ...preserved]
65
+ }
66
+
67
+ /**
68
+ * Insert or replace a single execution instance pushed by the event stream.
69
+ * Monotonic by `rev`: an out-of-order/stale event can't regress a run a newer
70
+ * write already advanced (same guard as {@link hydrate}).
71
+ */
35
72
  function upsert(instance: ExecutionInstance) {
36
73
  const i = instances.value.findIndex((e) => e.id === instance.id)
37
- if (i >= 0) instances.value[i] = instance
38
- else instances.value.push(instance)
74
+ if (i >= 0) {
75
+ if (revOf(instance) >= revOf(instances.value[i]!)) instances.value[i] = instance
76
+ } else instances.value.push(instance)
39
77
  }
40
78
 
41
79
  const byId = computed(() => {