diff --git a/src/main/github/github-issue-link-title-fill.test.ts b/src/main/github/github-issue-link-title-fill.test.ts index 02421afa866..f70b9c2520e 100644 --- a/src/main/github/github-issue-link-title-fill.test.ts +++ b/src/main/github/github-issue-link-title-fill.test.ts @@ -26,11 +26,11 @@ async function setup(readIssueTitle: () => Promise) { writeDataFile({ repos: [makeRepo({ id: 'repo', path: '/work' })] }) const store = await createStore() const pending: (() => void)[] = [] - const notifyChanged = vi.fn() + const publish = vi.fn() installGitHubIssueLinkTitleFill({ store, readIssueTitle, - notifyChanged, + publish, schedule: (run) => pending.push(run) }) const settle = async (): Promise => { @@ -40,7 +40,7 @@ async function setup(readIssueTitle: () => Promise) { await vi.waitFor(() => expect(readIssueTitle).toHaveBeenCalled()) await new Promise((resolve) => setImmediate(resolve)) } - return { store, settle, notifyChanged } + return { store, settle, publish } } describe('GitHub issue link title fill', () => { @@ -53,7 +53,7 @@ describe('GitHub issue link title fill', () => { }) it('titles a bare linked issue without re-selecting a review the user had cleared', async () => { - const { store, settle, notifyChanged } = await setup(vi.fn(async () => 'Repair authentication')) + const { store, settle, publish } = await setup(vi.fn(async () => 'Repair authentication')) // A kept merge request with no review selected, as after the user clears the selection. store.setWorktreeMeta(target, { linkedItems: [{ provider: 'gitlab', type: 'mr', number: 5 }], @@ -78,7 +78,9 @@ describe('GitHub issue link title fill', () => { ) expect(meta?.linkedIssue).toBe(42) expect(meta?.linkedGitLabMR ?? null).toBeNull() - await vi.waitFor(() => expect(notifyChanged).toHaveBeenCalledWith('repo')) + expect(publish).toHaveBeenCalledWith( + expect.objectContaining({ worktreeId: 'repo::/work', hostId: 'local' }) + ) }) it('keeps a hidden branch PR hidden when titling a link beside the selected PR', async () => { diff --git a/src/main/github/github-issue-link-title-fill.ts b/src/main/github/github-issue-link-title-fill.ts index d7a2defab71..ec845d6a2b7 100644 --- a/src/main/github/github-issue-link-title-fill.ts +++ b/src/main/github/github-issue-link-title-fill.ts @@ -24,9 +24,6 @@ export type GitHubIssueLinkTitleFillStore = { getRepos: () => Repo[] } -// Each publication refreshes the repo's whole workspace list in every client. -const NOTIFY_WINDOW_MS = 30_000 - type Job = { worktreeId: string hostId: ExecutionHostId @@ -48,7 +45,8 @@ function untitledGitHubIssues(meta: WorktreeMeta | undefined): WorkspaceAttachme export function installGitHubIssueLinkTitleFill(deps: { store: GitHubIssueLinkTitleFillStore readIssueTitle: (repo: Repo, link: WorkspaceAttachment) => Promise - notifyChanged: (repoId: string) => void + // Addressed to the one workspace whose links changed; never a repo-wide refresh. + publish: (change: { worktreeId: string; hostId: ExecutionHostId; meta: WorktreeMeta }) => void schedule?: (run: () => void) => void }): () => void { const schedule = deps.schedule ?? ((run) => setImmediate(run)) @@ -56,28 +54,6 @@ export function installGitHubIssueLinkTitleFill(deps: { let draining = false let disposed = false - const pendingNotify = new Set() - let lastNotifyAt = 0 - let notifyTimer: ReturnType | null = null - const flushNotify = (): void => { - notifyTimer = null - lastNotifyAt = Date.now() - for (const repoId of pendingNotify) { - deps.notifyChanged(repoId) - } - pendingNotify.clear() - } - // A quiet host publishes a title at once; a burst publishes at most once per window, never per title. - const scheduleNotify = (repoId: string): void => { - pendingNotify.add(repoId) - if (!notifyTimer) { - notifyTimer = setTimeout( - flushNotify, - Math.max(0, lastNotifyAt + NOTIFY_WINDOW_MS - Date.now()) - ) - } - } - // The job's link as it is now; null once removed, retitled or its workspace re-created. const currentTarget = (job: Job) => { const meta = deps.store.getWorktreeMetaForHost(job.worktreeId, job.hostId) @@ -102,12 +78,15 @@ export function installGitHubIssueLinkTitleFill(deps: { const keepClearedSelection = reviewSlots.every(([slot]) => (meta[slot] ?? null) === null) ? Object.fromEntries(reviewSlots.map(([slot]) => [slot, null])) : {} - deps.store.setWorktreeMeta(hostWorktreeTarget({ id: job.worktreeId, hostId: job.hostId }), { - ...keepClearedSelection, - linkedItemsBase: items, - linkedItems: items.map((item, i) => (i === index ? { ...item, title } : item)) - }) - scheduleNotify(getRepoIdFromWorktreeId(job.worktreeId)) + const updated = deps.store.setWorktreeMeta( + hostWorktreeTarget({ id: job.worktreeId, hostId: job.hostId }), + { + ...keepClearedSelection, + linkedItemsBase: items, + linkedItems: items.map((item, i) => (i === index ? { ...item, title } : item)) + } + ) + deps.publish({ worktreeId: job.worktreeId, hostId: job.hostId, meta: updated }) } const drain = async (): Promise => { @@ -179,9 +158,6 @@ export function installGitHubIssueLinkTitleFill(deps: { }) return () => { disposed = true - if (notifyTimer) { - clearTimeout(notifyTimer) - } queue.clear() unsubscribe() } diff --git a/src/main/github/github-issue-link-title-wiring.ts b/src/main/github/github-issue-link-title-wiring.ts index e666220ca9d..081a6a80bd9 100644 --- a/src/main/github/github-issue-link-title-wiring.ts +++ b/src/main/github/github-issue-link-title-wiring.ts @@ -1,4 +1,11 @@ +import { randomUUID } from 'node:crypto' import type { Repo } from '../../shared/repo-types' +import { composeWorktreeHostIdentity } from '../../shared/worktree/host-qualified-identity' +import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' +import { + workspaceMetadataSetRow, + type WorkspaceMetadataSet +} from '../../shared/worktree/workspace-metadata-set' import type { WorkspaceAttachment } from '../../shared/worktree/types' import { getRepoRoutingConnectionId } from '../../shared/execution-host' import type { Store } from '../persistence/loading-store/store' @@ -61,9 +68,12 @@ export function wireGitHubIssueLinkTitleFill( store: Store, runtime: { invalidateResolvedWorktreeCache: () => void - notifyWorktreesChanged: (repoId: string, options: { invalidateGitScans: false }) => void + publishWorkspaceMetadataSet: (set: WorkspaceMetadataSet) => void } ): () => void { + // This host's workspaceMetadata domain: a new epoch per start, one seq per published record. + const epoch = randomUUID() + let seq = 0 return installGitHubIssueLinkTitleFill({ store, // Background reads never start a stopped WSL distro; the link just stays untitled. @@ -76,10 +86,18 @@ export function wireGitHubIssueLinkTitleFill( wake: false } ), - notifyChanged: (repoId) => { - // Metadata-only change: refresh resolved rows for remote clients without forcing Git rescans. + publish: ({ worktreeId, hostId, meta }) => { + // Resolved rows embed metadata; refresh them so the next listing read agrees. runtime.invalidateResolvedWorktreeCache() - runtime.notifyWorktreesChanged(repoId, { invalidateGitScans: false }) + runtime.publishWorkspaceMetadataSet({ + hostId, + epoch, + seq: ++seq, + id: composeWorktreeHostIdentity(hostId, worktreeId), + repoId: getRepoIdFromWorktreeId(worktreeId), + worktreeId, + row: workspaceMetadataSetRow(meta) + }) } }) } diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index 699cea69893..0715c88c511 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -1,3 +1,4 @@ +import type { WorkspaceMetadataSet } from '../../../../shared/worktree/workspace-metadata-set' import type { RuntimeEditorTabReveal, RuntimeFileOpenPosition @@ -49,6 +50,7 @@ export type RuntimeNotifier = { // Why: false for metadata-only changes (sort order) that leave Git scan results valid. options?: { invalidateGitScans?: boolean } ): void + workspaceMetadataSet?(set: WorkspaceMetadataSet): void worktreeBaseStatus?(event: WorktreeBaseStatusEvent): void worktreeRemoteBranchConflict?(event: WorktreeRemoteBranchConflictEvent): void reposChanged(): void diff --git a/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts b/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts index c589d05f625..3fbe0504e57 100644 --- a/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts +++ b/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts @@ -3,6 +3,7 @@ import type { AutomationsChangedPayload } from '../../../../shared/runtime-clien import { wakeFolderRepoGitUpgradeWatch } from '../../../ipc/folder-repo-git-upgrade-wake' import { runWorktreeChangeInvalidators } from '../../../ipc/worktrees/listing/worktree-change-invalidators' import type { WorktreeSortOrderUpdate } from '../../../../shared/worktree/sort-order-update' +import type { WorkspaceMetadataSet } from '../../../../shared/worktree/workspace-metadata-set' import { NativeChatLaunchDraftOwner } from '../../agent-session/launch/native-chat-launch-draft-owner' export abstract class RuntimeWorkspaceChangeEvents extends NativeChatLaunchDraftOwner { @@ -35,6 +36,12 @@ export abstract class RuntimeWorkspaceChangeEvents extends NativeChatLaunchDraft }) } + /** One workspace's metadata, addressed: clients patch that row instead of refetching its repo. */ + publishWorkspaceMetadataSet(set: WorkspaceMetadataSet): void { + this.notifier?.workspaceMetadataSet?.(set) + this.emitClientEvent({ type: 'workspaceMetadataSet', ...set }) + } + /** Unlike coarse repoId-only changes, lifecycle events name the workspace; removals resolve only id/path before teardown. */ onWorktreeLifecycle(listener: (event: RuntimeWorktreeLifecycleEvent) => void): () => void { return this.worktreeLifecycleEvents.on(listener) diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index b5d40e737b9..bd52f6b33e4 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -45,6 +45,7 @@ export function registerRuntimeWindowLifecycle( } send('worktrees:changed', renamed ? { repoId, renamed } : { repoId }) }, + workspaceMetadataSet: (set) => send('worktrees:metadataSet', set), worktreeBaseStatus: (event) => send('worktree:baseStatus', event), worktreeRemoteBranchConflict: (event) => send('worktree:remoteBranchConflict', event), reposChanged: () => send('repos:changed'), diff --git a/src/preload/api/worktree-api.ts b/src/preload/api/worktree-api.ts index 845020f4a67..c2cb7654a05 100644 --- a/src/preload/api/worktree-api.ts +++ b/src/preload/api/worktree-api.ts @@ -1,3 +1,4 @@ +import type { WorkspaceMetadataSet } from '../../shared/worktree/workspace-metadata-set' import type { SparsePresetFailure } from '../../shared/worktree/sparse-preset-failure' import type { ForgetRemovedWorktreesForExecutionHostArgs, @@ -157,6 +158,7 @@ export type WorktreeApi = { onHeadIdentitiesChanged: ( callback: (data: { repoId: string; identities: WorktreeHeadIdentity[] }) => void ) => () => void + onMetadataSet?: (callback: (set: WorkspaceMetadataSet) => void) => () => void onBaseStatus: (callback: (data: WorktreeBaseStatusEvent) => void) => () => void onRemoteBranchConflict: ( callback: (data: WorktreeRemoteBranchConflictEvent) => void diff --git a/src/preload/api/worktrees-bridge.ts b/src/preload/api/worktrees-bridge.ts index 7106dc7c4a3..9bbfb55fed1 100644 --- a/src/preload/api/worktrees-bridge.ts +++ b/src/preload/api/worktrees-bridge.ts @@ -9,6 +9,7 @@ import type { WorktreeHeadIdentity } from '../../shared/worktree/types' import type { PreloadApi } from '../api-types' +import type { WorkspaceMetadataSet } from '../../shared/worktree/workspace-metadata-set' export const worktreesApi = { listRetiredNames: (args) => ipcRenderer.invoke('worktrees:listRetiredNames', args), @@ -105,6 +106,12 @@ export const worktreesApi = { return () => ipcRenderer.removeListener('worktrees:headIdentitiesChanged', listener) }, + onMetadataSet: (callback: (set: WorkspaceMetadataSet) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, set: WorkspaceMetadataSet) => callback(set) + ipcRenderer.on('worktrees:metadataSet', listener) + return () => ipcRenderer.removeListener('worktrees:metadataSet', listener) + }, + onBaseStatus: (callback: (data: WorktreeBaseStatusEvent) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, data: WorktreeBaseStatusEvent) => callback(data) diff --git a/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts index bb8c5e32b3f..8981c5646f4 100644 --- a/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts @@ -1,3 +1,4 @@ +import { applyLocalWorktreeMetadataSet } from './worktree-metadata-set-events' import { applyWorktreeHeadIdentities } from '../worktree-head-identity-apply' import type { WorktreeChangeRefreshQueue } from '../worktree-change-refresh-queue' import { useAppStore } from '../../store' @@ -46,6 +47,10 @@ export function registerProjectCatalogIpcBridge( ) ) + if (window.api.worktrees.onMetadataSet) { + unsubs.push(window.api.worktrees.onMetadataSet(applyLocalWorktreeMetadataSet)) + } + if (window.api.worktrees.onHeadIdentitiesChanged) { unsubs.push( window.api.worktrees.onHeadIdentitiesChanged((data) => { diff --git a/src/renderer/src/hooks/ipc-events/worktree-metadata-set-events.ts b/src/renderer/src/hooks/ipc-events/worktree-metadata-set-events.ts new file mode 100644 index 00000000000..855b50b913a --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/worktree-metadata-set-events.ts @@ -0,0 +1,21 @@ +import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' +import { readWorkspaceMetadataSet } from '../../../../shared/worktree/workspace-metadata-set' +import { useAppStore } from '../../store' +import { patchWorktreeMetadataSet } from '../../store/slices/worktrees/listing/worktree-metadata-set-patch' + +/** This app's own host: the record names the host its row lives on. */ +export function applyLocalWorktreeMetadataSet(record: unknown): void { + const set = readWorkspaceMetadataSet(record) + if (set) { + useAppStore.setState((state) => patchWorktreeMetadataSet(state, set, set.hostId)) + } +} + +/** A paired host's record: its rows live here under that environment's host id. */ +export function applyEnvironmentWorktreeMetadataSet(environmentId: string, record: unknown): void { + const set = readWorkspaceMetadataSet(record) + if (set) { + const hostId = toRuntimeExecutionHostId(environmentId) + useAppStore.setState((state) => patchWorktreeMetadataSet(state, set, hostId)) + } +} diff --git a/src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.ts b/src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.ts index 48eecbbd24f..293a92c883d 100644 --- a/src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.ts +++ b/src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.ts @@ -1,3 +1,4 @@ +import { applyEnvironmentWorktreeMetadataSet } from '../../../hooks/ipc-events/worktree-metadata-set-events' import type { RuntimeClientEvent, RuntimeClientEventStreamMessage @@ -77,6 +78,10 @@ function handleRuntimeClientEventResponse( if (message.type === 'end') { return } + if (message.type === 'workspaceMetadataSet') { + applyEnvironmentWorktreeMetadataSet(environmentId, message) + return + } if (message.type === 'browserHostRequested') { void answerBrowserClientHostRequest(environmentId, message.requestId) return diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.test.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.test.ts new file mode 100644 index 00000000000..6bfd0065e29 --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import type { WorkspaceAttachment } from '../../../../../../shared/worktree/types' +import { useAppStore } from '../../..' +import { + makeRepo, + makeWorktree +} from '../../../../components/worktree-jump/worktree-jump-palette-test-fixtures' +import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' +import { patchWorktreeMetadataSet } from './worktree-metadata-set-patch' + +const ID = 'repo-1::/work/orca' +const titled = (title: string): WorkspaceAttachment[] => [ + { provider: 'github', type: 'issue', number: 42, title } +] + +function state() { + return { + ...useAppStore.getInitialState(), + repos: [makeRepo()], + worktreesByRepo: { + 'repo-1': [ + makeWorktree(ID, 'local orca', { hostId: 'local', linkedIssue: 42 }), + makeWorktree(ID, 'ssh orca', { hostId: 'ssh:build-box', linkedIssue: 42 }) + ] + } + } +} + +function record(seq: number, title: string, epoch = 'e1') { + return { + hostId: 'ssh:build-box' as const, + epoch, + seq, + id: `ssh:build-box::${ID}`, + repoId: 'repo-1', + worktreeId: ID, + row: { + linkedItems: titled(title), + linkedWorkItem: null, + linkedIssue: 42, + linkedTaskSourceContext: null + } + } +} + +describe('addressed workspace metadata records', () => { + it('update only the named host row and ignore a replayed older record', () => { + const first = patchWorktreeMetadataSet( + state(), + record(2, 'Repair authentication'), + 'ssh:build-box' + ) + const rows = selectWorktreesByRepo({ ...state(), ...first })['repo-1'] + expect(rows.find((row) => row.hostId === 'ssh:build-box')?.linkedItems).toEqual( + titled('Repair authentication') + ) + expect(rows.find((row) => row.hostId === 'local')?.linkedItems).toBeUndefined() + + const applied = { ...state(), ...first } + expect(patchWorktreeMetadataSet(applied, record(1, 'Old title'), 'ssh:build-box')).toBe(applied) + }) +}) diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.ts new file mode 100644 index 00000000000..dd1dc68a7e5 --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.ts @@ -0,0 +1,41 @@ +import type { ExecutionHostId } from '../../../../../../shared/execution-host' +import type { WorkspaceMetadataSet } from '../../../../../../shared/worktree/workspace-metadata-set' +import type { AppState } from '../../../types' +import { worktreeHostMatchOptions, worktreeMatchesHost } from './worktree-host-ownership' +import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' + +// Last applied record per producer stream; a replayed or older record is dropped. +const appliedByProducer = new Map() + +/** + * Applies one producer's addressed `workspaceMetadata` record to the row it names. A row this client + * has not listed yet is left for its next listing, which already carries the same values. + */ +export function patchWorktreeMetadataSet( + state: AppState, + set: WorkspaceMetadataSet, + // The client's own id for the producing host (a paired server's records arrive as its local rows). + hostId: ExecutionHostId +): Pick | AppState { + const last = appliedByProducer.get(hostId) + if (last && last.epoch === set.epoch && set.seq <= last.seq) { + return state + } + appliedByProducer.set(hostId, { epoch: set.epoch, seq: set.seq }) + const listing = selectWorktreesByRepo(state) + const rows = listing[set.repoId] + if (!rows) { + return state + } + const matchOptions = worktreeHostMatchOptions(state, set.repoId, hostId) + const index = rows.findIndex( + (worktree) => + worktree.id === set.worktreeId && worktreeMatchesHost(worktree, hostId, matchOptions) + ) + if (index === -1) { + return state + } + const next = rows.slice() + next[index] = { ...rows[index], ...set.row } + return { worktreesByRepo: { ...listing, [set.repoId]: next } } +} diff --git a/src/renderer/src/web/preload-api/web-worktrees-api.ts b/src/renderer/src/web/preload-api/web-worktrees-api.ts index 85a06a72a75..961e52ceb23 100644 --- a/src/renderer/src/web/preload-api/web-worktrees-api.ts +++ b/src/renderer/src/web/preload-api/web-worktrees-api.ts @@ -267,6 +267,7 @@ export function createWorktreesApi(): NonNullable['worktrees onChanged: () => noopUnsubscribe, onGitStatusMetadataChanged: () => noopUnsubscribe, onHeadIdentitiesChanged: () => noopUnsubscribe, + onMetadataSet: () => noopUnsubscribe, onBaseStatus: () => noopUnsubscribe, onRemoteBranchConflict: () => noopUnsubscribe } diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index 65cda9b9c1c..f12d57daf00 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -10,6 +10,7 @@ import type { TerminalSideEffectBatch } from './terminal/output/terminal-side-ef import type { RuntimeNativeChatLaunchDraftResolution } from './runtime-types' import type { RuntimeNavigationTarget } from './runtime-navigation' import type { WorktreeSortOrderUpdate } from './worktree/sort-order-update' +import type { WorkspaceMetadataSet } from './worktree/workspace-metadata-set' import type { SidebarInputsChangedEvent } from './sidebar-list/sidebar-inputs-feed-contract' import type { BrowserClientHostRequestEvent } from './browser/client-hosting/browser-client-host-request-protocol' @@ -38,6 +39,8 @@ export type RuntimeClientEvent = } /** An agent row changed (coalesced, no ids); phones re-read worktree.ps. Sent only while the sidebar feed is off. */ | { type: 'worktreeRowsChanged' } + // Why: addressed workspace metadata; old clients drop the unknown type and see it on their next listing. + | ({ type: 'workspaceMetadataSet' } & WorkspaceMetadataSet) /** What mobileRelay.hosts.list answers changed; phones re-read it instead of polling. */ | { type: 'relayHostsChanged' } /** A desktop PR refresh found this checkout's PR (or its absence) changed; phones re-read it. */ diff --git a/src/shared/worktree/workspace-metadata-set.ts b/src/shared/worktree/workspace-metadata-set.ts new file mode 100644 index 00000000000..bee656edecb --- /dev/null +++ b/src/shared/worktree/workspace-metadata-set.ts @@ -0,0 +1,75 @@ +import { normalizeExecutionHostId, type ExecutionHostId } from '../execution-host' +import { normalizeStoredTaskSourceContext } from '../work-items/task-source-context' +import { normalizeWorkspaceAttachments } from '../workspace-attachments/workspace-attachment-normalization' +import { normalizeWorkspaceLinkedItem } from '../workspace-attachments/workspace-linked-item' +import type { WorktreeMeta } from './meta-types' + +/** The workspace-metadata fields a producer publishes today; the row widens without changing the envelope. */ +export type WorkspaceMetadataSetRow = Pick< + WorktreeMeta, + 'linkedItems' | 'linkedWorkItem' | 'linkedIssue' | 'linkedTaskSourceContext' +> + +/** + * One addressed `set` record in a producer host's `workspaceMetadata` domain: full current values for one + * workspace, ordered by `seq` within `epoch`. A gap, a new epoch or an unknown row falls back to the listing. + */ +export type WorkspaceMetadataSet = { + hostId: ExecutionHostId + epoch: string + seq: number + // Host-qualified worktree identity; repoId and worktreeId route it to the client's listing. + id: string + repoId: string + worktreeId: string + row: WorkspaceMetadataSetRow +} + +export function workspaceMetadataSetRow(meta: WorktreeMeta): WorkspaceMetadataSetRow { + return { + linkedItems: meta.linkedItems, + linkedWorkItem: meta.linkedWorkItem, + linkedIssue: meta.linkedIssue, + linkedTaskSourceContext: meta.linkedTaskSourceContext + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** A well-formed record, or null when an older or malformed producer sent something else. */ +export function readWorkspaceMetadataSet(value: unknown): WorkspaceMetadataSet | null { + if (!isRecord(value) || !isRecord(value.row)) { + return null + } + const { epoch, seq, id, repoId, worktreeId, row } = value + const hostId = normalizeExecutionHostId(typeof value.hostId === 'string' ? value.hostId : null) + if ( + !hostId || + typeof epoch !== 'string' || + typeof seq !== 'number' || + !Number.isSafeInteger(seq) || + typeof id !== 'string' || + typeof repoId !== 'string' || + typeof worktreeId !== 'string' || + !Array.isArray(row.linkedItems) || + (row.linkedIssue !== null && typeof row.linkedIssue !== 'number') + ) { + return null + } + return { + hostId, + epoch, + seq, + id, + repoId, + worktreeId, + row: { + linkedItems: normalizeWorkspaceAttachments(row.linkedItems), + linkedWorkItem: normalizeWorkspaceLinkedItem(row.linkedWorkItem), + linkedIssue: row.linkedIssue, + linkedTaskSourceContext: normalizeStoredTaskSourceContext(row.linkedTaskSourceContext) + } + } +}