From fd20d34362d66dfa96fee60c09769a5a415c75f9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:38:44 -0800 Subject: [PATCH] Save the issue title on GitHub issue links made without one (#40853) * fix(github): title GitHub issue links that were saved without one A workspace linked to a GitHub issue from the CLI (`--issue N`), a phone, the paired web client or a typed number kept only the number, so search could match its issue title only while a client happened to hold that issue. The host that owns the workspace now reads each newly linked untitled issue once, after the write returns, the way its card would, and saves the title on the link. It keeps the current review selection and never resurrects a removed link. * fix(github): bound and publish issue-title fills like other metadata writes Skip writes that leave links untouched before normalizing, check a queued link is still wanted before reading it, publish filled titles once per repo per 2 s window, refresh the resolved rows remote clients read, never wake a stopped WSL distro for a background read, keep a selected review's PR suppression, and keep a failing write observer from failing a saved write. * fix(github): keep link-title fills off unrelated writes and out of per-title refreshes Ignore linkedWorkItem in the unchanged-links check (it is rebuilt on every write and always titled), publish filled titles at once on a quiet host and at most once per repo per 30 s during a burst on a timer, and only lift a PR suppression when the selected PR changes, so restating the current PR (as a title fill does) keeps a hidden branch PR hidden. * perf(github): publish filled link titles as addressed workspace metadata Instead of a whole-repo worktreesChanged refresh per burst window, the host publishes one addressed workspaceMetadata set record {hostId, epoch, seq, id, row} for the workspace whose link was titled: to its desktop window over IPC and to paired clients as a runtime client event. Clients patch that one row (Cmd-J reads it) and drop replayed records; older clients ignore the new event and see the title on their next listing. * fix(github): agreed workspaceMetadata record shape, per-id seqs and late-listing refill Records name their kind and domain, clients keep the last applied seq per workspace for each producer epoch (dropped when the epoch changes), and a listing that read metadata before the title write cannot drop the title: recorded titles refill rows that still hold the same untitled link for 60 s, never restoring a removed link. The IPC channel is marked as interim transport. * fix(github): title-only, host-addressed application of workspaceMetadata records Clients fill the record's issue titles into the named row's still-untitled links and never take its links over the row's current ones, so a record that arrives after an unlink cannot restore the issue. A paired host's records reach the row of their own execution host (an SSH twin is a different row), and go through the bridge's connection-generation check like other host events. * test(github): type the metadata-record test helper as AppState * fix(github): keep recorded titles until expiry, refill only changed repos, retire with the pairing A record that beats the listing adding its link keeps its titles for the full window; the refill runs only for repos whose listing changed, indexes that repo's rows once and skips rows already checked; per-workspace seqs live in the expiring entries; a re-pair or reconnect of the producing environment retires its titles. * fix(github): read the listing through the workspace record selector * fix(github): keep link titles until their producer changes; fall back to a listing on eviction Recorded issue titles no longer expire on a timer (a slow listing could outlast it): they live until the producer's epoch, pairing or connection changes, refilling only present untitled links. When more than the cap are in flight the oldest is evicted and its repo is listed afresh, which carries the saved title. The refill runs in updater form so it never merges a stale store snapshot. * fix(github): sequenced listings replace the retained-title refill Per the re-plan ruling: the store keeps one workspaceMetadata cursor per process; a title record takes the next seq in the same turn as its write, and each listing records the cursor when it reads metadata. Clients note each record's seq per producer and repo; a listing at or past it ends the obligation, an older one keeps titles the rows already show and lists the repo afresh (a new invocation, never joining the stale one), a record whose row or link isn't listed yet asks for a fresh listing, and a seq gap lists every repo of that producer. The retained-title table, its watcher, TTL and cap are gone. * test(github): stamp capture, gap, restart and recovery coverage for workspace metadata listings Also retire an environment's earlier coverage bookkeeping when it is re-paired or reconnects. * fix(space): keep issue-title coverage per repo and host until a newer listing lands Coverage now keeps each projection's newest record seq after its covering listing settles, so an older listing that finishes later still keeps shown titles. Projections are keyed by repo and host, paired producers keep their stream cursor, retired pairings and unlisted projections are dropped, every listing served by this host carries its metadata stamp, and a record with any unlisted titled link asks for a listing. * fix(space): re-list after any stale listing and drop retired metadata producers A stale listing now always asks for one fresh listing, so a link it dropped comes back and a failed scan can no longer end the wait. Removed environments drop their producer state, the producer's repo list is built only on a gap or a first-seen projection, and recovery listings skip the lineage refresh. * perf(space): filter current rows only for listings that keep titles * fix(space): forget removed repos on a metadata gap; keep titles for another producer run's listing * fix(palette): search a linked issue by its saved title before its card renders The issue's search entry took its title only from the issue cache, which fills when the card renders, and it shadowed the saved link's titled entry under the same id. It now falls back to the link's saved title. * perf(palette): read a row's links once per palette document * fix(palette): give each saved link its own search unit Saved-link evidence was meant to carry an `attachment:` id but the override set an unused field, so a link shared the `issue:N` unit id with the legacy issue field and with same-number links from other repos, and only the first (often untitled) survived. The id now applies to the unit and its fields, so every saved link's title is searchable. Replaces the cache-title fallback. * fix(space): keep the title queue draining past a failed link; encode environment ids in coverage keys --------- --- .../github-issue-link-title-fill.test.ts | 114 +++++++++ .../github/github-issue-link-title-fill.ts | 166 +++++++++++++ .../github/github-issue-link-title-wiring.ts | 103 ++++++++ ...d-provider-listing-catalog-version.test.ts | 27 +- .../listing/detected-provider-listing.ts | 26 +- src/main/orcad/orcad-entry.ts | 2 + .../loading-store/store-runtime-state.ts | 6 +- .../worktree-identity-metadata.ts | 11 +- .../worktree-meta-write-normalization.ts | 2 +- .../loading-store/write-scheduling.ts | 32 +++ .../events/runtime-notifier-contract.ts | 2 + .../construction/runtime-store-contract.ts | 1 + .../catalog/runtime-listing-metadata.ts | 28 +++ .../runtime-managed-worktree-queries.ts | 16 +- .../runtime-workspace-change-events.ts | 7 + .../startup/main-process-runtime-service.ts | 4 + src/main/window/runtime-window-lifecycle.ts | 2 + src/preload/api/worktree-api.ts | 2 + src/preload/api/worktrees-bridge.ts | 7 + .../ipc-events/project-catalog-ipc-bridge.ts | 5 + .../ipc-events/runtime-client-ipc-bridge.ts | 5 +- .../worktree-metadata-set-events.ts | 98 ++++++++ .../worktrees/worktree-palette-document.ts | 14 +- .../worktrees/worktree-palette-search.test.ts | 30 +++ .../subscriptions/runtime-client-events.ts | 1 + .../detected-worktree-refresh-leases.ts | 23 +- .../listing/detected-worktree-refresh.ts | 25 +- .../worktrees/listing/fetch-all-worktrees.ts | 7 +- .../worktrees/listing/fetch-worktrees.ts | 10 +- .../workspace-metadata-coverage.test.ts | 76 ++++++ .../listing/workspace-metadata-coverage.ts | 235 ++++++++++++++++++ .../listing/workspace-metadata-recovery.ts | 40 +++ .../listing/worktree-fetch-options.ts | 2 + .../worktree-metadata-set-patch.test.ts | 124 +++++++++ .../listing/worktree-metadata-set-patch.ts | 83 +++++++ .../worktrees/listing/worktree-slice-types.ts | 2 + .../metadata/update-worktree-meta.ts | 3 +- .../src/web/preload-api/web-worktrees-api.ts | 1 + src/shared/runtime-client-events.ts | 3 + src/shared/worktree/github-pr-suppression.ts | 8 +- src/shared/worktree/types.ts | 2 + src/shared/worktree/workspace-metadata-set.ts | 84 +++++++ 42 files changed, 1392 insertions(+), 47 deletions(-) create mode 100644 src/main/github/github-issue-link-title-fill.test.ts create mode 100644 src/main/github/github-issue-link-title-fill.ts create mode 100644 src/main/github/github-issue-link-title-wiring.ts create mode 100644 src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts create mode 100644 src/renderer/src/hooks/ipc-events/worktree-metadata-set-events.ts create mode 100644 src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.test.ts create mode 100644 src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.ts create mode 100644 src/renderer/src/store/slices/worktrees/listing/workspace-metadata-recovery.ts create mode 100644 src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.test.ts create mode 100644 src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.ts create mode 100644 src/shared/worktree/workspace-metadata-set.ts diff --git a/src/main/github/github-issue-link-title-fill.test.ts b/src/main/github/github-issue-link-title-fill.test.ts new file mode 100644 index 00000000000..f70b9c2520e --- /dev/null +++ b/src/main/github/github-issue-link-title-fill.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { + closeTestStores, + createStore, + makeRepo, + testState, + writeDataFile +} from '../persistence/persistence-test-harness' +import { getWorkspaceAttachments } from '../../shared/workspace-attachments/workspace-attachments' +import { hostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' +import { installGitHubIssueLinkTitleFill } from './github-issue-link-title-fill' + +vi.mock('electron', () => ({ + app: { getPath: () => testState.dir }, + safeStorage: { isEncryptionAvailable: () => false } +})) +vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) + +const target = hostWorktreeTarget({ id: 'repo::/work', hostId: 'local' }) + +async function setup(readIssueTitle: () => Promise) { + writeDataFile({ repos: [makeRepo({ id: 'repo', path: '/work' })] }) + const store = await createStore() + const pending: (() => void)[] = [] + const publish = vi.fn() + installGitHubIssueLinkTitleFill({ + store, + readIssueTitle, + publish, + schedule: (run) => pending.push(run) + }) + const settle = async (): Promise => { + for (const run of pending.splice(0)) { + run() + } + await vi.waitFor(() => expect(readIssueTitle).toHaveBeenCalled()) + await new Promise((resolve) => setImmediate(resolve)) + } + return { store, settle, publish } +} + +describe('GitHub issue link title fill', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-issue-link-title-')) + }) + afterEach(async () => { + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('titles a bare linked issue without re-selecting a review the user had cleared', async () => { + 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 }], + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null + }) + store.setWorktreeMeta(target, { linkedIssue: 42 }) + expect(store.getWorktreeMetaForHost('repo::/work', 'local')?.linkedGitLabMR ?? null).toBeNull() + await settle() + + const meta = store.getWorktreeMetaForHost('repo::/work', 'local') + expect(getWorkspaceAttachments(meta)).toContainEqual( + expect.objectContaining({ + provider: 'github', + type: 'issue', + number: 42, + title: 'Repair authentication' + }) + ) + expect(meta?.linkedIssue).toBe(42) + expect(meta?.linkedGitLabMR ?? null).toBeNull() + 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 () => { + const { store, settle } = await setup(vi.fn(async () => 'Repair authentication')) + store.setWorktreeMeta(target, { linkedPR: 7 }) + store.setWorktreeMeta(target, { suppressedGitHubPR: 7 }) + store.setWorktreeMeta(target, { linkedIssue: 42 }) + await settle() + + const meta = store.getWorktreeMetaForHost('repo::/work', 'local') + expect(getWorkspaceAttachments(meta)).toContainEqual( + expect.objectContaining({ type: 'issue', number: 42, title: 'Repair authentication' }) + ) + expect(meta?.suppressedGitHubPR).toBe(7) + }) + + it('does not bring back a link removed while its title was being read', async () => { + let finish: (title: string) => void = () => {} + const read = vi.fn(() => new Promise((resolve) => (finish = resolve))) + const { store, settle } = await setup(read) + store.setWorktreeMeta(target, { linkedIssue: 42 }) + const settled = settle() + await vi.waitFor(() => expect(read).toHaveBeenCalled()) + store.setWorktreeMeta(target, { linkedIssue: null }) + finish('Repair authentication') + await settled + + const links = getWorkspaceAttachments(store.getWorktreeMetaForHost('repo::/work', 'local')) + expect(links.filter((item) => item.provider === 'github' && item.type === 'issue')).toEqual([]) + }) +}) diff --git a/src/main/github/github-issue-link-title-fill.ts b/src/main/github/github-issue-link-title-fill.ts new file mode 100644 index 00000000000..bea7dcc0f3e --- /dev/null +++ b/src/main/github/github-issue-link-title-fill.ts @@ -0,0 +1,166 @@ +import type { ExecutionHostId } from '../../shared/execution-host' +import type { Repo } from '../../shared/repo-types' +import type { WorktreeMeta } from '../../shared/worktree/meta-types' +import type { WorkspaceAttachment } from '../../shared/worktree/types' +import type { WorkspaceAttachmentMutation } from '../../shared/workspace-attachments/workspace-attachment-mutation' +import { getWorkspaceAttachments } from '../../shared/workspace-attachments/workspace-attachments' +import { WORKSPACE_ATTACHMENT_NUMBER_SLOTS } from '../../shared/workspace-attachments/workspace-attachment-legacy' +import { getWorkspaceReferenceIdentity } from '../../shared/workspace-attachments/workspace-reference-identity' +import { + hostWorktreeTarget, + type HostWorktreeTarget +} from '../../shared/worktree/host-qualified-identity' +import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' +import type { WorktreeMetaWriteListener } from '../persistence/loading-store/write-scheduling' +import { findRepoRowForHostScopedWrite } from '../persistence/tracking-repos/repo-update-operations' + +export type GitHubIssueLinkTitleFillStore = { + onWorktreeMetaWritten: (listener: WorktreeMetaWriteListener) => () => void + getWorktreeMetaForHost: (worktreeId: string, hostId: ExecutionHostId) => WorktreeMeta | undefined + setWorktreeMeta: ( + target: HostWorktreeTarget, + meta: Partial & WorkspaceAttachmentMutation + ) => WorktreeMeta + getRepos: () => Repo[] +} + +type Job = { + worktreeId: string + hostId: ExecutionHostId + instanceId: string | undefined + identity: string + link: WorkspaceAttachment +} + +function untitledGitHubIssues(meta: WorktreeMeta | undefined): WorkspaceAttachment[] { + return getWorkspaceAttachments(meta).filter( + (item) => item.provider === 'github' && item.type === 'issue' && !item.title?.trim() + ) +} + +/** + * Links made without a title (CLI `--issue N`, phones, typed numbers) get the issue's title once, on the + * host that owns the workspace, so search can match it without a client re-reading every linked issue. + */ +export function installGitHubIssueLinkTitleFill(deps: { + store: GitHubIssueLinkTitleFillStore + readIssueTitle: (repo: Repo, link: WorkspaceAttachment) => Promise + // 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)) + const queue = new Map() + let draining = false + let disposed = false + + // 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) + if (!meta || meta.instanceId !== job.instanceId) { + return null + } + const items = getWorkspaceAttachments(meta) + const index = items.findIndex( + (item) => getWorkspaceReferenceIdentity(item) === job.identity && !item.title?.trim() + ) + return index === -1 ? null : { meta, items, index } + } + + const apply = (job: Job, title: string): void => { + const target = currentTarget(job) + if (!target) { + return + } + const { meta, items, index } = target + const reviewSlots = WORKSPACE_ATTACHMENT_NUMBER_SLOTS.filter(([, , type]) => type !== 'issue') + // A cleared review selection must be restated or the merge re-picks one; a set one it keeps. + const keepClearedSelection = reviewSlots.every(([slot]) => (meta[slot] ?? null) === null) + ? Object.fromEntries(reviewSlots.map(([slot]) => [slot, null])) + : {} + 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 => { + if (draining) { + return + } + draining = true + try { + for (const [key, job] of queue) { + queue.delete(key) + if (disposed) { + return + } + try { + const repo = currentTarget(job) + ? findRepoRowForHostScopedWrite( + deps.store.getRepos(), + getRepoIdFromWorktreeId(job.worktreeId), + job.hostId + ) + : undefined + const title = repo ? await deps.readIssueTitle(repo, job.link).catch(() => null) : null + if (title?.trim() && !disposed) { + apply(job, title.trim()) + } + } catch { + // One link whose target changed underneath it (e.g. an alias turned ambiguous) is skipped; + // the rest of the queue still drains. + } + } + } finally { + draining = false + } + } + + const unsubscribe = deps.store.onWorktreeMetaWritten(({ worktreeId, hostId, previous, next }) => { + // Most writes (stamps, flags, comments) leave links untouched; skip them without normalizing. + // linkedWorkItem is re-created on every write and always titled, so it is not compared. + if ( + previous && + previous.instanceId === next.instanceId && + previous.linkedItems === next.linkedItems && + previous.linkedIssue === next.linkedIssue + ) { + return + } + const known = new Set( + previous?.instanceId === next.instanceId + ? untitledGitHubIssues(previous).map(getWorkspaceReferenceIdentity) + : [] + ) + let added = false + for (const link of untitledGitHubIssues(next)) { + const identity = getWorkspaceReferenceIdentity(link) + if (known.has(identity)) { + continue + } + queue.set(JSON.stringify([hostId, worktreeId, next.instanceId, identity]), { + worktreeId, + hostId, + instanceId: next.instanceId, + identity, + link + }) + added = true + } + if (added) { + // Run after the caller's write returns; nothing the user asked for waits on GitHub. + schedule(() => void drain()) + } + }) + return () => { + disposed = true + 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 new file mode 100644 index 00000000000..0c22857efcf --- /dev/null +++ b/src/main/github/github-issue-link-title-wiring.ts @@ -0,0 +1,103 @@ +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' +import { getLocalProjectGhExecOptions } from '../workspaces/execution-host/project-runtime-git-options' +import { getIssue } from './issues' +import { getWorkItemByOwnerRepo } from './client/fetch/get-work-item' +import { installGitHubIssueLinkTitleFill } from './github-issue-link-title-fill' +import { readGitHubRepoUnlessWslStopped } from '../ipc/source-control/github-repo-routing' + +const GITHUB_ISSUE_PATH = /^\/([^/]+)\/([^/]+)\/issues\/(\d+)$/ + +function sameIssueUrl(left: string, right: string): boolean { + try { + const a = new URL(left) + const b = new URL(right) + return ( + a.hostname.toLowerCase() === b.hostname.toLowerCase() && + a.pathname.replace(/\/+$/, '').toLowerCase() === b.pathname.replace(/\/+$/, '').toLowerCase() + ) + } catch { + return false + } +} + +/** Reads a link's issue the way its display does: a URL names its repo; a bare number uses the card's lookup. */ +async function readGitHubIssueLinkTitle( + store: Store, + repo: Repo, + link: WorkspaceAttachment +): Promise { + const connectionId = getRepoRoutingConnectionId(repo) + const options = getLocalProjectGhExecOptions(store, repo) + if (link.url) { + const url = new URL(link.url) + const route = GITHUB_ISSUE_PATH.exec(url.pathname) + if (!route || Number(route[3]) !== link.number) { + return null + } + const item = await getWorkItemByOwnerRepo( + repo.path, + { owner: route[1], repo: route[2], host: url.hostname }, + link.number, + 'issue', + connectionId, + options, + { preview: true } + ) + return item?.type === 'issue' && item.number === link.number && sameIssueUrl(item.url, link.url) + ? item.title + : null + } + const issue = await getIssue(repo.path, link.number, connectionId, options) + // The issues endpoint also answers PR numbers; a PR's title must not label an issue link. + return issue && issue.number === link.number && !/\/pull\/\d+$/.test(issue.url) + ? issue.title + : null +} + +export function wireGitHubIssueLinkTitleFill( + store: Store, + runtime: { + invalidateResolvedWorktreeCache: () => void + publishWorkspaceMetadataSet: (set: WorkspaceMetadataSet) => void + } +): () => void { + return installGitHubIssueLinkTitleFill({ + store, + // Background reads never start a stopped WSL distro; the link just stays untitled. + readIssueTitle: (repo, link) => + readGitHubRepoUnlessWslStopped( + store, + repo, + () => readGitHubIssueLinkTitle(store, repo, link), + { + wake: false + } + ), + publish: ({ worktreeId, hostId, meta }) => { + // Resolved rows embed metadata; refresh them so the next listing read agrees. + runtime.invalidateResolvedWorktreeCache() + // Same turn as the title write, so a listing either read it or carries an older seq. + const { epoch, seq } = store.advanceWorkspaceMetadataCursor() + runtime.publishWorkspaceMetadataSet({ + kind: 'set', + domain: 'workspaceMetadata', + hostId, + epoch, + seq, + id: composeWorktreeHostIdentity(hostId, worktreeId), + repoId: getRepoIdFromWorktreeId(worktreeId), + worktreeId, + row: workspaceMetadataSetRow(meta) + }) + } + }) +} diff --git a/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts b/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts index 3ea51313aa2..c9d96275b1d 100644 --- a/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts +++ b/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts @@ -41,7 +41,7 @@ const localRepo: Repo = { addedAt: 0 } -function createStore(repo: Repo) { +function createStore(repo: Repo, cursor?: { epoch: string; seq: number }) { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the listing reads only these store methods; the pruning that would need more is mocked above. return { getRepo: () => repo, @@ -55,7 +55,8 @@ function createStore(repo: Repo) { getAllWorktreeLineage: () => ({}), getAllWorkspaceLineage: () => ({}), removeWorktreeLineage: vi.fn(), - captureNativeLocalWorktreeMetadataScanExpectation: () => undefined + captureNativeLocalWorktreeMetadataScanExpectation: () => undefined, + ...(cursor ? { getWorkspaceMetadataCursor: () => ({ ...cursor }) } : {}) } as never } @@ -106,4 +107,26 @@ describe('the catalog version a listing carries', () => { first && 'catalogVersion' in first ? first.catalogVersion : undefined ) }) + + it('carries the metadata cursor it read with its metadata, not one advanced during the scan', async () => { + const cursor = { epoch: 'e1', seq: 4 } + // A title write lands while the scan is still running. + listRepoWorktreesMock.mockImplementation(async () => { + cursor.seq = 5 + return [worktreeAt(localRepo, localRepo.path)] + }) + const store = createStore(localRepo, cursor) + + const during = await listDetectedWorktreesForCapturedRepo(store, localRepo, () => true) + const after = await listDetectedWorktreesForCapturedRepo(store, localRepo, () => true) + + expect(during && 'workspaceMetadata' in during ? during.workspaceMetadata : null).toEqual({ + epoch: 'e1', + seq: 4 + }) + expect(after && 'workspaceMetadata' in after ? after.workspaceMetadata : null).toEqual({ + epoch: 'e1', + seq: 5 + }) + }) }) diff --git a/src/main/ipc/worktrees/listing/detected-provider-listing.ts b/src/main/ipc/worktrees/listing/detected-provider-listing.ts index 3344d22e1a6..7aa21b9e99a 100644 --- a/src/main/ipc/worktrees/listing/detected-provider-listing.ts +++ b/src/main/ipc/worktrees/listing/detected-provider-listing.ts @@ -46,6 +46,13 @@ import { wslDistroNotRunningForScanFailure } from './wsl-stopped-worktree-listing' +// Partial stores (tests, embedders) may not publish workspace metadata; their listings carry no stamp. +function readWorkspaceMetadataCursor(store: { + getWorkspaceMetadataCursor?: () => { epoch: string; seq: number } +}): { epoch: string; seq: number } | undefined { + return store.getWorkspaceMetadataCursor?.() +} + export async function listDetectedWorktreesForCapturedRepo( store: Store, repo: Repo, @@ -59,6 +66,8 @@ export async function listDetectedWorktreesForCapturedRepo( ? ({ providerAbortStatus: providerAbort.status() } as const) : undefined const allMeta = isFolderRepo(repo) ? undefined : readAllWorktreeMetaForRepo(store, repo) + // Read with the metadata, so clients can tell which published metadata records this listing includes. + const workspaceMetadata = readWorkspaceMetadataCursor(store) try { // Folder rows are read synchronously, leaving no mutation window that needs a re-scan. @@ -75,7 +84,8 @@ export async function listDetectedWorktreesForCapturedRepo( authoritative: false, source: 'metadata-fallback', worktrees: [], - catalogVersion: getLocalWorktreeCatalogVersion(repo.id) + catalogVersion: getLocalWorktreeCatalogVersion(repo.id), + ...(workspaceMetadata ? { workspaceMetadata } : {}) } } return { @@ -83,6 +93,7 @@ export async function listDetectedWorktreesForCapturedRepo( authoritative: true, source: 'git', catalogVersion: getLocalWorktreeCatalogVersion(repo.id), + ...(workspaceMetadata ? { workspaceMetadata } : {}), worktrees: projectWorktreeLineageWithHostPeers( store, repo, @@ -108,7 +119,8 @@ export async function listDetectedWorktreesForCapturedRepo( authoritative: false, source: 'metadata-fallback', worktrees: buildDisconnectedDetectedWorktrees(store, repo, worktrees), - catalogVersion: getLocalWorktreeCatalogVersion(repo.id) + catalogVersion: getLocalWorktreeCatalogVersion(repo.id), + ...(workspaceMetadata ? { workspaceMetadata } : {}) } } const pendingAtScan = snapshotPendingWorktreeRemovals() @@ -140,7 +152,8 @@ export async function listDetectedWorktreesForCapturedRepo( authoritative: false, source: 'metadata-fallback', worktrees: [], - catalogVersion: localWorktreeCatalogVersionAt(scan.generation) + catalogVersion: localWorktreeCatalogVersionAt(scan.generation), + ...(workspaceMetadata ? { workspaceMetadata } : {}) } } if (freshScan) { @@ -166,6 +179,7 @@ export async function listDetectedWorktreesForCapturedRepo( authoritative: true, source: 'git', catalogVersion: localWorktreeCatalogVersionAt(scan.generation), + ...(workspaceMetadata ? { workspaceMetadata } : {}), worktrees: projectPendingWorktreeRemovals( buildDetectedGitWorktrees(store, repo, localRows, allMeta), (worktree) => worktree.id, @@ -196,7 +210,8 @@ export async function listDetectedWorktreesForCapturedRepo( unavailableReason, failureKind, wslDistroStopped, - catalogVersion: getLocalWorktreeCatalogVersion(repo.id) + catalogVersion: getLocalWorktreeCatalogVersion(repo.id), + ...(workspaceMetadata ? { workspaceMetadata } : {}) } } warnOnce( @@ -212,7 +227,8 @@ export async function listDetectedWorktreesForCapturedRepo( worktrees: [], unavailableReason, failureKind, - catalogVersion: getLocalWorktreeCatalogVersion(repo.id) + catalogVersion: getLocalWorktreeCatalogVersion(repo.id), + ...(workspaceMetadata ? { workspaceMetadata } : {}) } } } diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index 0f463081e63..da51c916fe2 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -226,6 +226,8 @@ async function startOrcadRuntime( paneGridsForShutdown = runtime accountLaunch?.attachToRuntime(runtime) + const { wireGitHubIssueLinkTitleFill } = await import('../github/github-issue-link-title-wiring') + registerCleanup(wireGitHubIssueLinkTitleFill(profileStore, runtime)) const { installOrcadEmulatorBridge } = await import('./orcad-emulator-bridge') installOrcadEmulatorBridge(runtime, registerCleanup) diff --git a/src/main/persistence/loading-store/store-runtime-state.ts b/src/main/persistence/loading-store/store-runtime-state.ts index 951187da47b..d089fa159a4 100644 --- a/src/main/persistence/loading-store/store-runtime-state.ts +++ b/src/main/persistence/loading-store/store-runtime-state.ts @@ -1,3 +1,4 @@ +import { randomUUID } from 'node:crypto' import { removeStaleDurableWriteTempFiles } from '../../filesystem/durable-file-write' import type { GlobalSettings } from '../../../shared/global-settings-types' import type { PersistedState } from '../../../shared/persisted-state-types' @@ -6,7 +7,7 @@ import type { WorkspaceSessionWriteListener } from './workspace-session-write-listeners' import type { ExecutionHostId } from '../../../shared/execution-host' -import type { StateWriteListener } from './write-scheduling' +import type { StateWriteListener, WorktreeMetaWriteListener } from './write-scheduling' import type { PartitionEditorViews } from './layout-editor-views' import type { ActiveViewPreference } from '../preferences/active-view-preference' import { @@ -114,6 +115,9 @@ export class StoreRuntimeState { /** In-memory editor views by partition; layout-owner builds only. */ readonly layoutEditorViews = new Map() readonly stateWriteListeners = new Set() + readonly worktreeMetaWriteListeners = new Set() + // This store's workspaceMetadata position: a new epoch per process, one seq per published record. + readonly workspaceMetadataCursor = { epoch: randomUUID(), seq: 0 } projectHostOperations: ProjectHostPersistenceOperations | null = null projectGroupOperations: ProjectGroupPersistenceOperations | null = null folderWorkspaceOperations: FolderWorkspacePersistenceOperations | null = null diff --git a/src/main/persistence/loading-store/worktree-identity-metadata.ts b/src/main/persistence/loading-store/worktree-identity-metadata.ts index 8a9a78369b8..5b2c74cf061 100644 --- a/src/main/persistence/loading-store/worktree-identity-metadata.ts +++ b/src/main/persistence/loading-store/worktree-identity-metadata.ts @@ -19,7 +19,8 @@ import { worktreeMetaHostFor } from '../../../shared/worktree/local-only-worktree-meta-ids' -type MetadataRuntime = Pick +type MetadataRuntime = Pick & + Partial> type WorktreeMetaState = Pick< PersistedState, 'worktreeMeta' | 'worktreeMetaByIdentity' | 'worktreeIdentityAliases' @@ -265,5 +266,13 @@ export function setWorktreeMetaForHost( state.worktreeMeta[worktreeId] = updated } scheduleSave(scheduling, WORKTREE_METADATA_DOMAINS) + for (const listener of runtime.worktreeMetaWriteListeners ?? []) { + try { + listener({ worktreeId, hostId: executionHostId, previous: existing, next: updated }) + } catch (error) { + // The row is already written; an observer's failure must not report the write as failed. + console.error('[worktree-meta] write listener failed:', error) + } + } return updated } diff --git a/src/main/persistence/loading-store/worktree-meta-write-normalization.ts b/src/main/persistence/loading-store/worktree-meta-write-normalization.ts index 638623f5202..e98a0e2e7f7 100644 --- a/src/main/persistence/loading-store/worktree-meta-write-normalization.ts +++ b/src/main/persistence/loading-store/worktree-meta-write-normalization.ts @@ -49,7 +49,7 @@ export function mergeWorktreeMetaForWrite( const normalizedUpdates = normalizeWorkspaceAttachmentUpdate(existing, metaUpdates) const updated = { ...(existing ?? createDefaultWorktreeMeta()), - ...normalizeGitHubPRSuppressionUpdate(normalizedUpdates), + ...normalizeGitHubPRSuppressionUpdate(normalizedUpdates, existing?.linkedPR), ...identity } updated.linkedWorkItem = normalizeWorkspaceLinkedItem(updated.linkedWorkItem) diff --git a/src/main/persistence/loading-store/write-scheduling.ts b/src/main/persistence/loading-store/write-scheduling.ts index a5bd9ccd810..7397530f9ac 100644 --- a/src/main/persistence/loading-store/write-scheduling.ts +++ b/src/main/persistence/loading-store/write-scheduling.ts @@ -9,9 +9,17 @@ import { } from './workspace-session-write-listeners' import { ptyBindingGenerationOf } from './pty-binding-generations' import type { PartitionEditorViews } from './layout-editor-views' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' /** Undefined means any domain may have changed. */ export type StateWriteListener = (dirtyDomains: readonly string[] | undefined) => void +/** One host's worktree metadata row before and after a write. */ +export type WorktreeMetaWriteListener = (write: { + worktreeId: string + hostId: ExecutionHostId + previous: WorktreeMeta | undefined + next: WorktreeMeta +}) => void const SAVE_DEBOUNCE_MS = 1_000 const SAVE_MAX_WAIT_MS = 5_000 @@ -31,6 +39,8 @@ type WriteSchedulingOperationsRuntime = Pick< | 'workspaceSessionWriteListeners' | 'workspaceSessionOperationListeners' | 'stateWriteListeners' + | 'worktreeMetaWriteListeners' + | 'workspaceMetadataCursor' | 'ptyBindingGenerations' | 'layoutEditorViews' | 'state' @@ -88,6 +98,28 @@ export class WriteSchedulingOperations { runtime.stateWriteListeners.delete(listener) } } + + /** The workspaceMetadata position a listing records when it reads metadata. */ + getWorkspaceMetadataCursor(): { epoch: string; seq: number } { + const { epoch, seq } = this[writeSchedulingOperationsContext].runtime.workspaceMetadataCursor + return { epoch, seq } + } + + /** Advances the position for one published record; call in the same turn as its metadata write. */ + advanceWorkspaceMetadataCursor(): { epoch: string; seq: number } { + const cursor = this[writeSchedulingOperationsContext].runtime.workspaceMetadataCursor + cursor.seq += 1 + return { epoch: cursor.epoch, seq: cursor.seq } + } + + /** Observe each host-qualified worktree metadata write; callbacks must not throw, block or write. */ + onWorktreeMetaWritten(listener: WorktreeMetaWriteListener): () => void { + const { runtime } = this[writeSchedulingOperationsContext] + runtime.worktreeMetaWriteListeners.add(listener) + return () => { + runtime.worktreeMetaWriteListeners.delete(listener) + } + } } export function scheduleSave( 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/construction/runtime-store-contract.ts b/src/main/runtime/construction/runtime-store-contract.ts index e65b65778b7..4847daa5909 100644 --- a/src/main/runtime/construction/runtime-store-contract.ts +++ b/src/main/runtime/construction/runtime-store-contract.ts @@ -32,6 +32,7 @@ export type RuntimeStore = { removeProjectForHost?: Store['removeProjectForHost'] reorderRepos?: Store['reorderRepos'] getAllWorktreeMeta: Store['getAllWorktreeMeta'] + getWorkspaceMetadataCursor?: Store['getWorkspaceMetadataCursor'] getAllWorktreeMetaForHost?: Store['getAllWorktreeMetaForHost'] captureNativeLocalWorktreeMetadataScanExpectation?: Store['captureNativeLocalWorktreeMetadataScanExpectation'] pruneSessionlessMissingLocalWorktreeMetadataForRepo?: Store['pruneSessionlessMissingLocalWorktreeMetadataForRepo'] diff --git a/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts b/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts new file mode 100644 index 00000000000..eff460beecd --- /dev/null +++ b/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts @@ -0,0 +1,28 @@ +import type { Repo } from '../../../../shared/repo-types' +import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' +import type { WorkspaceMetadataCursor } from '../../../../shared/worktree/workspace-metadata-set' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership' + +/** + * The metadata a listing reads, with the store's workspaceMetadata cursor taken in the same turn, so + * clients can tell which published metadata records the listing includes. + */ +export function readRuntimeListingMetadata( + store: RuntimeStore, + repo: Repo +): { + repoOwnerCount: number + workspaceMetadata: WorkspaceMetadataCursor | undefined + // The repo-owned metadata row for a worktree id, from this same read. + ownedMeta: (worktreeId: string) => WorktreeMeta | undefined +} { + const workspaceMetadata = store.getWorkspaceMetadataCursor?.() + const metaById = store.getAllWorktreeMeta() + const repoOwnerCount = store.getRepos().filter((candidate) => candidate.id === repo.id).length + return { + repoOwnerCount, + workspaceMetadata, + ownedMeta: (worktreeId) => getRepoOwnedWorktreeMeta(repo, worktreeId, metaById, repoOwnerCount) + } +} diff --git a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts index 2aa6864c649..63f4308ea41 100644 --- a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts +++ b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts @@ -1,3 +1,4 @@ +import { readRuntimeListingMetadata } from './runtime-listing-metadata' import type { RuntimeManagedWorktreeQueryDependencies } from './runtime-managed-worktree-query-dependencies' import { resolveWorktreeHostRouting } from './worktree-launch-host-repo' import { createRepoRowExecutionHostLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' @@ -137,8 +138,7 @@ export class RuntimeManagedWorktreeQueries { const visibilitySettings = { ...settings, worktreeVisibilityDefaults: visibilityDefaults } if (isFolderRepo(repo)) { const worktrees = listRuntimeFolderWorkspaces(store, repo) - const metaById = store.getAllWorktreeMeta() - const repoOwnerCount = store.getRepos().filter((candidate) => candidate.id === repo.id).length + const listed = readRuntimeListingMetadata(store, repo) const matcher = createWorktreeVisibilitySourceMatcher( [repo.path, ...worktrees.map((worktree) => worktree.path)], resolveCustomWorktreeVisibilitySources(repo, visibilityDefaults), @@ -151,7 +151,7 @@ export class RuntimeManagedWorktreeQueries { matcher, defaultsSupported, visibilitySettings, - getRepoOwnedWorktreeMeta(repo, worktree.id, metaById, repoOwnerCount) ?? null + listed.ownedMeta(worktree.id) ?? null ) ) return { @@ -159,6 +159,7 @@ export class RuntimeManagedWorktreeQueries { authoritative: true, source: 'git', catalogVersion: getLocalWorktreeCatalogVersion(repo.id), + workspaceMetadata: listed.workspaceMetadata, worktrees: projectWorktreeLineageWithHostPeers(store, repo, detected) } } @@ -185,13 +186,11 @@ export class RuntimeManagedWorktreeQueries { resolveConfiguredWorktreeBasePaths(repo) ) const expectedHostId = getRepoExecutionHostId(repo) - const repoOwnerCount = store.getRepos().filter((candidate) => candidate.id === repo.id).length - const metaById = store.getAllWorktreeMeta() + const listed = readRuntimeListingMetadata(store, repo) + const repoOwnerCount = listed.repoOwnerCount const detected = scan.worktrees.map((gitWorktree) => { const id = `${repo.id}::${gitWorktree.path}` - const meta = - readWorktreeMetaForHost(store, id, expectedHostId) ?? - getRepoOwnedWorktreeMeta(repo, id, metaById, repoOwnerCount) + const meta = readWorktreeMetaForHost(store, id, expectedHostId) ?? listed.ownedMeta(id) const worktree = { ...mergeWorktree(repo.id, gitWorktree, meta, repo.displayName), hostId: repoOwnerCount === 1 ? (meta?.hostId ?? expectedHostId) : expectedHostId @@ -210,6 +209,7 @@ export class RuntimeManagedWorktreeQueries { repoId: repo.id, authoritative: scan.ok && !scan.superseded, source: scan.ok ? 'git' : 'metadata-fallback', + workspaceMetadata: listed.workspaceMetadata, // Stamp the scan's starting generation: that is the catalog its rows describe. catalogVersion: localWorktreeCatalogVersionAt(scan.scanGeneration), worktrees: projectWorktreeLineageWithHostPeers(store, repo, detected) 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..10a338ffee2 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. Interim transport for the record. */ + 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/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index 7b0405af786..0306a69d3b1 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -1,4 +1,5 @@ import { wireRecipeWorkspaceRemoval } from '../ephemeral-vm/recipe-workspace-removal-wiring' +import { wireGitHubIssueLinkTitleFill } from '../github/github-issue-link-title-wiring' import { applySessionSearchSettingsChange, installChildSessionSearchService @@ -159,6 +160,9 @@ export function initializeMainProcessRuntime(): OrcaRuntimeService { recordDurableCrashBreadcrumb('agent_state_rules_active', rules) ) wireRecipeWorkspaceRemoval(runtime, store, () => app.getPath('userData')) + // Each host titles its own workspaces' untitled GitHub issue links once, when they are linked. + const disposeIssueLinkTitleFill = wireGitHubIssueLinkTitleFill(store, runtime) + app.once('will-quit', disposeIssueLinkTitleFill) state.runtime = runtime // Opening a recipe VM's workspace from a client wakes the VM through the runtime's one owner. registerRecipeVmWaker({ diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index b5d40e737b9..96b3d4f769d 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -45,6 +45,8 @@ export function registerRuntimeWindowLifecycle( } send('worktrees:changed', renamed ? { repoId, renamed } : { repoId }) }, + // Why: interim transport for the workspaceMetadata set record; the record shape, not this channel, is the contract. + 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/runtime-client-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts index f3f855af18a..ea7bdb181c0 100644 --- a/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts @@ -1,8 +1,8 @@ import '@/store/slices/linear/linear-issue-read' import { consumeLinearIssueRead } from '@/store/slices/linear/linear-issue-read-lifecycle' -import { applyHostWorktreeTerminalSleepState } from '@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-exit-deferral' import { dispatchTerminalSideEffectBatch } from '@/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler' import { emitAutomationsChangedWindowEvent } from '@/components/automations/events/automations-changed-window-event' +import { applyHostWorkspaceRowEvent } from './worktree-metadata-set-events' import { applyNativeChatLaunchDraftResolved } from '@/runtime/native-chat/launch-drafts/native-chat-launch-draft-runtime-resolution' import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' import { @@ -111,8 +111,7 @@ export function registerRuntimeClientIpcBridge( ) return } - if (event.type === 'worktreeTerminalSleepState') { - applyHostWorktreeTerminalSleepState(environmentId, event) + if (applyHostWorkspaceRowEvent(environmentId, event)) { return } if (event.type === 'terminalSideEffects') { 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..9ce76a4dc55 --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/worktree-metadata-set-events.ts @@ -0,0 +1,98 @@ +import { applyHostWorktreeTerminalSleepState } from '@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-exit-deferral' +import { + getRepoExecutionHostId, + toRuntimeExecutionHostId, + type ExecutionHostId +} from '../../../../shared/execution-host' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import { readWorkspaceMetadataSet } from '../../../../shared/worktree/workspace-metadata-set' +import { useAppStore } from '../../store' +import { + noteWorkspaceMetadataRecord, + requireWorkspaceMetadataCoverage, + workspaceMetadataProducerKey +} from '../../store/slices/worktrees/listing/workspace-metadata-coverage' +import { requestWorkspaceMetadataRecovery } from '../../store/slices/worktrees/listing/workspace-metadata-recovery' +import { + patchWorktreeMetadataSet, + type MetadataSetSource +} from '../../store/slices/worktrees/listing/worktree-metadata-set-patch' +import type { WorktreeFetchOptions } from '../../store/slices/worktrees/listing/worktree-fetch-options' + +const fetchWorktrees = (repoId: string, options: WorktreeFetchOptions): Promise => + useAppStore.getState().fetchWorktrees(repoId, options) + +function apply(record: unknown, source: MetadataSetSource): void { + const set = readWorkspaceMetadataSet(record) + if (!set) { + return + } + // The listing owner for this record's repo: this app (local and SSH rows) or the paired environment. + const listingHost: ExecutionHostId = + source.kind === 'environment' ? toRuntimeExecutionHostId(source.environmentId) : set.hostId + const producerKey = workspaceMetadataProducerKey(listingHost) + // Every repo projection this producer lists here, built only for a gap or a first-seen projection. + let projections: { repoId: string; hostId: ExecutionHostId }[] | undefined + let listed: Set | undefined + const producerProjections = (): { repoId: string; hostId: ExecutionHostId }[] => + (projections ??= useAppStore.getState().repos.flatMap((repo) => { + const hostId = getRepoExecutionHostId(repo) + return workspaceMetadataProducerKey(hostId) === producerKey + ? [{ repoId: repo.id, hostId }] + : [] + })) + const { replayed, gap } = noteWorkspaceMetadataRecord( + producerKey, + set.epoch, + set.seq, + set.repoId, + listingHost, + (repoId, hostId) => + (listed ??= new Set(producerProjections().map((p) => `${p.hostId}\u0000${p.repoId}`))).has( + `${hostId}\u0000${repoId}` + ) + ) + if (replayed) { + return + } + let applied = false + useAppStore.setState((current) => { + const result = patchWorktreeMetadataSet(current, set, source) + applied = result.applied + return result.patch ?? current + }) + if (gap) { + // A missed record names no projection: list every one this producer owns here, each once. + requireWorkspaceMetadataCoverage(producerKey, producerProjections()) + for (const { repoId, hostId } of producerProjections()) { + requestWorkspaceMetadataRecovery(repoId, hostId, fetchWorktrees) + } + } else if (!applied) { + // The row or a link isn't listed yet; a listing begun now includes this record. + requestWorkspaceMetadataRecovery(set.repoId, listingHost, fetchWorktrees) + } +} + +/** This app's own host: the record names the host its row lives on. */ +export function applyLocalWorktreeMetadataSet(record: unknown): void { + apply(record, { kind: 'local' }) +} + +/** + * A paired host's per-workspace row events, after the bridge's connection-generation check. + * Returns false for any other event. + */ +export function applyHostWorkspaceRowEvent( + environmentId: string, + event: RuntimeClientEvent +): boolean { + if (event.type === 'worktreeTerminalSleepState') { + applyHostWorktreeTerminalSleepState(environmentId, event) + return true + } + if (event.type === 'workspaceMetadataSet') { + apply(event, { kind: 'environment', environmentId }) + return true + } + return false +} diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts index 5d62ca41274..62ee63ea12b 100644 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts +++ b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts @@ -116,6 +116,18 @@ function resolveIssueTitle( return sources.issueCache[key]?.data?.title ?? '' } +// Each saved link is its own unit: same-number links (another repo, or the legacy issue field) must not +// shadow each other's saved titles. +function withEvidenceId(evidence: PaletteComposedEvidence, id: string): PaletteComposedEvidence { + const prefix = evidence.unit.id.length + return { + unit: { ...evidence.unit, id }, + fields: evidence.fields.map( + (field) => field && { ...field, id: `${id}${field.id.slice(prefix)}`, evidenceId: id } + ) + } +} + function buildEvidence( worktree: Worktree, repo: Repo | undefined, @@ -138,7 +150,7 @@ function buildEvidence( }), ...getWorkspaceAttachments({ linkedItems: worktree.linkedItems }).map((item) => { const evidence = buildWorktreeAttachmentEvidence(item) - return evidence ? { ...evidence, id: `attachment:${getWorkspaceAttachmentKey(item)}` } : null + return evidence && withEvidenceId(evidence, `attachment:${getWorkspaceAttachmentKey(item)}`) }), ...ports.map((port) => buildWorktreePortEvidence(port)) ] diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts index 20dce1a770d..7ad40ac0666 100644 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts +++ b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts @@ -125,4 +125,34 @@ describe('worktree-palette-search', () => { }) ]) }) + + it("finds each linked issue by its saved title before the issue's card has rendered", () => { + const issue = (number: number, title: string, url?: string) => ({ + provider: 'github' as const, + type: 'issue' as const, + number, + title, + ...(url ? { url } : {}) + }) + const worktrees = [ + makeWorktree({ + id: 'wt-cli', + linkedIssue: 11704, + linkedItems: [issue(11704, 'verificacion de permisos')] + }), + makeWorktree({ + id: 'wt-two-repos', + linkedIssue: 42, + linkedItems: [ + issue(42, 'alpha release', 'https://github.com/stablyai/orca/issues/42'), + issue(42, 'zebra crossing', 'https://github.com/other/repo/issues/42') + ] + }) + ] + const search = (query: string) => + searchWorktrees(worktrees, query, repoMap).map((result) => result.worktreeId) + + expect(search('verificacion')).toEqual(['wt-cli']) + expect(search('zebra')).toEqual(['wt-two-repos']) + }) }) 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..0c407253fc8 100644 --- a/src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.ts +++ b/src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.ts @@ -103,6 +103,7 @@ function isRuntimeClientEvent( isNotificationAttentionAcknowledgement(message.acknowledgement)) || message.type === 'reposChanged' || message.type === 'worktreesChanged' || + message.type === 'workspaceMetadataSet' || message.type === 'nativeChatLaunchDraftResolved' || message.type === 'terminalSideEffects' || message.type === 'sshStateChanged' || diff --git a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh-leases.ts b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh-leases.ts index e24c501bd51..ea21280af48 100644 --- a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh-leases.ts +++ b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh-leases.ts @@ -56,7 +56,8 @@ type ProviderInvocation = { export type DetectedWorktreeRefreshLeaseRegistry = { acquire( publicKey: string, - input: DetectedWorktreeRefreshProviderInput + input: DetectedWorktreeRefreshProviderInput, + fresh?: boolean ): DetectedWorktreeRefreshLease getActiveCounts(): { providerInvocations: number; waiterLeases: number } } @@ -198,15 +199,19 @@ export function createDetectedWorktreeRefreshLeaseRegistry( const acquire = ( publicKey: string, - input: DetectedWorktreeRefreshProviderInput + input: DetectedWorktreeRefreshProviderInput, + // A fresh listing must not join one that may have read metadata before a newer write. + fresh = false ): DetectedWorktreeRefreshLease => { - const invocation = - [...(invocationsByPublicKey.get(publicKey) ?? [])].find( - (candidate) => - !candidate.settled && - !candidate.cancelAttempted && - requestsAreCompatible(candidate.request, input) - ) ?? startInvocation(publicKey, input) + const joinable = fresh + ? undefined + : [...(invocationsByPublicKey.get(publicKey) ?? [])].find( + (candidate) => + !candidate.settled && + !candidate.cancelAttempted && + requestsAreCompatible(candidate.request, input) + ) + const invocation = joinable ?? startInvocation(publicKey, input) const waiterLeaseId = mintWaiterLeaseId() let resolveResult!: (result: HostQualifiedDetectedWorktreeResult) => void let rejectResult!: (error: unknown) => void diff --git a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh.ts b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh.ts index dc85da6755b..2987e36a5bd 100644 --- a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh.ts +++ b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh.ts @@ -61,10 +61,11 @@ export function acquireDetectedWorktreeRefreshLeaseForRepo( } const publicKey = detectedWorktreeRefreshKey(repoId, options) if (parsedHost.kind === 'local') { - return detectedWorktreeRefreshLeaseRegistry.acquire(publicKey, { - repoId, - executionHostId: LOCAL_EXECUTION_HOST_ID - }) + return detectedWorktreeRefreshLeaseRegistry.acquire( + publicKey, + { repoId, executionHostId: LOCAL_EXECUTION_HOST_ID }, + options.forceFresh + ) } if ( !options.directSshAuthority || @@ -72,11 +73,15 @@ export function acquireDetectedWorktreeRefreshLeaseForRepo( ) { throw new Error('Direct SSH provider leases require exact target authority') } - return detectedWorktreeRefreshLeaseRegistry.acquire(publicKey, { - repoId, - executionHostId: options.executionHostId as SshExecutionHostId, - expectedAuthority: { ...options.directSshAuthority } - }) + return detectedWorktreeRefreshLeaseRegistry.acquire( + publicKey, + { + repoId, + executionHostId: options.executionHostId as SshExecutionHostId, + expectedAuthority: { ...options.directSshAuthority } + }, + options.forceFresh + ) } export function qualifiedProviderResultIsAdmitted( @@ -148,7 +153,7 @@ async function listDetectedWorktreesForRuntimeRepoOnce( const key = detectedWorktreeRefreshKey(repoId, options) const connectionGeneration = getEnvironmentSshStateGeneration(environmentId) const runtimeConnectionGeneration = getRuntimeEnvironmentConnectionGeneration(environmentId) - let refresh = runtimeDetectedWorktreeRefreshesInFlight.get(key) + let refresh = options.forceFresh ? undefined : runtimeDetectedWorktreeRefreshesInFlight.get(key) if (!refresh) { refresh = listDetectedWorktreesForRepo({ kind: 'environment', environmentId }, repoId, { reuseRecentCompatibilityFailure: options.reuseRecentCompatibilityFailure diff --git a/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts b/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts index ac72a2588c0..bbe2405acac 100644 --- a/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts +++ b/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts @@ -13,6 +13,7 @@ import { } from './worktree-host-ownership' import { fetchKnownSshWorktreesForRepo } from './known-ssh-worktree-fetch' import { mergeFetchedWorktrees } from './fetched-worktree-merge' +import { listingMetadataCoverage } from './workspace-metadata-coverage' import { notifyRuntimeScopeForbiddenIfNeeded } from './runtime-scope-forbidden-toast' import { mapReposForWorktreeRefresh } from './worktree-refresh-pool' import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' @@ -64,15 +65,19 @@ export function createFetchAllWorktrees( if (refresh.status !== 'admitted') { return failed } + const metadata = listingMetadataCoverage(get(), repo.id, hostId, refresh) const outcome = mergeFetchedWorktrees(set, get, { repoId: repo.id, hostId, ownerWasMissingAtStart: false, requestStartedWorktrees, setup, - refresh, + refresh: metadata.refresh, purgeRemovedWorktrees }) + if (outcome === 'applied') { + metadata.settle((id, fetchOptions) => get().fetchWorktrees(id, fetchOptions)) + } return outcome === 'applied' ? { repoId: repo.id, hostId, refresh } : failed } catch (err) { if (!notifyRuntimeScopeForbiddenIfNeeded(err)) { diff --git a/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts b/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts index 6c42355d76d..4761ad69ff3 100644 --- a/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts +++ b/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts @@ -20,6 +20,7 @@ import { } from './worktree-host-ownership' import { fetchKnownSshWorktreesForRepo } from './known-ssh-worktree-fetch' import { mergeFetchedWorktrees } from './fetched-worktree-merge' +import { listingMetadataCoverage } from './workspace-metadata-coverage' import { notifyRuntimeScopeForbiddenIfNeeded } from './runtime-scope-forbidden-toast' import { refreshRemoteWorktreeLineageBestEffort } from '../metadata/worktree-lineage-refresh' import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' @@ -87,7 +88,8 @@ export function createFetchWorktrees( connectionId: repoOwner?.connectionId, knownWorktreeIds: getKnownWorktreeIdsForPurge(ownerState, repoId, hostId), isStaleCatalogPublication: (result) => - isStaleWorktreeCatalogPublication(get(), repoId, hostId, result.catalogVersion) + isStaleWorktreeCatalogPublication(get(), repoId, hostId, result.catalogVersion), + ...(options?.forceFresh ? { forceFresh: true } : {}) }) if (refresh.status !== 'admitted') { return directCallerAuthority ? refresh.providerResult : false @@ -95,6 +97,7 @@ export function createFetchWorktrees( if (options?.requireAuthoritative && !refresh.result.authoritative) { return directCallerAuthority ? (refresh.providerResult ?? false) : false } + const metadata = listingMetadataCoverage(get(), repoId, hostId, refresh) const outcome = mergeFetchedWorktrees(set, get, { repoId, hostId, @@ -105,8 +108,11 @@ export function createFetchWorktrees( : undefined, requestStartedWorktrees, setup, - refresh + refresh: metadata.refresh }) + if (outcome === 'applied') { + metadata.settle((id, fetchOptions) => get().fetchWorktrees(id, fetchOptions)) + } switch (outcome) { case 'applied': break diff --git a/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.test.ts b/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.test.ts new file mode 100644 index 00000000000..6ae672a6ff9 --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest' +import { + noteWorkspaceMetadataRecord, + requireWorkspaceMetadataCoverage, + workspaceMetadataListingCoverage +} from './workspace-metadata-coverage' +import { requestWorkspaceMetadataRecovery } from './workspace-metadata-recovery' + +const listed = () => true + +describe('workspace metadata listing coverage', () => { + it('a missed record makes every repo of that producer wait for a listing that includes it', () => { + expect(noteWorkspaceMetadataRecord('local', 'gap', 1, 'repo-a', 'local', listed)).toEqual({ + replayed: false, + gap: false + }) + expect(noteWorkspaceMetadataRecord('local', 'gap', 3, 'repo-a', 'local', listed).gap).toBe(true) + requireWorkspaceMetadataCoverage('local', [ + { repoId: 'repo-a', hostId: 'local' }, + { repoId: 'repo-b', hostId: 'ssh:box' } + ]) + + expect( + workspaceMetadataListingCoverage('local', 'repo-b', 'ssh:box', { epoch: 'gap', seq: 2 }) + ).toBe('stale') + expect( + workspaceMetadataListingCoverage('local', 'repo-b', 'ssh:box', { epoch: 'gap', seq: 3 }) + ).toBe('covered') + // The same repo listed on another host is a different projection. + expect( + workspaceMetadataListingCoverage('local', 'repo-b', 'local', { epoch: 'gap', seq: 0 }) + ).toBe('unknown') + + // A later gap after repo-b was removed forgets it. + noteWorkspaceMetadataRecord('local', 'gap', 5, 'repo-a', 'local', listed) + requireWorkspaceMetadataCoverage('local', [{ repoId: 'repo-a', hostId: 'local' }]) + expect( + workspaceMetadataListingCoverage('local', 'repo-b', 'ssh:box', { epoch: 'gap', seq: 5 }) + ).toBe('unknown') + }) + + it("another producer run's listing keeps titles without claiming to cover them", () => { + noteWorkspaceMetadataRecord('env:e1:1:1', 'before', 9, 'repo-a', 'runtime:e1', listed) + expect( + workspaceMetadataListingCoverage('env:e1:1:1', 'repo-a', 'runtime:e1', { + epoch: 'after', + seq: 1 + }) + ).toBe('unstamped') + }) +}) + +describe('workspace metadata recovery listing', () => { + it('runs one fresh listing at a time and once more for requests made during it', async () => { + let finish: () => void = () => {} + const fetchWorktrees = vi.fn( + () => new Promise((resolve) => (finish = () => resolve(true))) + ) + + requestWorkspaceMetadataRecovery('repo-a', 'local', fetchWorktrees) + requestWorkspaceMetadataRecovery('repo-a', 'local', fetchWorktrees) + requestWorkspaceMetadataRecovery('repo-a', 'local', fetchWorktrees) + expect(fetchWorktrees).toHaveBeenCalledTimes(1) + expect(fetchWorktrees).toHaveBeenCalledWith('repo-a', { + forceLocalOwner: true, + forceFresh: true, + suppressRemoteLineageRefresh: true + }) + + finish() + await vi.waitFor(() => expect(fetchWorktrees).toHaveBeenCalledTimes(2)) + finish() + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(fetchWorktrees).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.ts b/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.ts new file mode 100644 index 00000000000..f43e4b932b6 --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-coverage.ts @@ -0,0 +1,235 @@ +import { parseExecutionHostId, type ExecutionHostId } from '../../../../../../shared/execution-host' +import type { Worktree } from '../../../../../../shared/worktree/types' +import type { WorkspaceMetadataCursor } from '../../../../../../shared/worktree/workspace-metadata-set' +import { getWorkspaceAttachments } from '../../../../../../shared/workspace-attachments/workspace-attachments' +import { getWorkspaceReferenceIdentity } from '../../../../../../shared/workspace-attachments/workspace-reference-identity' +import { + getRuntimeEnvironmentRevision, + onRuntimeEnvironmentsRetired +} from '../../../../runtime/rpc/environment-revisions/runtime-environment-revision' +import { getRuntimeEnvironmentConnectionGeneration } from '../../runtime-status/runtime-status-connection-generation' +import type { AppState } from '../../../types' +import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' +import { worktreeHostMatchOptions, worktreeMatchesHost } from './worktree-host-ownership' +import type { AdmittedDetectedWorktreeRefresh } from './worktree-slice-types' +import type { WorktreeFetchOptions } from './worktree-fetch-options' +import { requestWorkspaceMetadataRecovery } from './workspace-metadata-recovery' + +// One producer's workspaceMetadata stream as this client has seen it: the last record seq, and per listed +// projection (repo on a host) the newest record that touched it. +type Projection = { repoId: string; hostId: ExecutionHostId; latest: number } +type ProducerCoverage = { epoch: string; lastSeq: number; projections: Map } + +const producers = new Map() + +// Encoded: environment ids (WSL ones) may contain ':', which would let one id prefix another's keys. +const environmentKeyPrefix = (environmentId: string): string => + `env:${encodeURIComponent(environmentId)}:` + +function dropEnvironmentProducers(environmentId: string, except?: string): void { + for (const key of producers.keys()) { + if (key !== except && key.startsWith(environmentKeyPrefix(environmentId))) { + producers.delete(key) + } + } +} + +// A removed or re-pointed environment's stream ends with it. +onRuntimeEnvironmentsRetired((environmentIds) => { + for (const environmentId of environmentIds) { + dropEnvironmentProducers(environmentId) + } +}) + +const projectionKey = (repoId: string, hostId: ExecutionHostId): string => + `${hostId}\u0000${repoId}` + +/** + * The producer whose cursor a host's listings and records share: this app's own main for local and + * SSH rows, or a paired environment for its rows, keyed by that pairing and connection. + */ +export function workspaceMetadataProducerKey(hostId: ExecutionHostId): string { + const parsed = parseExecutionHostId(hostId) + if (parsed?.kind !== 'runtime') { + return 'local' + } + const environmentId = parsed.environmentId + return `${environmentKeyPrefix(environmentId)}${getRuntimeEnvironmentRevision(environmentId) ?? ''}:${getRuntimeEnvironmentConnectionGeneration(environmentId)}` +} + +function producerFor(key: string, epoch: string, hostId: ExecutionHostId): ProducerCoverage { + const current = producers.get(key) + if (current?.epoch === epoch) { + return current + } + // A new epoch is a restarted producer: what it lists already includes its earlier writes. + const fresh = { epoch, lastSeq: 0, projections: new Map() } + const parsed = parseExecutionHostId(hostId) + if (parsed?.kind === 'runtime') { + // A reconnected environment is a new producer; its earlier bookkeeping dies here. + dropEnvironmentProducers(parsed.environmentId, key) + } + producers.set(key, fresh) + return fresh +} + +/** + * Notes a record before it is applied. `replayed` records are dropped; a `gap` means some earlier + * record was missed and its projection is unknown, so every projection of this producer needs a + * covering listing. A projection seen for the first time forgets those no longer listed here. + */ +export function noteWorkspaceMetadataRecord( + key: string, + epoch: string, + seq: number, + repoId: string, + hostId: ExecutionHostId, + isListed: (repoId: string, hostId: ExecutionHostId) => boolean +): { replayed: boolean; gap: boolean } { + const producer = producerFor(key, epoch, hostId) + if (seq <= producer.lastSeq) { + return { replayed: true, gap: false } + } + const gap = producer.lastSeq > 0 && seq > producer.lastSeq + 1 + producer.lastSeq = seq + const recorded = projectionKey(repoId, hostId) + if (!producer.projections.has(recorded)) { + for (const [projection, entry] of producer.projections) { + if (!isListed(entry.repoId, entry.hostId)) { + producer.projections.delete(projection) + } + } + } + producer.projections.set(recorded, { repoId, hostId, latest: seq }) + return { replayed: false, gap } +} + +/** + * After a gap, every listed projection of the producer must be listed again at or past the last seq; + * the live projections replace all earlier ones. + */ +export function requireWorkspaceMetadataCoverage( + key: string, + projections: Iterable<{ repoId: string; hostId: ExecutionHostId }> +): void { + const producer = producers.get(key) + if (!producer) { + return + } + producer.projections = new Map( + [...projections].map(({ repoId, hostId }) => [ + projectionKey(repoId, hostId), + { repoId, hostId, latest: producer.lastSeq } + ]) + ) +} + +/** + * Where a listing stands against the newest record that touched its projection. `stale` read before + * that record; `unstamped` comes from a path, host or producer run that can't say; `unknown` has nothing to check. + */ +export function workspaceMetadataListingCoverage( + key: string, + repoId: string, + hostId: ExecutionHostId, + stamp: WorkspaceMetadataCursor | undefined +): 'covered' | 'stale' | 'unstamped' | 'unknown' { + const producer = producers.get(key) + const projection = producer?.projections.get(projectionKey(repoId, hostId)) + if (!producer || !projection) { + return 'unknown' + } + // Another epoch's stamp can't be ordered against this one's records (a restart either way). + if (!stamp || stamp.epoch !== producer.epoch) { + return 'unstamped' + } + return stamp.seq >= projection.latest ? 'covered' : 'stale' +} + +/** + * A listing that read metadata before a published write must not erase what that write already showed: + * keep the current rows' issue titles on the same, still-untitled links. Never adds or restores a link. + */ +function keepPublishedLinkTitles( + incoming: T[], + current: readonly Worktree[] +): T[] { + const currentById = new Map(current.map((row) => [row.id, row])) + return incoming.map((row) => { + const previous = currentById.get(row.id) + if (!previous) { + return row + } + const titles = new Map() + for (const item of getWorkspaceAttachments(previous)) { + const title = item.title?.trim() + if (item.provider === 'github' && item.type === 'issue' && title) { + titles.set(getWorkspaceReferenceIdentity(item), title) + } + } + if (titles.size === 0) { + return row + } + let kept = false + const linkedItems = getWorkspaceAttachments(row).map((item) => { + const title = item.title?.trim() ? undefined : titles.get(getWorkspaceReferenceIdentity(item)) + if (!title) { + return item + } + kept = true + return { ...item, title } + }) + return kept ? { ...row, linkedItems } : row + }) +} + +function currentRows(state: AppState, repoId: string, hostId: ExecutionHostId): Worktree[] { + const matchOptions = worktreeHostMatchOptions(state, repoId, hostId) + return (selectWorktreesByRepo(state)[repoId] ?? []).filter((row) => + worktreeMatchesHost(row, hostId, matchOptions) + ) +} + +type FetchWorktrees = (repoId: string, options: WorktreeFetchOptions) => Promise + +/** + * A listing's place against the newest record for its repo and host, checked right before it is + * merged: a stale listing keeps already-shown titles and, once applied, asks for a fresh listing. + */ +export function listingMetadataCoverage( + state: AppState, + repoId: string, + hostId: ExecutionHostId, + refresh: AdmittedDetectedWorktreeRefresh +): { refresh: AdmittedDetectedWorktreeRefresh; settle: (fetchWorktrees: FetchWorktrees) => void } { + const key = workspaceMetadataProducerKey(hostId) + const coverage = workspaceMetadataListingCoverage( + key, + repoId, + hostId, + refresh.result.workspaceMetadata + ) + // Keeping titles already shown is always safe (it never adds or restores a link), so any listing that + // can't prove it includes the newest record keeps them. + const keep = coverage === 'stale' || coverage === 'unstamped' + return { + refresh: keep + ? { + ...refresh, + result: { + ...refresh.result, + worktrees: keepPublishedLinkTitles( + refresh.result.worktrees, + currentRows(state, repoId, hostId) + ) + } + } + : refresh, + settle: (fetchWorktrees) => { + // Whatever the stale listing dropped (a newer link, say), a listing begun now includes. + if (coverage === 'stale') { + requestWorkspaceMetadataRecovery(repoId, hostId, fetchWorktrees) + } + } + } +} diff --git a/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-recovery.ts b/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-recovery.ts new file mode 100644 index 00000000000..938afa9f88c --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/workspace-metadata-recovery.ts @@ -0,0 +1,40 @@ +import { + LOCAL_EXECUTION_HOST_ID, + type ExecutionHostId +} from '../../../../../../shared/execution-host' +import type { WorktreeFetchOptions } from './worktree-fetch-options' + +type FetchWorktrees = (repoId: string, options: WorktreeFetchOptions) => Promise + +// One recovery listing per repo and host at a time; a request during one runs once more after it. +const inFlight = new Set() +const rerun = new Set() + +/** + * Lists a repo afresh (never joining a listing that may predate a published metadata write). The + * listing's own coverage check asks again if it still turns out stale. + */ +export function requestWorkspaceMetadataRecovery( + repoId: string, + hostId: ExecutionHostId, + fetchWorktrees: FetchWorktrees +): void { + const key = `${hostId}\u0000${repoId}` + if (inFlight.has(key)) { + rerun.add(key) + return + } + inFlight.add(key) + const options: WorktreeFetchOptions = + hostId === LOCAL_EXECUTION_HOST_ID + ? { forceLocalOwner: true, forceFresh: true, suppressRemoteLineageRefresh: true } + : { executionHostId: hostId, forceFresh: true, suppressRemoteLineageRefresh: true } + void fetchWorktrees(repoId, options) + .catch(() => undefined) + .finally(() => { + inFlight.delete(key) + if (rerun.delete(key)) { + requestWorkspaceMetadataRecovery(repoId, hostId, fetchWorktrees) + } + }) +} diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-fetch-options.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-fetch-options.ts index a4ba5fb93a8..f3375da59b0 100644 --- a/src/renderer/src/store/slices/worktrees/listing/worktree-fetch-options.ts +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-fetch-options.ts @@ -9,6 +9,8 @@ export type WorktreeFetchOptions = { forceLocalOwner?: boolean /** Skip automatic remote lineage when the caller owns a final host-wide refresh. */ suppressRemoteLineageRefresh?: boolean + /** Start a new listing instead of joining one in flight (it may predate a published metadata write). */ + forceFresh?: boolean } export type DirectSshWorktreeFetchOptions = WorktreeFetchOptions & { 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..4af41008656 --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it, vi } from 'vitest' +import type { WorkspaceAttachment } from '../../../../../../shared/worktree/types' +import type { AppState } from '../../../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' +import { listingMetadataCoverage, noteWorkspaceMetadataRecord } from './workspace-metadata-coverage' +import type { AdmittedDetectedWorktreeRefresh } from './worktree-slice-types' + +const ID = 'repo-1::/work/orca' +const issue = (title?: string): WorkspaceAttachment[] => [ + { provider: 'github', type: 'issue', number: 42, ...(title ? { title } : {}) } +] +const local = { kind: 'local' as const } + +function state(linkedItems: WorkspaceAttachment[] = issue()): AppState { + const linkedIssue = linkedItems.length > 0 ? 42 : null + return { + ...useAppStore.getInitialState(), + repos: [makeRepo()], + worktreesByRepo: { + 'repo-1': [ + makeWorktree(ID, 'local orca', { hostId: 'local', linkedIssue, linkedItems }), + makeWorktree(ID, 'ssh orca', { hostId: 'ssh:build-box', linkedIssue, linkedItems }) + ] + } + } +} + +function record(seq: number, epoch: string, hostId: 'local' | 'ssh:build-box' = 'ssh:build-box') { + return { + kind: 'set' as const, + domain: 'workspaceMetadata' as const, + hostId, + epoch, + seq, + id: `${hostId}::${ID}`, + repoId: 'repo-1', + worktreeId: ID, + row: { + linkedItems: issue('Fix login'), + linkedWorkItem: null, + linkedIssue: 42, + linkedTaskSourceContext: null + } + } +} + +const linksOn = (value: AppState, hostId: string) => + selectWorktreesByRepo(value)['repo-1'].find((row) => row.hostId === hostId)?.linkedItems + +describe('addressed workspace metadata records', () => { + it('title only the named host row, and never bring back an unlinked issue', () => { + const { patch, applied } = patchWorktreeMetadataSet(state(), record(1, 'e1'), local) + const titled = { ...state(), ...patch } + expect(applied).toBe(true) + expect(linksOn(titled, 'ssh:build-box')).toEqual(issue('Fix login')) + expect(linksOn(titled, 'local')).toEqual(issue()) + + expect(patchWorktreeMetadataSet(state([]), record(2, 'e1'), local)).toEqual({ + patch: null, + applied: false + }) + + // A second titled link the row doesn't list yet still needs a listing. + const twoLinks = record(3, 'e1') + twoLinks.row.linkedItems = [ + ...issue('Fix login'), + { provider: 'github', type: 'issue', number: 43, title: 'Fix logout' } + ] + expect(patchWorktreeMetadataSet(state(), twoLinks, local).applied).toBe(false) + }) + + it('keeps a shown title through a listing that predates it, then lists the repo afresh', async () => { + noteWorkspaceMetadataRecord('local', 'e2', 7, 'repo-1', 'local', () => true) + const shown = { + ...state(), + ...patchWorktreeMetadataSet(state(), record(7, 'e2', 'local'), local).patch + } + const listing = (seq: number): AdmittedDetectedWorktreeRefresh => ({ + status: 'admitted', + executionHostId: 'local', + result: { + repoId: 'repo-1', + authoritative: true, + source: 'git', + workspaceMetadata: { epoch: 'e2', seq }, + worktrees: [ + { + ...makeWorktree(ID, 'local orca', { linkedIssue: 42, linkedItems: issue() }), + ownership: 'orca-managed', + selectedCheckout: false, + visible: true + } + ] + } + }) + const fetchWorktrees = vi.fn(async () => true) + + const stale = listingMetadataCoverage(shown, 'repo-1', 'local', listing(6)) + expect(stale.refresh.result.worktrees[0].linkedItems).toEqual(issue('Fix login')) + stale.settle(fetchWorktrees) + expect(fetchWorktrees).toHaveBeenCalledWith('repo-1', { + forceLocalOwner: true, + forceFresh: true, + suppressRemoteLineageRefresh: true + }) + + const covering = listingMetadataCoverage(shown, 'repo-1', 'local', listing(7)) + expect(covering.refresh.result.worktrees[0].linkedItems).toEqual(issue()) + covering.settle(fetchWorktrees) + expect(fetchWorktrees).toHaveBeenCalledTimes(1) + // A listing that read before record 7 and lands after the covering one still keeps the title, and + // lists again for anything else it dropped. + const late = listingMetadataCoverage(shown, 'repo-1', 'local', listing(6)) + expect(late.refresh.result.worktrees[0].linkedItems).toEqual(issue('Fix login')) + late.settle(fetchWorktrees) + await vi.waitFor(() => expect(fetchWorktrees).toHaveBeenCalledTimes(2)) + }) +}) 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..fd89ff6bc07 --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-metadata-set-patch.ts @@ -0,0 +1,83 @@ +import { + parseExecutionHostId, + toRuntimeExecutionHostId +} from '../../../../../../shared/execution-host' +import type { Worktree } from '../../../../../../shared/worktree/types' +import type { WorkspaceMetadataSet } from '../../../../../../shared/worktree/workspace-metadata-set' +import { getWorkspaceAttachments } from '../../../../../../shared/workspace-attachments/workspace-attachments' +import { getWorkspaceReferenceIdentity } from '../../../../../../shared/workspace-attachments/workspace-reference-identity' +import type { AppState } from '../../../types' +import { worktreeHostMatchOptions, worktreeMatchesHost } from './worktree-host-ownership' +import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' + +/** Where a record came from: this app's own main, or a paired host's runtime event stream. */ +export type MetadataSetSource = { kind: 'local' } | { kind: 'environment'; environmentId: string } + +// The row a record names, by its own execution host; a paired host's SSH twin is a different row. +function rowMatcher( + state: AppState, + set: WorkspaceMetadataSet, + source: MetadataSetSource +): (row: Worktree) => boolean { + if (source.kind === 'local') { + const options = worktreeHostMatchOptions(state, set.repoId, set.hostId) + return (row) => row.id === set.worktreeId && worktreeMatchesHost(row, set.hostId, options) + } + const environmentHost = toRuntimeExecutionHostId(source.environmentId) + const options = worktreeHostMatchOptions(state, set.repoId, environmentHost) + const sshHost = parseExecutionHostId(set.hostId)?.kind === 'ssh' ? set.hostId : null + return (row) => + row.id === set.worktreeId && + worktreeMatchesHost(row, environmentHost, options) && + (sshHost ? row.hostId === sshHost : parseExecutionHostId(row.hostId ?? null)?.kind !== 'ssh') +} + +/** + * Fills a producer's addressed `workspaceMetadata` record into the row it names. The only producer + * today saves issue titles, so only still-untitled links with the same identity take a title; the + * record's links never replace the row's. `applied` is false when the row or link isn't listed yet. + */ +export function patchWorktreeMetadataSet( + state: AppState, + set: WorkspaceMetadataSet, + source: MetadataSetSource +): { patch: Pick | null; applied: boolean } { + const titles = new Map() + for (const item of set.row.linkedItems ?? []) { + const title = item.title?.trim() + if (item.provider === 'github' && item.type === 'issue' && title) { + titles.set(getWorkspaceReferenceIdentity(item), title) + } + } + const rows = selectWorktreesByRepo(state)[set.repoId] + const index = titles.size > 0 && rows ? rows.findIndex(rowMatcher(state, set, source)) : -1 + if (!rows || index === -1) { + return { patch: null, applied: titles.size === 0 } + } + const seen = new Set() + let filled = false + const linkedItems = getWorkspaceAttachments(rows[index]).map((item) => { + const identity = getWorkspaceReferenceIdentity(item) + const title = titles.get(identity) + if (!title) { + return item + } + seen.add(identity) + if (item.title?.trim()) { + return item + } + filled = true + return { ...item, title } + }) + // Every titled link must be listed here; one that isn't needs a listing that includes it. + const applied = seen.size === titles.size + if (!filled) { + return { patch: null, applied } + } + const next = rows.slice() + next[index] = { ...rows[index], linkedItems } + return { + patch: { worktreesByRepo: { ...selectWorktreesByRepo(state), [set.repoId]: next } }, + applied + } +} diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts index e4094088a09..8abc30b2011 100644 --- a/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts @@ -34,6 +34,8 @@ export type DetectedWorktreeRefreshOptions = BackgroundRuntimeRefreshOptions & { // Why a callback: staleness is judged against the client's live applied version, which a // create or remove reply can advance while the listing is in flight. isStaleCatalogPublication?: (result: DetectedWorktreeListResult) => boolean + // Start a new listing instead of joining one in flight (it may predate a published metadata write). + forceFresh?: boolean } export type AdmittedDetectedWorktreeRefresh = { diff --git a/src/renderer/src/store/slices/worktrees/metadata/update-worktree-meta.ts b/src/renderer/src/store/slices/worktrees/metadata/update-worktree-meta.ts index 77d3c6969e9..b015759b24e 100644 --- a/src/renderer/src/store/slices/worktrees/metadata/update-worktree-meta.ts +++ b/src/renderer/src/store/slices/worktrees/metadata/update-worktree-meta.ts @@ -120,7 +120,8 @@ export function createUpdateWorktreeMeta( return { ok: true } } normalizedUpdates = normalizeGitHubPRSuppressionUpdate( - normalizeWorkspaceAttachmentUpdate(worktreeForUpdate, mutationUpdates) + normalizeWorkspaceAttachmentUpdate(worktreeForUpdate, mutationUpdates), + worktreeForUpdate?.linkedPR ) const currentResolvedPushTarget = normalizedUpdates.linkedPR === linkedPrForPushTarget ? resolvedPushTarget : undefined 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/github-pr-suppression.ts b/src/shared/worktree/github-pr-suppression.ts index f89ccbfc8e2..e7d671e59ce 100644 --- a/src/shared/worktree/github-pr-suppression.ts +++ b/src/shared/worktree/github-pr-suppression.ts @@ -10,10 +10,14 @@ export function isGitHubPRSuppressed( return linkedPR === null && suppressedGitHubPR === prNumber } +/** Selecting a PR lifts a suppression; restating the already-selected PR leaves it alone. */ export function normalizeGitHubPRSuppressionUpdate( - updates: Partial + updates: Partial, + currentLinkedPR?: number | null ): Partial { - return typeof updates.linkedPR === 'number' && updates.linkedPR > 0 + return typeof updates.linkedPR === 'number' && + updates.linkedPR > 0 && + updates.linkedPR !== currentLinkedPR ? { ...updates, suppressedGitHubPR: null } : updates } diff --git a/src/shared/worktree/types.ts b/src/shared/worktree/types.ts index 1eb076a08ff..3bf89f8e919 100644 --- a/src/shared/worktree/types.ts +++ b/src/shared/worktree/types.ts @@ -258,6 +258,8 @@ export type DetectedWorktreeListResult = { failureKind?: WorktreeScanFailureKind /** Which catalog this listing describes; additive, older hosts omit it. */ catalogVersion?: WorktreeCatalogVersion + /** The producer's workspaceMetadata position when this listing read metadata; additive, older hosts omit it. */ + workspaceMetadata?: { epoch: string; seq: number } /** The repo's WSL distro is stopped or unverifiable, so rows are stored ones; additive, older hosts omit it. */ wslDistroStopped?: { distro: string; state: 'stopped' | 'unverifiable' } } diff --git a/src/shared/worktree/workspace-metadata-set.ts b/src/shared/worktree/workspace-metadata-set.ts new file mode 100644 index 00000000000..b66b8550e8e --- /dev/null +++ b/src/shared/worktree/workspace-metadata-set.ts @@ -0,0 +1,84 @@ +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' + +/** A producer's `workspaceMetadata` position: records with `seq` at or below it are in what it read. */ +export type WorkspaceMetadataCursor = { epoch: string; seq: number } + +/** 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 = { + kind: 'set' + domain: 'workspaceMetadata' + 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 { kind, domain, epoch, seq, id, repoId, worktreeId, row } = value + const hostId = normalizeExecutionHostId(typeof value.hostId === 'string' ? value.hostId : null) + if ( + kind !== 'set' || + domain !== 'workspaceMetadata' || + !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 { + kind, + domain, + hostId, + epoch, + seq, + id, + repoId, + worktreeId, + row: { + linkedItems: normalizeWorkspaceAttachments(row.linkedItems), + linkedWorkItem: normalizeWorkspaceLinkedItem(row.linkedWorkItem), + linkedIssue: row.linkedIssue, + linkedTaskSourceContext: normalizeStoredTaskSourceContext(row.linkedTaskSourceContext) + } + } +}