diff --git a/cloud/apps/relay-edge/src/host-relay-handshake.ts b/cloud/apps/relay-edge/src/host-relay-handshake.ts index bc153be8a0c..22614a1fe85 100644 --- a/cloud/apps/relay-edge/src/host-relay-handshake.ts +++ b/cloud/apps/relay-edge/src/host-relay-handshake.ts @@ -191,7 +191,7 @@ export abstract class HostRelayHandshake extends HostRelayBase { }) // After the ack, which strict shipped parsers must see unchanged; only hosts that asked get it. if (a.clientKeepalive) { this.send(ws, { type: 'keepalive-offer', v: 1, intervalMs: this.config.pingIntervalMs }) } - metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [], '', a.place) + metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [], a.clientKeepalive ? 'keepalive' : 'legacy', a.place) await this.reschedule() } } diff --git a/cloud/apps/relay-edge/src/host-relay.ts b/cloud/apps/relay-edge/src/host-relay.ts index 958232f8ff4..14f5a0f544f 100644 --- a/cloud/apps/relay-edge/src/host-relay.ts +++ b/cloud/apps/relay-edge/src/host-relay.ts @@ -187,7 +187,8 @@ export class HostRelay extends HostRelayPhones { // Same order as the cells' heartbeat: expired auth past its grace, then the 6 h lease. if (now > a.claims.exp + CONTROL_CONTINUITY_LIMITS.expiredAuthExistingSpliceGraceMs) { const sinceRefreshS = a.lastRefreshAt === undefined ? -1 : Math.round((now - a.lastRefreshAt) / 1000) - metric(this.env, 'auth_expired_close', sinceRefreshS, a.lastRefreshAt === undefined ? 'never' : 'refreshed', [], '', a.place) + const seenAgoS = Math.round((now - seen) / 1000) + metric(this.env, 'auth_expired_close', sinceRefreshS, a.lastRefreshAt === undefined ? 'never' : 'refreshed', [seenAgoS], this.keepalive(a) ? 'keepalive' : 'legacy', a.place) this.close(ws, RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, 'relay authorization expired') await this.onSocketGone(ws, RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, '') continue diff --git a/cloud/apps/relay-edge/src/metrics.ts b/cloud/apps/relay-edge/src/metrics.ts index 7d87b759e4d..febc2bab77c 100644 --- a/cloud/apps/relay-edge/src/metrics.ts +++ b/cloud/apps/relay-edge/src/metrics.ts @@ -2,6 +2,7 @@ import type { Env } from './env' export type MetricEvent = + // label 'new' | 'rebind'; reason 'keepalive' | 'legacy' (took the keepalive offer or not). | 'control_active' | 'control_close' | 'phone_open' @@ -26,6 +27,7 @@ export type MetricEvent = | 'control_upgrade' // Control closed 4401 for expired authorization: value = seconds since its last extending // refresh, label 'refreshed'; -1 and label 'never' when this socket never extended its token. + // double2 = seconds since the host's last inbound frame or keepalive; reason 'keepalive' | 'legacy'. | 'auth_expired_close' // Pre-auth socket refused by the per-source limiter: label 'phone' | 'data' | 'health'. Unpushed-host phones: 'not_on_edge'. | 'preauth_limited' diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 36b07604a3e..3437945403d 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -479,7 +479,7 @@ 2 src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts 1 src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts 2 src/main/runtime/push/push-unregister-outbox.ts -2 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts +1 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts 1 src/main/runtime/rpc/server/network-source-policy-store.ts 2 src/main/runtime/rpc/server/pairing/device-registry-corruption.ts 2 src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts diff --git a/mobile/src/mobile-web-shell/generation-store-file-system.test.ts b/mobile/src/mobile-web-shell/generation-store-file-system.test.ts index 7b170ea268f..644f2c83d96 100644 --- a/mobile/src/mobile-web-shell/generation-store-file-system.test.ts +++ b/mobile/src/mobile-web-shell/generation-store-file-system.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it, vi } from 'vitest' -// Mock the import-time native module to test only the URI converter. +// Mock the import-time native modules to test only the URI converter. vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: { cache: '' } })) +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) import { generationDirectoryPath } from './generation-store-file-system' diff --git a/mobile/src/mobile-web-shell/generation-store-file-system.ts b/mobile/src/mobile-web-shell/generation-store-file-system.ts index 74189aeb408..06aa62f880e 100644 --- a/mobile/src/mobile-web-shell/generation-store-file-system.ts +++ b/mobile/src/mobile-web-shell/generation-store-file-system.ts @@ -1,4 +1,5 @@ import { Directory, File } from 'expo-file-system' +import { Platform } from 'react-native' export type GenerationDirectoryEntry = { readonly name: string @@ -127,7 +128,23 @@ export function createExpoGenerationFileSystem(rootUri: string): GenerationFileS } }, async moveDirectory(fromUri, toUri) { - new Directory(fromUri).move(new Directory(toUri)) + const from = new Directory(fromUri) + // Below API 26, Expo 55's move copies a directory without its contents; its copy is recursive. + if (Platform.OS === 'android' && Number(Platform.Version) < 26) { + const to = new Directory(toUri) + try { + from.copy(to) + } catch (error) { + // Readers trust a generation by its manifest, so a failed copy must leave no partial tree. + if (to.exists) { + to.delete() + } + throw error + } + from.delete() + return + } + from.move(new Directory(toUri)) }, async moveFile(fromUri, toUri) { new File(fromUri).move(new File(toUri)) diff --git a/mobile/src/mobile-web-shell/generation-store.ts b/mobile/src/mobile-web-shell/generation-store.ts index 0e78ad2a2d6..45f54c2772b 100644 --- a/mobile/src/mobile-web-shell/generation-store.ts +++ b/mobile/src/mobile-web-shell/generation-store.ts @@ -216,7 +216,7 @@ export function createGenerationStore(options: { manifest: staged.manifest } const entries = await fs.list(generations) - // A build-id directory alone proves nothing: pre-API-26 Android moves can leave it empty. Require its activation manifest before reusing it. + // A build-id directory alone proves nothing; require its activation manifest before reusing it. const existing = entries.find((entry) => entry.name === staged.buildId) if ( existing?.isDirectory === true && @@ -238,7 +238,7 @@ export function createGenerationStore(options: { } await fs.createDirectory(generations) await fs.moveDirectory(staged.directory, target) - // Below API 26, Expo Android FileSystemPath.kt moves directories via non-recursive copy/delete and can leave an empty target; failed source deletion leaves tmp for sweeping. + // Never activate a target without its manifest; a source left in tmp is swept. if (!(await fs.fileExists(joinUri(target, MANIFEST_FILE_NAME)))) { await fs.delete(target) throw new Error(`generation ${staged.buildId} did not carry its manifest through the rename`) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts index b023ae70955..f5b1619252e 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts @@ -7,6 +7,7 @@ const doubles = vi.hoisted(() => ({ })) vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: { cache: '' } })) +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) // The runner's deadlines live in the runtime module, whose foreground timer reads React Native's AppState. vi.mock('./foreground-timer', () => ({ setForegroundTimer: () => () => {} })) vi.mock('../transport/rpc/rpc-operation', () => ({ diff --git a/skill-guides/orca-cli/references/browser.md b/skill-guides/orca-cli/references/browser.md index d10112b75f0..8e9564eab9a 100644 --- a/skill-guides/orca-cli/references/browser.md +++ b/skill-guides/orca-cli/references/browser.md @@ -71,6 +71,7 @@ Browser rules: - Pass `--page ` on every command that acts on one page; `ORCA --help` lists `--page` when it does. `tab list`, `tab current`, `tab create` and `open-url` take no `--page`, and `tab switch`/`tab close` pick a tab by `--index` or `--page`, never both, since `--page` wins. Take the ID from `result.tab.browserPageId` in `ORCA tab current --json` or `result.browserPageId` in `ORCA tab create --json` and keep it for the task; `tab current` shows the routed tab, not the one you pin. When the user means a specific tab, find it by URL or title in `ORCA tab list --json`. - Without `--page`, a command goes to the worktree's current tab. That stays the agent's tab while it has had a command in the last 20 seconds or so, even after the user picks another (`tab current` reports it too), then moves to the user's pick. - After `ORCA tab switch`, pass the new page's `browserPageId`. +- When the user says they left notes or comments on a page, read them with `ORCA tab annotations --page ` (the current tab without `--page`). It prints the notes they haven't sent, the same text the tab's Copy button gives, and `--json` returns them in `result.annotations`. Notes the user already sent arrive in your chat instead. - A popup window a page opens (sign-in, payment) is listed in `ORCA tab list --json` as a `popup-` page with `openerBrowserPageId`. If a click seems to do nothing, check `tab list`, then drive the popup with `--page popup-`. When it closes, continue on the opener page. - Browser commands default to the current worktree. `--page` reaches the page in any worktree unless you also pass `--worktree `. Use `--worktree all` only intentionally. - `tab list` shows every tab in the tab bar. After a restart, tabs the user has not opened report `loaded: false`; `tab switch` or any `--page` command loads one in the background without changing the user's visible tab. diff --git a/src/cli/browser/browser-format.ts b/src/cli/browser/browser-format.ts index 63a3d5d814f..ac3e7122022 100644 --- a/src/cli/browser/browser-format.ts +++ b/src/cli/browser/browser-format.ts @@ -1,10 +1,12 @@ import { readBrowserActionEffects } from '../../shared/browser-action-effects' import { writeCliScreenshotTempFile } from '../cli-screenshot-temp-file' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' +import { formatBrowserAnnotationsAsMarkdown } from '../../shared/browser/annotations/browser-annotation-output' import type { BrowserProfileListResult, BrowserScreenshotResult, BrowserSnapshotResult, + BrowserTabAnnotationsResult, BrowserTabCurrentResult, BrowserTabListResult, BrowserTabProfileCloneResult, @@ -132,6 +134,13 @@ export function formatTabShow(result: BrowserTabShowResult | BrowserTabCurrentRe ].join('\n') } +// The same text the tab's Copy button gives, so an agent reads what the user would send. +export function formatTabAnnotations(result: BrowserTabAnnotationsResult): string { + return result.annotations.length > 0 + ? formatBrowserAnnotationsAsMarkdown(result.annotations) + : `No unsent notes on tab ${result.tab.browserPageId}` +} + export function formatTabProfileShow(result: BrowserTabProfileShowResult): string { return [ `page: ${result.browserPageId}`, diff --git a/src/cli/browser/browser-tab.ts b/src/cli/browser/browser-tab.ts index 74edfe04e53..7ee72d93664 100644 --- a/src/cli/browser/browser-tab.ts +++ b/src/cli/browser/browser-tab.ts @@ -1,11 +1,17 @@ import type { + BrowserTabAnnotationsResult, BrowserTabCurrentResult, BrowserTabListResult, BrowserTabShowResult, BrowserTabSwitchResult } from '../../shared/browser/runtime/runtime-browser-contracts' import type { CommandHandler } from '../dispatch' -import { formatTabList, formatTabListWithProfiles, formatTabShow } from './browser-format' +import { + formatTabAnnotations, + formatTabList, + formatTabListWithProfiles, + formatTabShow +} from './browser-format' import { printResult } from '../format' import { getOptionalNonNegativeIntegerFlag, @@ -42,6 +48,11 @@ export const BROWSER_TAB_HANDLERS: Record = { const result = await client.call('browser.tabShow', target) printResult(result, json, formatTabShow) }, + 'tab annotations': async ({ flags, client, cwd, json }) => { + const target = await getBrowserCommandTarget(flags, cwd, client) + const result = await client.call('browser.tabAnnotations', target) + printResult(result, json, formatTabAnnotations) + }, 'tab current': async ({ flags, client, cwd, json }) => { const worktree = await getBrowserWorktreeSelector(flags, cwd, client) const result = await client.call('browser.tabCurrent', { worktree }) diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 6aaf42ad5c4..f9f46a79606 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -740,6 +740,7 @@ const ORCA_CLI_BROWSER_REFERENCE_MARKDOWN = [ "- Pass `--page ` on every command that acts on one page; `ORCA --help` lists `--page` when it does. `tab list`, `tab current`, `tab create` and `open-url` take no `--page`, and `tab switch`/`tab close` pick a tab by `--index` or `--page`, never both, since `--page` wins. Take the ID from `result.tab.browserPageId` in `ORCA tab current --json` or `result.browserPageId` in `ORCA tab create --json` and keep it for the task; `tab current` shows the routed tab, not the one you pin. When the user means a specific tab, find it by URL or title in `ORCA tab list --json`.", "- Without `--page`, a command goes to the worktree's current tab. That stays the agent's tab while it has had a command in the last 20 seconds or so, even after the user picks another (`tab current` reports it too), then moves to the user's pick.", "- After `ORCA tab switch`, pass the new page's `browserPageId`.", + "- When the user says they left notes or comments on a page, read them with `ORCA tab annotations --page ` (the current tab without `--page`). It prints the notes they haven't sent, the same text the tab's Copy button gives, and `--json` returns them in `result.annotations`. Notes the user already sent arrive in your chat instead.", "- A popup window a page opens (sign-in, payment) is listed in `ORCA tab list --json` as a `popup-` page with `openerBrowserPageId`. If a click seems to do nothing, check `tab list`, then drive the popup with `--page popup-`. When it closes, continue on the opener page.", "- Browser commands default to the current worktree. `--page` reaches the page in any worktree unless you also pass `--worktree `. Use `--worktree all` only intentionally.", "- `tab list` shows every tab in the tab bar. After a restart, tabs the user has not opened report `loaded: false`; `tab switch` or any `--page` command loads one in the background without changing the user's visible tab.", diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 10e3f99ae0a..0b0415336b9 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -207,6 +207,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' tab create Create a new browser tab (navigates to --url)', ' tab list List open browser tabs', ' tab show Show one browser tab by page id', + " tab annotations Show a tab's unsent notes from the user", ' tab current Show the current browser tab', ' tab profile list List browser session profiles', ' tab profile create Create a browser session profile', diff --git a/src/cli/specs/browser-basic.ts b/src/cli/specs/browser-basic.ts index 2d9ea0f589e..b25628d9e4a 100644 --- a/src/cli/specs/browser-basic.ts +++ b/src/cli/specs/browser-basic.ts @@ -206,6 +206,12 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = withBrowserPageTarget( usage: 'orca tab show --page [--worktree ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'page', 'worktree'] }, + { + path: ['tab', 'annotations'], + summary: "Show the notes the user left on a browser tab and hasn't sent yet", + usage: 'orca tab annotations [--page ] [--worktree ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'page', 'worktree'] + }, { path: ['tab', 'current'], summary: 'Show the current browser tab', diff --git a/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts b/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts index abff471a47b..888cdbb736a 100644 --- a/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts +++ b/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts @@ -256,22 +256,3 @@ function urlOrigin(value: unknown): string | null { return null } } - -// Routed tabs can still display local files; those remain off-limits to hosts. -// Allow chrome-error: so hosts can navigate away from failed loads. -const HOST_REACHABLE_DOCUMENT_PROTOCOLS = new Set([ - 'http:', - 'https:', - 'about:', - 'blob:', - 'data:', - 'chrome-error:' -]) - -export function isHostReachableDocument(url: string): boolean { - try { - return HOST_REACHABLE_DOCUMENT_PROTOCOLS.has(new URL(url).protocol) - } catch { - return url === '' - } -} diff --git a/src/main/git/command-runner/gh-exec-file.ts b/src/main/git/command-runner/gh-exec-file.ts index dcc7a3c67d0..9eb9b7c973a 100644 --- a/src/main/git/command-runner/gh-exec-file.ts +++ b/src/main/git/command-runner/gh-exec-file.ts @@ -21,6 +21,7 @@ import { execFileCaptureToTermination } from './exec-file-capture' import { logHostedCliDeadlineKill } from './hosted-cli-deadline-log' import type { GitExecOptions } from './git-exec-options' import { argsLookIdempotent } from './gh-idempotency' +import { GhExecutableAbsenceBatch } from './gh-executable-absence-batch' import { applyGhHostToArgs, explicitGhHostname, explicitGhRepoHostname } from './gh-host-args' import { isGhBoundAccountError, resolveBoundGhExecEnv } from './gh-bound-account-env' import { @@ -178,6 +179,13 @@ export async function ghExecFileWithScopeAsync( if (lifetime) { await lifetime.waitPending(options.signal) } + const availability = GhExecutableAbsenceBatch.assertAvailable( + resolved, + boundEnv ?? options.env ?? process.env + ) + if (availability) { + await availability + } // gh may be a shim chain; terminate the whole tree so descendants cannot outlive the deadline. const { stdout, stderr } = await execFileCaptureToTermination( resolved.binary, @@ -198,6 +206,7 @@ export async function ghExecFileWithScopeAsync( if (lifetime) { await lifetime.waitPending(options.signal) } + GhExecutableAbsenceBatch.recordSuccess(resolved, boundEnv ?? options.env ?? process.env) return { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Capture decodes stdout with the requested string encoding above. stdout: stdout as string, @@ -277,6 +286,11 @@ export async function ghExecFileWithScopeAsync( await sleep(delayMs, options.signal) continue } + await GhExecutableAbsenceBatch.recordMissing( + resolved, + boundEnv ?? options.env ?? process.env, + err + ) throw err } finally { lifetime?.seal() diff --git a/src/main/git/command-runner/gh-executable-absence-batch.ts b/src/main/git/command-runner/gh-executable-absence-batch.ts new file mode 100644 index 00000000000..a2362641c3a --- /dev/null +++ b/src/main/git/command-runner/gh-executable-absence-batch.ts @@ -0,0 +1,116 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { stat } from 'node:fs/promises' +import path from 'node:path' +import { + isCommandOnLocalPath, + resolveSelectedLocalCommand +} from '../../ipc/command-path/command-path-resolver' +import type { ResolvedCommand } from './wsl-command-resolution' + +const currentBatch = new AsyncLocalStorage() +const batches = new Set() + +function searchScope(command: ResolvedCommand, env: NodeJS.ProcessEnv): string | null { + if (command.wsl || command.binary !== 'gh' || !command.cwd) { + return null + } + const pathKey = Object.keys(env).find((key) => + process.platform === 'win32' ? key.toLowerCase() === 'path' : key === 'PATH' + ) + const searchPath = pathKey ? env[pathKey] : undefined + if (!searchPath || searchPath.split(path.delimiter).some((entry) => !path.isAbsolute(entry))) { + return null + } + const extensions = Object.entries(env).find(([key]) => key.toLowerCase() === 'pathext')?.[1] + return JSON.stringify([process.platform, command.binary, searchPath, extensions]) +} + +/** A finite recovery batch shares only proved native executable absence, never API failures. */ +export class GhExecutableAbsenceBatch { + private readonly missing = new Map() + + constructor() { + batches.add(this) + } + + run(operation: () => Promise): Promise { + return currentBatch.run(this, operation) + } + + close(): void { + batches.delete(this) + this.missing.clear() + } + + static assertAvailable(command: ResolvedCommand, env: NodeJS.ProcessEnv): Promise | null { + const batch = currentBatch.getStore() + if (!batch?.missing.size) { + return null + } + const scope = searchScope(command, env) + if (!scope || !batch.missing.has(scope)) { + return null + } + if (resolveSelectedLocalCommand('gh', { env, cwd: command.cwd }) !== 'gh') { + batch.missing.delete(scope) + return null + } + if (process.platform === 'win32') { + // Windows searches each checkout before PATH; a peer may have its own executable. + const localEnv = Object.fromEntries( + Object.entries(env).filter(([key]) => key.toLowerCase() !== 'path') + ) + return isCommandOnLocalPath('gh', { + env: { ...localEnv, PATH: '' }, + cwd: command.cwd + }).then((found) => { + if (!found) { + throw batch.missing.get(scope) + } + }) + } + throw batch.missing.get(scope) + } + + static async recordMissing( + command: ResolvedCommand, + env: NodeJS.ProcessEnv, + error: unknown + ): Promise { + const batch = currentBatch.getStore() + const scope = batch && searchScope(command, env) + if ( + !batch || + !scope || + !error || + typeof error !== 'object' || + !('code' in error) || + error.code !== 'ENOENT' || + batch.missing.get(scope) === error + ) { + return + } + try { + if ( + command.cwd && + (await stat(command.cwd)).isDirectory() && + resolveSelectedLocalCommand('gh', { env, cwd: command.cwd }) === 'gh' && + !(await isCommandOnLocalPath('gh', { env, cwd: command.cwd })) && + batches.has(batch) + ) { + batch.missing.set(scope, error) + } + } catch { + // A missing cwd or unreadable search environment proves nothing about peer checkouts. + } + } + + static recordSuccess(command: ResolvedCommand, env: NodeJS.ProcessEnv): void { + const scope = batches.size && searchScope(command, env) + if (scope) { + for (const batch of batches) { + batch.missing.delete(scope) + } + } + } +} diff --git a/src/main/github/client/fetch/repo-slug-upstream.ts b/src/main/github/client/fetch/repo-slug-upstream.ts index 4cbf567f238..4184817e685 100644 --- a/src/main/github/client/fetch/repo-slug-upstream.ts +++ b/src/main/github/client/fetch/repo-slug-upstream.ts @@ -1,4 +1,12 @@ -import { ghExecFileAsync, acquire, release, type OwnerRepo } from '../../gh-utils' +import { + ghExecFileAsync, + acquire, + release, + getRemoteUrlForRepo, + githubRepoContext, + parseGitHubRemoteIdentity, + type OwnerRepo +} from '../../gh-utils' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions @@ -10,6 +18,17 @@ import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +import { withSharedRemoteUrlReads } from '../../../git/remotes/remote-url-probe' +import { isStableMissingGitRemoteError } from '../../../git/remotes/stable-missing-git-remote-error' +import { + normalizeForgeWebHost, + foldWwwHostAlias +} from '../../../../shared/git/remotes/git-remote-host-alias' +import { + gitHubSshConfigHostAlias, + effectiveGitHubRemoteHost +} from '../../github-remote-identity-parsing' +import { resolveSshConfigHostname } from '../../github-ssh-host-alias-resolution' import { hostedReviewLocalGitOptionArgs, sameOwnerRepo } from './../github-exec-scope' export async function getRepoSlug( repoPath: string, @@ -23,55 +42,122 @@ export async function getRepoSlug( ) } -/** Best-effort fork parent for indicators/avatar selection; failures return null. */ +export type RepoUpstreamProbe = { + // Undefined is unavailable evidence, never a durable non-fork verdict. + upstream: OwnerRepo | null | undefined + origin: GitHubApiRepository | null +} + +export async function probeRepoUpstream( + repoPath: string, + connectionId?: string | null, + options: HostedReviewExecutionOptions = {}, + resolveParent = true +): Promise { + return withSharedRemoteUrlReads(async () => { + let origin: GitHubApiRepository | null = null + try { + const localGitOptions = hostedReviewLocalGitOptionArgs(options)[0] ?? {} + const context = githubRepoContext(repoPath, connectionId, localGitOptions) + let url: string | null + try { + url = await getRemoteUrlForRepo(context, 'origin') + } catch (error) { + if (isStableMissingGitRemoteError(error)) { + return { upstream: null, origin } + } + throw error + } + // An unserved remote host is not evidence of a missing origin. + if (url === null) { + return { upstream: undefined, origin } + } + const parsed = parseGitHubRemoteIdentity(url) + if (!parsed) { + return { upstream: null, origin } + } + let host = parsed.host + let hostResolved = true + const alias = gitHubSshConfigHostAlias(url) + if (alias) { + const resolved = await resolveSshConfigHostname(alias, context) + if (resolved.resolved && resolved.hostname) { + host = effectiveGitHubRemoteHost(host, resolved.hostname) + } else { + hostResolved = false + } + } + const forgeHost = normalizeForgeWebHost(foldWwwHostAlias(host)) + if (hostResolved && (forgeHost === 'gitlab.com' || forgeHost === 'bitbucket.org')) { + return { upstream: null, origin } + } + const execution = await resolveGitHubRepoExecution( + repoPath, + undefined, + connectionId, + localGitOptions + ) + origin = execution.ownerRepo + // Missing auth for an arbitrary custom host does not prove it is another forge. + if (!origin || !resolveParent) { + return { upstream: undefined, origin } + } + const upstream = await getGitHubApiRepositoryForRemote( + repoPath, + 'upstream', + connectionId, + localGitOptions + ) + if (upstream && !sameOwnerRepo(upstream, origin)) { + return { upstream, origin } + } + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), 10_000) + let acquired = false + try { + await acquire(controller.signal) + acquired = true + const { stdout } = await ghExecFileAsync( + ['repo', 'view', githubRepositorySlugArg(origin), '--json', 'isFork,parent'], + { ...execution.ghOptions, timeout: 10_000, signal: controller.signal } + ) + const data = JSON.parse(stdout) as { + isFork?: boolean + parent?: { name?: string; owner?: { login?: string } } | null + } + if (data.isFork === false) { + return { upstream: null, origin } + } + const owner = data.parent?.owner?.login + const repo = data.parent?.name + return { + upstream: + data.isFork === true && + typeof owner === 'string' && + owner.trim() && + typeof repo === 'string' && + repo.trim() + ? { owner, repo, ...(origin.host ? { host: origin.host } : {}) } + : undefined, + origin + } + } finally { + clearTimeout(timer) + if (acquired) { + release() + } + } + } catch { + return { upstream: undefined, origin } + } + }) +} + +/** Compatibility callers receive null when optional metadata is unavailable. */ export async function getRepoUpstream( repoPath: string, connectionId?: string | null, options: HostedReviewExecutionOptions = {} ): Promise { - const localGitArgs = hostedReviewLocalGitOptionArgs(options) - const localGitOptions = localGitArgs[0] ?? {} - const { ownerRepo: origin, ghOptions } = await resolveGitHubRepoExecution( - repoPath, - undefined, - connectionId, - localGitOptions - ) - if (!origin) { - return null - } - const upstreamRemote = await getGitHubApiRepositoryForRemote( - repoPath, - 'upstream', - connectionId, - localGitOptions - ) - if (upstreamRemote && !sameOwnerRepo(upstreamRemote, origin)) { - return upstreamRemote - } - await acquire() - try { - // Positional slugs bypass --repo qualification, so include the Enterprise host directly. - const { stdout } = await ghExecFileAsync( - ['repo', 'view', githubRepositorySlugArg(origin), '--json', 'isFork,parent'], - // Do not let optional metadata stall repository creation. - { - ...ghOptions, - timeout: 10_000 - } - ) - const data = JSON.parse(stdout) as { - isFork?: boolean - parent?: { name?: string; owner?: { login?: string } } | null - } - const owner = data.parent?.owner?.login - const repo = data.parent?.name - return data.isFork && owner && repo - ? { owner, repo, ...(origin.host ? { host: origin.host } : {}) } - : null - } catch { - return null - } finally { - release() - } + return (await probeRepoUpstream(repoPath, connectionId, options)).upstream ?? null } diff --git a/src/main/github/github-enterprise-repository.test.ts b/src/main/github/github-enterprise-repository.test.ts index 025609e3880..99885cc2254 100644 --- a/src/main/github/github-enterprise-repository.test.ts +++ b/src/main/github/github-enterprise-repository.test.ts @@ -33,6 +33,8 @@ import { isGitHubHostAuthenticated } from './github-enterprise-repository' import { _resetSshHostnameResolutionCache } from './github-ssh-host-alias-resolution' +import { getRepoUpstream, probeRepoUpstream } from './client/fetch/repo-slug-upstream' +import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' function mockOriginRemote(url: string): void { gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { @@ -65,6 +67,7 @@ describe('getEnterpriseGitHubRepoSlug', () => { resolveWithSshGMock.mockResolvedValue(null) _resetGitHubHostAuthCache() _resetSshHostnameResolutionCache() + _resetOriginGitHubApiRepositoryCache() }) it.each([ @@ -93,6 +96,29 @@ describe('getEnterpriseGitHubRepoSlug', () => { host: 'ghe.acme.com:8443' }) }) + + it.each([true, false])( + 'keeps the literal Enterprise host fallback when SSH expansion fails (authenticated=%s)', + async (authenticated) => { + mockOriginRemote('git@ghe.corp.example:org/app.git') + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => ({ + stdout: + args[0] === 'auth' + ? authenticated + ? 'ghe.corp.example\n ✓ Logged in to ghe.corp.example account kelora (keyring)' + : '' + : JSON.stringify({ isFork: true, parent: { owner: { login: 'parent' }, name: 'app' } }), + stderr: '' + })) + const expected = { owner: 'parent', repo: 'app', host: 'ghe.corp.example' } + const result = await probeRepoUpstream('/repo') + expect(result.upstream).toEqual(authenticated ? expected : undefined) + await expect(getRepoUpstream('/repo')).resolves.toEqual(authenticated ? expected : null) + expect(ghExecFileAsyncMock.mock.calls.filter(([args]) => args[0] === 'repo')).toHaveLength( + authenticated ? 2 : 0 + ) + } + ) }) describe('isGitHubHostAuthenticated', () => { diff --git a/src/main/github/github-repository-identity.fork-owner-repo.test.ts b/src/main/github/github-repository-identity.fork-owner-repo.test.ts index c697801eb0a..5e194798172 100644 --- a/src/main/github/github-repository-identity.fork-owner-repo.test.ts +++ b/src/main/github/github-repository-identity.fork-owner-repo.test.ts @@ -1,6 +1,6 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' // Fork PR reads prefer upstream while origin-only probes retain the checkout identity. @@ -29,7 +29,11 @@ vi.mock('./local-git-config-signature', () => ({ import { _resetRemoteNameListingCache } from '../git/remotes/remote-name-listing' import { getOwnerRepoForRemote, _resetOwnerRepoCache } from './github-repository-identity' import { getOwnerRepo } from './github-owner-repo-selection' -import { getRepoUpstream } from './client/fetch/repo-slug-upstream' +import { getRepoUpstream, probeRepoUpstream } from './client/fetch/repo-slug-upstream' + +import { acquire, release } from './gh-utils' + +afterEach(() => vi.useRealTimers()) const FORK_PATH = '/tmp/fork-checkout' const NON_FORK_PATH = '/tmp/plain-checkout' @@ -43,6 +47,8 @@ const REMOTE_URLS_BY_REPO: Record> = { [NON_FORK_PATH]: { origin: 'https://github.com/stablyai/orca.git' }, + '/tmp/gitlab': { origin: 'https://gitlab.com/group/widget.git' }, + '/tmp/custom': { origin: 'https://code.example.com/group/widget.git' }, [SSH_FORK_PATH]: { origin: 'git@github.com:fsdwen/orca.git', upstream: 'git@github.com:stablyai/orca.git' @@ -117,3 +123,59 @@ describe('issue #7331: fork PR owner/repo resolution', () => { expect(ghExecFileAsyncMock).not.toHaveBeenCalled() }) }) + +describe('optional parent evidence', () => { + it.each([ + ['{"isFork":false}', null], + [ + '{"isFork":true,"parent":{"owner":{"login":"acme"},"name":"widget"}}', + { owner: 'acme', repo: 'widget', host: 'github.com' } + ], + ['{"isFork":true,"parent":null}', undefined], + ['{}', undefined], + ['invalid', undefined] + ])('persists only successful fork evidence from %s', async (stdout, expected) => { + ghExecFileAsyncMock.mockResolvedValue({ stdout }) + expect((await probeRepoUpstream(NON_FORK_PATH)).upstream).toEqual(expected) + }) + + it('bounds global admission and leaves origin avatar evidence usable on failure', async () => { + vi.useFakeTimers() + for (let slot = 0; slot < 4; slot++) { + await acquire() + } + try { + const pending = probeRepoUpstream(NON_FORK_PATH) + await vi.advanceTimersByTimeAsync(10_000) + expect(await pending).toEqual({ + upstream: undefined, + origin: { owner: 'stablyai', repo: 'orca', host: 'github.com' } + }) + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + let nextStarted = false + const next = acquire().then(() => { + nextStarted = true + release() + }) + await Promise.resolve() + expect(nextStarted).toBe(false) + release() + await next + for (let slot = 0; slot < 3; slot++) { + release() + } + } catch (error) { + for (let slot = 0; slot < 4; slot++) { + release() + } + throw error + } + }) +}) + +it('settles proven missing/other-forge origins but leaves unclassified custom hosts unknown', async () => { + expect(await probeRepoUpstream('/tmp/no-origin')).toEqual({ upstream: null, origin: null }) + expect(await probeRepoUpstream('/tmp/gitlab')).toEqual({ upstream: null, origin: null }) + ghExecFileAsyncMock.mockRejectedValue(new Error('auth unavailable')) + expect(await probeRepoUpstream('/tmp/custom')).toEqual({ upstream: undefined, origin: null }) +}) diff --git a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts index e6f533b851a..cd40d4ad535 100644 --- a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts +++ b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts @@ -5,7 +5,9 @@ import { DESKTOP_BROWSER_BRIDGE_CANCEL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY, - isDesktopBrowserBridgeMethod + DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY, + isDesktopBrowserBridgeMethod, + isHostReachableDocument } from '../../../shared/desktop-browser-bridge-protocol' import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' import '../../../shared/remote-runtime/requests/remote-runtime-request-socket' @@ -22,10 +24,7 @@ import { DesktopBrowserBridgeManager, type DesktopBrowserBridgeCandidate } from '../../browser/desktop-browser-bridge/desktop-browser-bridge-manager' -import { - executeDesktopBrowserBridgeRequest, - isHostReachableDocument -} from '../../browser/desktop-browser-bridge/desktop-browser-bridge-executor' +import { executeDesktopBrowserBridgeRequest } from '../../browser/desktop-browser-bridge/desktop-browser-bridge-executor' import { rendererResolveRemoteCliWorkspace } from '../../browser/desktop-browser-bridge/desktop-browser-bridge-renderer-scope' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { RpcDispatcher } from '../../runtime/rpc/dispatcher' @@ -153,7 +152,8 @@ export function installDesktopBrowserBridge(options: { ...ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY, DESKTOP_BROWSER_BRIDGE_CANCEL_CAPABILITY, - DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY + DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY, + DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY ] } ) diff --git a/src/main/ipc/repos-nested-import.test.ts b/src/main/ipc/repos-nested-import.test.ts index f70d1a9bae3..a3cfc198564 100644 --- a/src/main/ipc/repos-nested-import.test.ts +++ b/src/main/ipc/repos-nested-import.test.ts @@ -70,7 +70,17 @@ describe('projectGroups IPC validation', () => { mockWindow.webContents.send.mockReset() resetProjectGroupMocks(reposMocks, { isGitRepo, getGitRepoRoot }) - registerRepoHandlers(mockWindow as never, mockStore as never, {} as never) + registerRepoHandlers( + mockWindow as never, + mockStore as never, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These IPC cases use only the metadata owner's enqueue method; other runtime handlers are not invoked. + { + repositoryForkBackfill: { + enqueue: vi.fn().mockResolvedValue(undefined), + resolve: vi.fn().mockResolvedValue(true) + } + } as never + ) }) const group = { diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 68ae1b3aed9..24448a20635 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -66,14 +66,22 @@ export function registerRepoHandlers( ipcMain.removeHandler('sparsePresets:remove') registerRepoCatalogHandlers(mainWindow, store, runtime) - registerProjectHostSetupHandlers(mainWindow, store) - registerRepoCreationHandlers(mainWindow, store) + const metadata = { + enqueueRepositoryMetadata: ( + repos: Parameters[0] + ) => void runtime.repositoryForkBackfill.enqueue(repos), + resolveRepositoryMetadata: ( + repo: Parameters[0] + ) => runtime.repositoryForkBackfill.resolve(repo) + } + registerProjectHostSetupHandlers(mainWindow, store, metadata) + registerRepoCreationHandlers(mainWindow, store, metadata.enqueueRepositoryMetadata) registerProjectGroupHandlers(mainWindow, store) registerFolderWorkspaceHandlers(mainWindow, store, runtime) - registerNestedRepoImportHandler(mainWindow, store) + registerNestedRepoImportHandler(mainWindow, store, metadata.enqueueRepositoryMetadata) registerRepoUpdateHandler(mainWindow, store) registerSparsePresetHandlers(mainWindow, store) registerRepoFolderPickerHandlers(mainWindow) - registerRepoCloneHandlers(mainWindow, store) + registerRepoCloneHandlers(mainWindow, store, metadata.enqueueRepositoryMetadata) registerBaseRefQueryHandlers(store) } diff --git a/src/main/ipc/repos/local-repo-registration.test.ts b/src/main/ipc/repos/local-repo-registration.test.ts index 8cae231ea9d..53b854a0ab4 100644 --- a/src/main/ipc/repos/local-repo-registration.test.ts +++ b/src/main/ipc/repos/local-repo-registration.test.ts @@ -7,7 +7,7 @@ import type { Store } from '../../persistence/loading-store/store' import { addLocalRepoFromPath } from './local-repo-registration' vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) + detectRepoLocalMetadata: vi.fn().mockResolvedValue({}) })) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) diff --git a/src/main/ipc/repos/local-repo-registration.ts b/src/main/ipc/repos/local-repo-registration.ts index 5f447575fd1..53f4c136704 100644 --- a/src/main/ipc/repos/local-repo-registration.ts +++ b/src/main/ipc/repos/local-repo-registration.ts @@ -10,7 +10,7 @@ import { } from '../../git/repo' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { findProjectAtSameRealPath } from '../../workspaces/catalog/project-realpath-identity' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { describeWslUncAccessDenied } from '../../wsl/filesystem/wsl-unc-access-denied' import { createLocalProjectRecord } from '../../workspaces/catalog/local-project-record' @@ -86,7 +86,7 @@ export async function addLocalRepoFromPath( } } - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath: resolvedPath, kind: repoKind, executionHostId: LOCAL_EXECUTION_HOST_ID diff --git a/src/main/ipc/repos/nested-repo-import-handler.ts b/src/main/ipc/repos/nested-repo-import-handler.ts index 84dc522b3c2..bc4768f64c0 100644 --- a/src/main/ipc/repos/nested-repo-import-handler.ts +++ b/src/main/ipc/repos/nested-repo-import-handler.ts @@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto' import { realpath } from 'node:fs/promises' import type { Store } from '../../persistence/loading-store/store' import type { Repo } from '../../../shared/repo-types' +import type { RepositoryMetadataOwner } from '../../workspaces/catalog/imported-folder-project-link' import type { ProjectGroupImportResult } from '../../../shared/project-group-types' import { DEFAULT_REPO_BADGE_COLOR } from '../../../shared/constants' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' @@ -15,7 +16,7 @@ import { } from '../../project-groups/nested-repo-import' import { createNestedRepoImportTargetResolver } from '../../project-groups/nested-repo-import-target' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered-worktree-roots-cache' import { emitRepoAdded } from './repo-added-telemetry' @@ -28,7 +29,11 @@ function sanitizeNestedRepoImportError(context: string, error: unknown): string return 'Repository could not be imported' } -export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store: Store): void { +export function registerNestedRepoImportHandler( + mainWindow: BrowserWindow, + store: Store, + enqueueMetadata: RepositoryMetadataOwner['enqueueRepositoryMetadata'] +): void { ipcMain.handle( 'projectGroups:importNested', async (_event, rawArgs: unknown): Promise => { @@ -65,6 +70,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store const importedProjectIdsByRepoPath = new Map() const importTargetResolver = createNestedRepoImportTargetResolver() + const acceptedRepos: Repo[] = [] for (const [projectGroupOrder, repoPath] of selection.selectedPaths.entries()) { try { // This process cannot validate SSH paths with local Git. @@ -117,7 +123,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store results.push({ path: repoPath, projectId: existing.id, status: 'already-known' }) continue } - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath: importRepoPath, kind: 'git', executionHostId: LOCAL_EXECUTION_HOST_ID @@ -140,6 +146,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store : {}) } store.addRepo(repo) + acceptedRepos.push(repo) await prepareLocalWorktreeRootForRepo(store, repo) importedProjectIdsByRepoPath.set(normalizedImportRepoPath, repo.id) results.push({ path: repoPath, projectId: repo.id, status: 'imported' }) @@ -153,6 +160,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store } } + enqueueMetadata(acceptedRepos) const importedCount = results.filter((entry) => entry.status === 'imported').length const alreadyKnownCount = results.filter((entry) => entry.status === 'already-known').length const failedCount = results.filter((entry) => entry.status === 'failed').length diff --git a/src/main/ipc/repos/project-host-setup-handlers.ts b/src/main/ipc/repos/project-host-setup-handlers.ts index 61f412d26cc..7326003eb2e 100644 --- a/src/main/ipc/repos/project-host-setup-handlers.ts +++ b/src/main/ipc/repos/project-host-setup-handlers.ts @@ -13,7 +13,10 @@ import type { ProjectHostSetupUpdateResult } from '../../../shared/project-types' import { getProjectHostSetupForRepo } from '../../../shared/project-host-setup-lookup' -import { resolveImportedFolderProjectLink } from '../../../shared/imported-folder-project-identity' +import { + linkImportedFolderToProject, + type RepositoryMetadataOwner +} from '../../workspaces/catalog/imported-folder-project-link' import { readCurrentGitRemoteIdentity } from '../../workspaces/catalog/repo-git-remote-identity' import { getRepoExecutionHostId, parseExecutionHostId } from '../../../shared/execution-host' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' @@ -45,48 +48,11 @@ function buildProjectHostSetupResult(store: Store, repo: Repo): ProjectHostSetup return { project, setup, repo } } -function alignRepoWithRequestedProject( +export function registerProjectHostSetupHandlers( + mainWindow: BrowserWindow, store: Store, - repo: Repo, - folderRemote: Pick, - projectId: string, - setupMethod: ProjectHostSetupExistingFolderArgs['setupMethod'] = 'imported-existing-folder', - requestedProviderIdentity?: ProjectHostSetupExistingFolderArgs['projectProviderIdentity'] -): ProjectHostSetupResult { - assertWslMoveHostSetupWritable(store, { - projectId, - hostId: getRepoExecutionHostId(repo), - repoId: repo.id - }) - let setup = getProjectHostSetupForRepo(store.getProjectHostSetups(), repo) - if (setup.projectId !== projectId) { - const project = store.getProjects().find((entry) => entry.id === projectId) - // Project identity must travel with the request when it exists only on the source host. - const updated = store.updateRepo( - repo, - resolveImportedFolderProjectLink( - { ...repo, ...folderRemote }, - projectId, - project?.providerIdentity ?? requestedProviderIdentity - ) - ) - if (!updated) { - throw new Error(`Project setup repo disappeared before it could be linked: ${repo.id}`) - } - repo = updated - setup = getProjectHostSetupForRepo(store.getProjectHostSetups(), repo) - } - const updated = store.updateRepo(repo, { projectHostSetupMethod: setupMethod }) - if (!updated) { - throw new Error( - `Project setup repo disappeared before setup metadata could be linked: ${repo.id}` - ) - } - repo = updated - return buildProjectHostSetupResult(store, repo) -} - -export function registerProjectHostSetupHandlers(mainWindow: BrowserWindow, store: Store): void { + metadata: RepositoryMetadataOwner +): void { ipcMain.handle( 'projectHostSetups:create', (_event, rawArgs: ProjectHostSetupCreateArgs): ProjectHostSetupCreateResult => { @@ -191,20 +157,21 @@ export function registerProjectHostSetupHandlers(mainWindow: BrowserWindow, stor : result.repo let aligned: ProjectHostSetupResult try { - aligned = alignRepoWithRequestedProject( - store, + const repo = await linkImportedFolderToProject( + () => store, result.repo, folderRemote, - args.projectId, - args.setupMethod, - args.projectProviderIdentity + { ...args, hostId: getRepoExecutionHostId(result.repo) }, + metadata ) + aligned = buildProjectHostSetupResult(store, repo) } catch (err) { // Failed linking must not leave a newly registered repo or authorization root. if (!result.alreadyExisted) { store.removeProjectForHost(result.repo) invalidateAuthorizedRootsCache() } + notifyReposChanged(mainWindow) throw err } invalidateAuthorizedRootsCache() diff --git a/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts b/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts index a450dcab9d3..98cdb340348 100644 --- a/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts +++ b/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts @@ -83,7 +83,10 @@ describe('project host setups under a WSL move', () => { store.addRepo(repo('repo-1')) store.addRepo(repo('repo-2')) seedWslMoveCutover(testState.dir, cutover('move-1', 'source-fenced')) - registerProjectHostSetupHandlers(new BrowserWindow(), store) + registerProjectHostSetupHandlers(new BrowserWindow(), store, { + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true) + }) const moving = setupFor('repo-1') await expect( @@ -107,7 +110,10 @@ describe('project host setups under a WSL move', () => { it("keeps a setup's own repo frozen once the WSL host owns it", async () => { store.addRepo(repo('repo-1')) seedWslMoveCutover(testState.dir, cutover('move-1', 'destination-committed')) - registerProjectHostSetupHandlers(new BrowserWindow(), store) + registerProjectHostSetupHandlers(new BrowserWindow(), store, { + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true) + }) const owned = setupFor('repo-1') await expect( @@ -129,6 +135,8 @@ describe('project host setups under a WSL move', () => { invalidateResolvedWorktrees: vi.fn(), invalidateWorktreeScan: vi.fn(), notifyReposChanged: vi.fn(), + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true), countLiveTerminalsForRepo: () => 0 }) const setupId = setupFor('repo-1').id diff --git a/src/main/ipc/repos/repo-clone-lifecycle.ts b/src/main/ipc/repos/repo-clone-lifecycle.ts index bd68750b60e..422d3833f68 100644 --- a/src/main/ipc/repos/repo-clone-lifecycle.ts +++ b/src/main/ipc/repos/repo-clone-lifecycle.ts @@ -22,14 +22,16 @@ import { getSavedProjectPathKeys } from '../../git/repo-clone-path' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered-worktree-roots-cache' import { emitRepoAdded } from './repo-added-telemetry' import { notifyReposChanged } from './repos-changed-notification' import { runWithClonePathLock } from './clone-path-lock' +import { emitCloneProgressFromText } from './repo-clone-progress' import { resolveClonedFolderConversion } from '../../workspaces/catalog/folder-repo-git-conversion' import { findExtraFolderWorkspaceIds } from '../../workspaces/catalog/folder-workspace-meta-presence' +import type { RepositoryMetadataOwner } from '../../workspaces/catalog/imported-folder-project-link' type ActiveCloneMetadata = { path: string @@ -49,18 +51,6 @@ let nextCloneGeneration = 1 const latestCloneGenerationByPath = new Map() const pendingAbortCleanupByPath = new Map>() -function emitCloneProgressFromText(mainWindow: BrowserWindow, text: string): void { - for (const line of text.split(/[\r\n]+/)) { - const match = line.match(/^([\w\s]+):\s+(\d+)%/) - if (match && !mainWindow.isDestroyed()) { - mainWindow.webContents.send('repos:clone-progress', { - phase: match[1].trim(), - percent: Number.parseInt(match[2], 10) - }) - } - } -} - async function cleanupOwnedCloneTarget(metadata: ActiveCloneMetadata): Promise { if (!metadata.claimedTarget.canCleanup || !metadata.claimedTarget.ownedDirectoryIdentity) { return @@ -102,7 +92,11 @@ function settleCloneAbortCleanup(metadata: ActiveCloneMetadata): void { metadata.resolvePendingAbortCleanup = null } -export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Store): void { +export function registerRepoCloneHandlers( + mainWindow: BrowserWindow, + store: Store, + enqueueMetadata: RepositoryMetadataOwner['enqueueRepositoryMetadata'] +): void { ipcMain.handle('repos:cloneAbort', async () => { for (const controller of pendingLocalCloneControllers) { controller.abort() @@ -136,7 +130,7 @@ export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Stor const clonePathKey = getClonePathComparisonKey(clonePath) let savedPathKeys: string[] = [] const findSaved = (): Repo | undefined => findLocalSaved(savedPathKeys) - return runWithClonePathLock(clonePathKey, async () => { + const repo = await runWithClonePathLock(clonePathKey, async () => { await pendingAbortCleanupByPath.get(clonePathKey) // Read after the lock so lookup sees what a queued clone of this path registered. savedPathKeys = await getSavedProjectPathKeys(clonePath) @@ -299,7 +293,7 @@ export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Stor // Register Git's checkout path so the clone stays its own selected checkout. const repoPath = (await inspectGitRepoForRegistrationAsync(clonePath)).rootPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: 'git', executionHostId: LOCAL_EXECUTION_HOST_ID @@ -329,5 +323,7 @@ export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Stor } } }) + enqueueMetadata([repo]) + return repo }) } diff --git a/src/main/ipc/repos/repo-clone-progress.ts b/src/main/ipc/repos/repo-clone-progress.ts new file mode 100644 index 00000000000..cce16fbcd9c --- /dev/null +++ b/src/main/ipc/repos/repo-clone-progress.ts @@ -0,0 +1,13 @@ +import type { BrowserWindow } from 'electron' + +export function emitCloneProgressFromText(mainWindow: BrowserWindow, text: string): void { + for (const line of text.split(/[\r\n]+/)) { + const match = line.match(/^([\w\s]+):\s+(\d+)%/) + if (match && !mainWindow.isDestroyed()) { + mainWindow.webContents.send('repos:clone-progress', { + phase: match[1].trim(), + percent: Number.parseInt(match[2], 10) + }) + } + } +} diff --git a/src/main/ipc/repos/repo-creation-handlers.ts b/src/main/ipc/repos/repo-creation-handlers.ts index 25aed3525a0..d17a56ee3ba 100644 --- a/src/main/ipc/repos/repo-creation-handlers.ts +++ b/src/main/ipc/repos/repo-creation-handlers.ts @@ -6,6 +6,7 @@ import { homedir } from 'node:os' import { isAbsolute, join } from 'node:path' import type { Store } from '../../persistence/loading-store/store' import type { Repo } from '../../../shared/repo-types' +import type { RepositoryMetadataOwner } from '../../workspaces/catalog/imported-folder-project-link' import { DEFAULT_REPO_BADGE_COLOR, getDefaultWorkspaceDir } from '../../../shared/constants' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' @@ -14,7 +15,7 @@ import { probeGitAvailability } from '../../git/git-availability' import { gitExecFileAsync } from '../../git/runner' import { inspectGitRepoForRegistrationAsync } from '../../git/repo' import { getClonePathComparisonKey, getSavedProjectPathKeys } from '../../git/repo-clone-path' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered-worktree-roots-cache' import { repoCreateFailure, type RepoCreateFailure } from '../../../shared/repo-create-failure-copy' @@ -51,7 +52,11 @@ function getDefaultCreateProjectParent(store: Store): string { return join(home, 'orca', 'projects') } -export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: Store): void { +export function registerRepoCreationHandlers( + mainWindow: BrowserWindow, + store: Store, + enqueueMetadata: RepositoryMetadataOwner['enqueueRepositoryMetadata'] +): void { ipcMain.handle('repos:isGitAvailable', () => probeLocalGitAvailability()) ipcMain.handle('repos:getDefaultCreateProjectParent', () => getDefaultCreateProjectParent(store)) @@ -70,6 +75,7 @@ export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: S } invalidateAuthorizedRootsCache() notifyReposChanged(mainWindow) + enqueueMetadata([result.repo]) emitRepoAdded('folder_picker', result.alreadyExisted, result.repo.kind === 'git') return { repo: result.repo } } @@ -222,7 +228,7 @@ export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: S repoKind === 'git' ? (await inspectGitRepoForRegistrationAsync(targetPath)).rootPath : targetPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: repoKind, executionHostId: LOCAL_EXECUTION_HOST_ID @@ -244,6 +250,7 @@ export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: S } store.addRepo(repo) + enqueueMetadata([repo]) await prepareLocalWorktreeRootForRepo(store, repo) invalidateAuthorizedRootsCache() notifyReposChanged(mainWindow) diff --git a/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts b/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts index 87ba94bcabf..e3964f7f6ef 100644 --- a/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts +++ b/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts @@ -265,6 +265,10 @@ export function journalInputPresentationMember( state: JournalReducerState, itemId: string ): boolean { + // Renders ask this of every row on each commit; parsing each key froze main in big chats (#40682). + if (state.inputs.rejections.size === 0) { + return true + } const identity = parseAgentJournalItemKey(itemId) return ( identity?.provider !== 'orca' || diff --git a/src/main/orcad/orcad-client-page-commands.ts b/src/main/orcad/orcad-client-page-commands.ts index 9afc3d95ab7..11e8e8e4a1e 100644 --- a/src/main/orcad/orcad-client-page-commands.ts +++ b/src/main/orcad/orcad-client-page-commands.ts @@ -28,6 +28,11 @@ import { type BrowserEngineTabs } from '../runtime/browser/client-pages/browser-client-page-queries' +import { + findListedBrowserTab, + readBrowserTabAnnotations +} from '../runtime/browser/tabs/browser-tab-annotations' + type Forward = (args: unknown[], name?: string) => unknown const LOGICAL_TAB_QUERIES = [ @@ -70,6 +75,16 @@ export function orcadClientPageCommand( : closeBrowserPageWithoutEngine(host, params, browserUnavailableError) } } + if (name === 'browserTabAnnotations') { + return async (...args: Parameters) => { + const { page, worktree } = args[0] ?? {} + // The engine's active flags are global, so a worktree's current tab needs its own query. + const tab = page + ? findListedBrowserTab((await logicalTabs().browserTabList({ worktree })).tabs, page) + : (await logicalTabs().browserTabCurrent({ worktree })).tab + return readBrowserTabAnnotations(host, tab) + } + } const query = LOGICAL_TAB_QUERIES.find((candidate) => candidate === name) if (query) { return (...args: unknown[]) => { diff --git a/src/main/repository-icons/repo-icon-autodetect.ts b/src/main/repository-icons/repo-icon-autodetect.ts index 64dce61e202..393672a9ef9 100644 --- a/src/main/repository-icons/repo-icon-autodetect.ts +++ b/src/main/repository-icons/repo-icon-autodetect.ts @@ -8,7 +8,7 @@ import { githubAvatarSlug, type RepoIcon } from '../../shared/repo-icon' -import { getRepoSlug, getRepoUpstream } from '../github/client/fetch/repo-slug-upstream' +import { getRepoSlug } from '../github/client/fetch/repo-slug-upstream' import { resolveFilesystemRouteForHost, resolveGitRouteForHost @@ -92,6 +92,24 @@ export async function detectGitHubAvatarIcon( } } +async function detectRepoLocalIcon( + repoPath: string, + executionHostId: ExecutionHostId +): Promise { + try { + const route = resolveFilesystemRouteForHost(executionHostId) + const fileIcon = await detectRepoFileIcon(repoPath, route) + if (fileIcon) { + return fileIcon + } + return ( + (route.kind === 'local' ? await detectLocalPackageHomepageIcon(repoPath) : null) ?? undefined + ) + } catch { + return undefined + } +} + export async function detectRepoIcon({ repoPath, kind, @@ -103,30 +121,15 @@ export async function detectRepoIcon({ executionHostId: ExecutionHostId upstream?: GitHubRepositoryIdentity | null }): Promise { - try { - const route = resolveFilesystemRouteForHost(executionHostId) - const fileIcon = await detectRepoFileIcon(repoPath, route) - if (fileIcon) { - return fileIcon - } - - const homepageIcon = - route.kind === 'local' ? await detectLocalPackageHomepageIcon(repoPath) : null - if (homepageIcon) { - return homepageIcon - } - - if (kind === 'git') { - return (await detectGitHubAvatarIcon(repoPath, executionHostId, upstream)) ?? undefined - } - } catch { - // Icon failures must not prevent repo creation. - } - return undefined + return ( + (await detectRepoLocalIcon(repoPath, executionHostId)) ?? + (kind === 'git' + ? ((await detectGitHubAvatarIcon(repoPath, executionHostId, upstream)) ?? undefined) + : undefined) + ) } -// A null upstream marks a resolved non-fork and prevents repeated probes. -export async function detectRepoIconAndUpstream({ +export async function detectRepoLocalMetadata({ repoPath, kind, executionHostId @@ -135,22 +138,13 @@ export async function detectRepoIconAndUpstream({ kind: RepoKind executionHostId: ExecutionHostId }) { - const remoteRead = repoRemoteReadConnection(executionHostId) - const upstream = - kind === 'git' && remoteRead.kind === 'dial' - ? await getRepoUpstream(repoPath, remoteRead.connectionId) - : null const gitRemoteIdentity = kind === 'git' - ? await detectGitRemoteIdentity(repoPath, executionHostId, { - // Host Git on purpose: this runs while the project is being added, before it exists. - hostGit: true - }) + ? await detectGitRemoteIdentity(repoPath, executionHostId, { hostGit: true }) : null - const repoIcon = await detectRepoIcon({ repoPath, kind, executionHostId, upstream }) + const repoIcon = await detectRepoLocalIcon(repoPath, executionHostId) return { ...(repoIcon ? { repoIcon } : {}), - ...(gitRemoteIdentity ? { gitRemoteIdentity } : {}), - ...(kind === 'git' ? { upstream: upstream ?? null } : {}) + ...(gitRemoteIdentity ? { gitRemoteIdentity } : {}) } } diff --git a/src/main/runtime/browser/commands/browser-command-contracts.ts b/src/main/runtime/browser/commands/browser-command-contracts.ts index 9d5367bf3b9..09d04d459ce 100644 --- a/src/main/runtime/browser/commands/browser-command-contracts.ts +++ b/src/main/runtime/browser/commands/browser-command-contracts.ts @@ -9,6 +9,7 @@ import type { BrowserBackend } from '../../../browser/browser-backend' import type { BrowserSessionTabSelectionOptions } from '../tabs/browser-tab-create-publication' import type { ServeBrowserTabs } from '../headless/serve-browser-tabs' import type { BrowserTabBarEntry } from '../tabs/browser-tab-listing' +import type { BrowserPageAnnotation } from '../../../../shared/browser/element-grab/browser-grab-types' export type BrowserCommandTargetParams = { worktree?: string @@ -60,6 +61,8 @@ export type RuntimeBrowserCommandHost = { options?: BrowserSessionTabSelectionOptions ): void notifyHeadlessBrowserSessionTabsChanged?(worktreeId: string): void + /** A page's unsent notes; see readSavedBrowserPageAnnotations. */ + readBrowserPageAnnotations?(browserPageId: string): BrowserPageAnnotation[] /** The tab bar's browser tabs, loaded or not, from the published session snapshot. */ readBrowserTabBar?(worktreeId: string | undefined): BrowserTabBarEntry[] retireRuntimeOwnedBrowserSessionTab?(worktreeId: string, browserPageId: string): boolean | void diff --git a/src/main/runtime/browser/commands/browser-commands.ts b/src/main/runtime/browser/commands/browser-commands.ts index acdda731ff6..4f8e0cb11a8 100644 --- a/src/main/runtime/browser/commands/browser-commands.ts +++ b/src/main/runtime/browser/commands/browser-commands.ts @@ -81,6 +81,7 @@ export class RuntimeBrowserCommands { readonly browserProceedCertificate: RuntimeBrowserTabQueries['browserProceedCertificate'] readonly browserTabShow: RuntimeBrowserTabQueries['browserTabShow'] readonly browserTabCurrent: RuntimeBrowserTabQueries['browserTabCurrent'] + readonly browserTabAnnotations: RuntimeBrowserTabQueries['browserTabAnnotations'] readonly browserTabSwitch: RuntimeBrowserTabQueries['browserTabSwitch'] readonly browserTabCreate: RuntimeBrowserTabCreation['browserTabCreate'] readonly browserOpenUrlOnClient: RuntimeBrowserTabCreation['browserOpenUrlOnClient'] @@ -187,6 +188,7 @@ export class RuntimeBrowserCommands { this.browserProceedCertificate = queries.browserProceedCertificate.bind(queries) this.browserTabShow = queries.browserTabShow.bind(queries) this.browserTabCurrent = queries.browserTabCurrent.bind(queries) + this.browserTabAnnotations = queries.browserTabAnnotations.bind(queries) this.browserTabSwitch = queries.browserTabSwitch.bind(queries) this.browserTabCreate = creation.browserTabCreate.bind(creation) this.browserOpenUrlOnClient = creation.browserOpenUrlOnClient.bind(creation) diff --git a/src/main/runtime/browser/tabs/browser-tab-annotations.ts b/src/main/runtime/browser/tabs/browser-tab-annotations.ts new file mode 100644 index 00000000000..c58ceffb5ab --- /dev/null +++ b/src/main/runtime/browser/tabs/browser-tab-annotations.ts @@ -0,0 +1,67 @@ +import type { BrowserPageAnnotation } from '../../../../shared/browser/element-grab/browser-grab-types' +import type { + BrowserTabAnnotationsResult, + BrowserTabInfo +} from '../../../../shared/browser/runtime/runtime-browser-contracts' +import { isHostReachableDocument } from '../../../../shared/desktop-browser-bridge-protocol' +import { BrowserError } from '../../../browser/browser-error' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import type { RuntimeBrowserCommandHost } from '../commands/browser-command-contracts' +import { remoteCliBrowserScopeWorkspaceId } from '../../desktop-browser-bridge/remote-cli-browser-scope' + +/** A page's unsent notes from the saved session, which the window keeps current. */ +export function readSavedBrowserPageAnnotations( + store: + | Pick + | null + | undefined, + browserPageId: string +): BrowserPageAnnotation[] { + // Page ids are unique across hosts, and a bridged SSH page has no worktree row here. + for (const hostId of store?.getWorkspaceSessionHostIds?.() ?? []) { + const pages = store?.getWorkspaceSession?.(hostId)?.browserPagesByWorkspace ?? {} + for (const workspacePages of Object.values(pages)) { + const page = workspacePages.find((candidate) => candidate.id === browserPageId) + if (page) { + return page.annotations ?? [] + } + } + } + return [] +} + +export function findListedBrowserTab( + tabs: readonly BrowserTabInfo[], + page: string +): BrowserTabInfo { + const tab = tabs.find((candidate) => candidate.browserPageId === page) + if (!tab) { + throw new BrowserError('browser_tab_not_found', `Browser page ${page} was not found`) + } + return tab +} + +export function readBrowserTabAnnotations( + host: Pick< + RuntimeBrowserCommandHost, + 'getRuntimeBrowserPageRegistry' | 'readBrowserPageAnnotations' + >, + tab: BrowserTabInfo +): BrowserTabAnnotationsResult { + // A paired desktop draws this page and keeps its notes; this host would wrongly report none. + if (host.getRuntimeBrowserPageRegistry().getPage(tab.browserPageId)) { + throw new BrowserError( + 'browser_annotations_unavailable', + `Tab ${tab.browserPageId} is drawn by a paired desktop, which keeps its unsent notes. Ask the user to send them from that tab.` + ) + } + const annotations = host.readBrowserPageAnnotations?.(tab.browserPageId) ?? [] + return { + tab, + // An SSH host may not read what a note captured from a desktop-local document. + annotations: + remoteCliBrowserScopeWorkspaceId() === undefined + ? annotations + : annotations.filter((note) => isHostReachableDocument(note.payload.page.sanitizedUrl)) + } +} diff --git a/src/main/runtime/browser/tabs/browser-tab-queries.ts b/src/main/runtime/browser/tabs/browser-tab-queries.ts index 5aaab4a5a66..51f31bdbe76 100644 --- a/src/main/runtime/browser/tabs/browser-tab-queries.ts +++ b/src/main/runtime/browser/tabs/browser-tab-queries.ts @@ -1,4 +1,5 @@ import type { + BrowserTabAnnotationsResult, BrowserTabCurrentResult, BrowserTabListResult, BrowserTabShowResult, @@ -17,6 +18,7 @@ import type { } from '../commands/browser-command-contracts' import type { RuntimeBrowserCommandTargets } from '../commands/browser-command-targets' import type { RuntimeBrowserTabCatalog } from './browser-tab-catalog' +import { findListedBrowserTab, readBrowserTabAnnotations } from './browser-tab-annotations' export class RuntimeBrowserTabQueries { constructor( @@ -27,6 +29,7 @@ export class RuntimeBrowserTabQueries { | 'getRuntimeBrowserPageRegistry' | 'markHeadlessBrowserSessionTabActive' | 'notifyHeadlessBrowserSessionTabsChanged' + | 'readBrowserPageAnnotations' >, private readonly targets: Pick< RuntimeBrowserCommandTargets, @@ -89,6 +92,22 @@ export class RuntimeBrowserTabQueries { return { tab: this.catalog.describeBrowserTab(params.page, target.worktreeId) } } + async browserTabAnnotations(params: { + page?: string + worktree?: string + }): Promise { + if (!params.page) { + return readBrowserTabAnnotations(this.host, (await this.browserTabCurrent(params)).tab) + } + // A named page's notes are saved state: list the tab bar as saved rather than waking a browser. + const workspaceId = params.worktree + ? (await this.host.resolveBrowserWorkspace(params.worktree)).id + : undefined + const clientPages = this.host.getRuntimeBrowserPageRegistry().listPages(workspaceId) + const tabs = this.catalog.listLogicalBrowserTabs(workspaceId, clientPages) + return readBrowserTabAnnotations(this.host, findListedBrowserTab(tabs, params.page)) + } + async browserTabCurrent(params: { worktree?: string }): Promise { const tab = (await this.browserTabList(params)).tabs.find((candidate) => candidate.active) if (!tab) { diff --git a/src/main/runtime/construction/runtime-edge-command-controller.ts b/src/main/runtime/construction/runtime-edge-command-controller.ts index 933c812272c..6d6b7fac4ec 100644 --- a/src/main/runtime/construction/runtime-edge-command-controller.ts +++ b/src/main/runtime/construction/runtime-edge-command-controller.ts @@ -47,6 +47,7 @@ const BROWSER_COMMAND_NAMES = [ 'browserProceedCertificate', 'browserTabShow', 'browserTabCurrent', + 'browserTabAnnotations', 'browserTabSwitch', 'browserHover', 'browserDrag', diff --git a/src/main/runtime/construction/runtime-host-services.ts b/src/main/runtime/construction/runtime-host-services.ts index b1515e72345..38403c91120 100644 --- a/src/main/runtime/construction/runtime-host-services.ts +++ b/src/main/runtime/construction/runtime-host-services.ts @@ -1,8 +1,6 @@ import type * as Calls from './runtime-host-service-calls' import type { RuntimeConstructionBindings as HostBindings } from './runtime-construction-dependencies' -import type { RuntimeRepositoryCommandSurface } from '../repositories/runtime-repository-command-surface' - import type { LegacyWorkerRecoveryCandidate } from '../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' import type { LegacyWorkerTerminalRecoveryPlan } from '../orchestration/terminal-authority/release/orchestration-legacy-worker-terminal-recovery' @@ -46,8 +44,6 @@ import { teardownFolderWorkspacePtys } from '../workspaces/removal/folder-worksp import { countRepoTerminalsNotKnownExited } from '../workspaces/removal/project-removal-impact' export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeWithTerminalDrivers { - declare addRepo: RuntimeRepositoryCommandSurface['addRepo'] - declare cloneRepo: RuntimeRepositoryCommandSurface['cloneRepo'] declare acquireFileWatcherRemoval: ConstructorParameters< typeof RuntimeProjectGroupController >[0]['acquireFileWatcherRemoval'] @@ -279,8 +275,11 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeW protected readonly projectHostSetups = new RuntimeProjectHostSetupController({ getStore: () => this.store, listRepos: () => this.listRepos(), - addRepo: (path, kind, hostId) => this.addRepo(path, kind, hostId), - cloneRepo: (args) => this.cloneRepo(args.url, args.destination, args.hostId, args.folderName), + addRepo: (path, kind, hostId) => this.repositoryRegistrations.add(path, kind, hostId), + cloneRepo: (args) => + this.repositoryClones.clone(args.url, args.destination, args.hostId, args.folderName), + resolveRepositoryMetadata: (repo) => this.repositoryForkBackfill.resolve(repo), + enqueueRepositoryMetadata: (repos) => void this.repositoryForkBackfill.enqueue(repos), invalidateResolvedWorktrees: () => this.invalidateResolvedWorktreeCache(), invalidateWorktreeScan: (repoId) => this.invalidateWorktreeScanCacheForRepo(repoId), notifyReposChanged: () => this.notifyReposChanged(), @@ -353,7 +352,7 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeW protected readonly serverEnvironment = new RuntimeServerEnvironmentCommands() - protected readonly repositoryForkBackfill = new RuntimeRepositoryForkBackfill( + readonly repositoryForkBackfill = new RuntimeRepositoryForkBackfill( () => this.store, () => this.notifyReposChanged() ) diff --git a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts index cc2170d60e7..4338bf8352b 100644 --- a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts +++ b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts @@ -6,6 +6,28 @@ import { } from './desktop-browser-bridge-registry' import { routeDesktopBrowserBridgeRpc } from './desktop-browser-bridge-route' +describe('tab annotations through the desktop bridge', () => { + it('never sends them to an older desktop, which would drop its whole bridge', async () => { + const registry = new DesktopBrowserBridgeRegistry() + const emit = vi.fn() + registry.attach({ connectionId: 'new', pairedDeviceId: 'd', readsTabAnnotations: true, emit }) + registry.attach({ connectionId: 'old', pairedDeviceId: 'd', emit }) + + await expect( + routeDesktopBrowserBridgeRpc({ + method: 'browser.tabAnnotations', + params: { page: 'page-1' }, + caller: { kind: 'local-cli' }, + hostEnabled: true, + registry, + localBrowserAvailable: false, + resolveWorkspace: async (selector) => ({ id: selector }) + }) + ).rejects.toMatchObject({ code: 'desktop_browser_bridge_not_forwarded' }) + expect(emit).not.toHaveBeenCalled() + }) +}) + describe('--expect-url through the desktop bridge', () => { const route = (registry: DesktopBrowserBridgeRegistry) => routeDesktopBrowserBridgeRpc({ diff --git a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts index b0c561e52ef..b297f8e6d2b 100644 --- a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts +++ b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts @@ -19,6 +19,7 @@ type Attachment = { pairedDeviceId: string acceptsCancel?: boolean enforcesExpectUrl?: boolean + readsTabAnnotations?: boolean emit: (event: DesktopBrowserBridgeEvent) => void } @@ -57,6 +58,10 @@ export class DesktopBrowserBridgeRegistry { return this.attachments.at(-1)?.enforcesExpectUrl === true } + newestAttachmentReadsTabAnnotations(): boolean { + return this.attachments.at(-1)?.readsTabAnnotations === true + } + forward( request: DesktopBrowserBridgeForward, options: { timeoutMs: number; signal?: AbortSignal } diff --git a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts index ae0f6a6aaa5..2f472b5f36e 100644 --- a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts +++ b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts @@ -75,6 +75,15 @@ export async function routeDesktopBrowserBridgeRpc(options: { 'The Orca desktop sharing its browser cannot check --expect-url. Update Orca on that desktop or drop the flag.' ) } + if ( + forwardedMethod === 'browser.tabAnnotations' && + !options.registry.newestAttachmentReadsTabAnnotations() + ) { + throw new BrowserError( + DESKTOP_BROWSER_BRIDGE_NOT_FORWARDED_CODE, + 'The Orca desktop sharing its browser cannot read tab notes. Update Orca on that desktop.' + ) + } const result = await options.registry.forward( { method: forwardedMethod, params, ...(workspaceId ? { workspaceId } : {}) }, { timeoutMs: forwardTimeoutMs(forwardedMethod, params), signal: options.signal } diff --git a/src/main/runtime/hosts/runtime-status.ts b/src/main/runtime/hosts/runtime-status.ts index 7800d47fea3..73dc3dea758 100644 --- a/src/main/runtime/hosts/runtime-status.ts +++ b/src/main/runtime/hosts/runtime-status.ts @@ -45,7 +45,7 @@ import { TERMINAL_PERSISTENCE_UNAVAILABLE_MESSAGE } from '../../../shared/runtime-capability-degradation' import { MOBILE_WEB_BUNDLE_CAPABILITY } from '../../../shared/mobile-web-bundle/mobile-web-bundle-capability' -import { loadBundledMobileWebBundle } from '../rpc/methods/mobile-delivery/bundled-mobile-web-bundle' +import { getBundledMobileWebBundleRoot } from '../rpc/methods/mobile-delivery/bundled-mobile-web-bundle' import { runtimeTerminalDegradation } from '../terminal/launch/native-terminal-availability' import { isWindowsProcessStartTimeAvailable } from '../../windows/windows-process-table' import { WORKTREE_CREATE_RESULT_TTL_MS } from '../workspaces/creation/worktree-create-idempotency' @@ -120,8 +120,8 @@ export abstract class OrcaRuntimeWithGetStatus extends RuntimeWorkspaceChangeEve capabilities.push(DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY) } capabilities.push(...darkSwitchRuntimeCapabilities()) - // Dev/serve installs may lack out/mobile-web; never advertise downloads this install cannot produce. - if (loadBundledMobileWebBundle()) { + // Dev/serve installs may lack out/mobile-web; advertise downloads only where the install ships it. + if (getBundledMobileWebBundleRoot()) { capabilities.push(MOBILE_WEB_BUNDLE_CAPABILITY) } // Report the actual failure so operators are not told to fix already-correct configuration. diff --git a/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts b/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts index a141ece1665..6251a4fca06 100644 --- a/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts +++ b/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts @@ -1,9 +1,9 @@ import { realpathSync } from 'node:fs' -import { describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { execFileSync } from 'node:child_process' -import { getRepoUpstreamMock } from '../orca-runtime-test-mocks/setup.spec' +import * as forkMetadata from '../../github/client/fetch/repo-slug-upstream' import { join } from 'node:path' import { mkdtemp, rm } from 'node:fs/promises' import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' @@ -12,6 +12,11 @@ import { store } from './orca-runtime-test-fixtures.spec' import type { Repo } from '../../../shared/repo-types' import type { RuntimeStore } from '../construction/runtime-store-contract' +const parentProbe = vi.spyOn(forkMetadata, 'probeRepoUpstream') +beforeEach(() => { + parentProbe.mockReset().mockResolvedValue({ upstream: undefined, origin: null }) +}) + function createRuntime(repos: Repo[]): OrcaRuntimeService { const runtimeStore: RuntimeStore = { ...store, @@ -61,7 +66,6 @@ const repoA = { provider: 'github' as const, owner: 'acme', repo: 'repo-a' } describe('OrcaRuntimeService project setup of an existing folder (#30663)', () => { it('refuses to relabel a folder whose own GitHub remote names another repository', async () => { const repos: Repo[] = [] - getRepoUpstreamMock.mockResolvedValueOnce(null) const runtime = createRuntime(repos) await withGitFolder({ origin: 'https://github.com/acme/repo-b.git' }, async (path) => { @@ -118,3 +122,447 @@ describe('OrcaRuntimeService project setup of an existing folder (#30663)', () = ) }) }) + +describe('explicit fork project setup with deferred ordinary metadata', () => { + it.each([ + ['git@gh-personal:me/repo-a.git', 'github:me/repo-a', undefined, null], + [ + 'https://code.corp.example/me/repo-a.git', + 'github:code.corp.example/me/repo-a', + 'code.corp.example', + undefined + ] + ] as const)( + 'keeps a resolved origin nonfork through setup when its local hostname needs resolution: %s', + async (url, projectId, host, upstream) => { + const repos: Repo[] = [] + const origin = { owner: 'me', repo: 'repo-a', ...(host ? { host } : {}) } + parentProbe.mockResolvedValue({ upstream, origin }) + const runtime = createRuntime(repos) + await withGitFolder({ origin: url }, async (path) => { + const result = await runtime.setupProjectExistingFolder({ + projectId, + projectProviderIdentity: { provider: 'github', ...origin }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe(projectId) + expect(result.repo.upstream).toBeNull() + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe(projectId) + expect(parentProbe).toHaveBeenCalledTimes(1) + }) + } + ) + + it.each([ + ['github:acme/repo-a', { owner: 'acme', repo: 'repo-a' }], + ['github:me/repo-a', { owner: 'me', repo: 'repo-a' }] + ] as const)( + 'preserves selected project %s when a hosted parent is known', + async (projectId, upstream) => { + const repos: Repo[] = [] + parentProbe.mockResolvedValue({ + upstream: { owner: 'acme', repo: 'repo-a' }, + origin: { owner: 'me', repo: 'repo-a' } + }) + const runtime = createRuntime(repos) + await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { + const result = await runtime.setupProjectExistingFolder({ + projectId, + projectProviderIdentity: { provider: 'github', ...upstream }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe(projectId) + expect(result.repo.upstream).toEqual(upstream) + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe(projectId) + expect(parentProbe).toHaveBeenCalledTimes(1) + }) + } + ) + + it.each([null, undefined])( + 'keeps a matching origin nonfork when parent evidence is %s', + async (upstream) => { + const repos: Repo[] = [] + parentProbe.mockResolvedValue({ upstream, origin: { owner: 'me', repo: 'repo-a' } }) + const runtime = createRuntime(repos) + await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toBeNull() + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe('github:me/repo-a') + expect(parentProbe).toHaveBeenCalledTimes(1) + const again = await runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(again.repo.upstream).toBeNull() + expect(parentProbe).toHaveBeenCalledTimes(1) + }) + } + ) +}) + +it('completes parent-selected setup while unrelated background metadata remains pending', async () => { + await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { + const repos: Repo[] = [ + { + id: 'blocker', + path: '/blocked', + displayName: 'blocker', + badgeColor: 'blue', + addedAt: 1, + kind: 'git' + } + ] + const runtime = createRuntime(repos) + const gate = Promise.withResolvers() + parentProbe + .mockImplementationOnce(() => gate.promise) + .mockResolvedValue({ + upstream: { owner: 'acme', repo: 'repo-a' }, + origin: { owner: 'me', repo: 'repo-a' } + }) + const background = runtime.repositoryForkBackfill.enqueue(repos) + try { + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:acme/repo-a', + projectProviderIdentity: repoA, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe('github:acme/repo-a') + expect(repos[0].upstream).toBeUndefined() + expect(parentProbe).toHaveBeenCalledTimes(2) + } finally { + gate.resolve({ upstream: null, origin: null }) + await background + } + }) +}) + +it.each([false, true])( + 'refuses changed current origin after an unavailable lookup (pre-existing=%s)', + async (existing) => { + await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { + const repos: Repo[] = [] + if (existing) { + repos.push({ + id: 'selected', + path: realpathSync(path), + displayName: 'repo-a', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1', + gitRemoteIdentity: { + canonicalKey: 'github.com/me/repo-a', + remoteName: 'origin', + remoteUrl: 'https://github.com/me/repo-a.git' + } + }) + } + const runtime = createRuntime(repos) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + parentProbe.mockImplementationOnce(() => { + started.resolve() + return gate.promise + }) + const setup = runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + const rejection = expect(setup).rejects.toThrow(/points at other\/repo-a, not me\/repo-a/) + await started.promise + execFileSync('git', ['remote', 'set-url', 'origin', 'https://github.com/other/repo-a.git'], { + cwd: path, + stdio: 'ignore' + }) + gate.resolve({ upstream: undefined, origin: { owner: 'me', repo: 'repo-a' } }) + await rejection + expect(repos).toHaveLength(existing ? 1 : 0) + expect(parentProbe).toHaveBeenCalledTimes(1) + }) + } +) + +it.each([ + [ + 'older automatic avatar', + { + type: 'image', + source: 'github', + src: 'https://ghe.corp.example/old.png?size=64', + label: 'old/repo-a' + }, + { host: 'ghe.corp.example', owner: 'new', repo: 'repo-a' } + ], + [ + 'protected image', + { + type: 'image', + source: 'file', + src: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=' + }, + null + ] +] as const)( + 'links a current enterprise remote despite unavailable metadata and a retained %s', + async (_label, repoIcon, upstream) => { + await withGitFolder({ origin: 'https://ghe.corp.example/new/repo-a.git' }, async (path) => { + const repos: Repo[] = [ + { + id: 'selected', + path: realpathSync(path), + displayName: 'repo-a', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1', + gitRemoteIdentity: { + canonicalKey: 'ghe.corp.example/old/repo-a', + remoteName: 'origin', + remoteUrl: 'https://ghe.corp.example/old/repo-a.git' + }, + repoIcon + } + ] + const runtime = createRuntime(repos) + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:ghe.corp.example/new/repo-a', + projectProviderIdentity: { + provider: 'github', + host: 'ghe.corp.example', + owner: 'new', + repo: 'repo-a' + }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe('github:ghe.corp.example/new/repo-a') + expect(repos[0].upstream).toEqual(upstream) + expect(repos[0].repoIcon).toEqual(repoIcon) + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe('github:ghe.corp.example/new/repo-a') + }) + } +) + +it('retains matching null authority when a nonfork result settles during setup', async () => { + await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { + const repos: Repo[] = [] + const runtime = createRuntime(repos) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + parentProbe.mockImplementationOnce(() => { + started.resolve() + return gate.promise + }) + const setup = runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + await started.promise + execFileSync('git', ['remote', 'set-url', 'origin', 'https://github.com/other/repo-a.git'], { + cwd: path, + stdio: 'ignore' + }) + gate.resolve({ upstream: null, origin: { owner: 'me', repo: 'repo-a' } }) + const result = await setup + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toBeNull() + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe('github:me/repo-a') + }) +}) + +it('publishes metadata retained on a pre-existing row after explicit setup fails', async () => { + await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { + const repos: Repo[] = [ + { + id: 'selected', + path: realpathSync(path), + displayName: 'repo-a', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1' + } + ] + const runtime = createRuntime(repos) + parentProbe.mockResolvedValue({ + upstream: { owner: 'acme', repo: 'repo-a' }, + origin: { owner: 'me', repo: 'repo-a' } + }) + const notifications: string[] = [] + const unsubscribe = runtime.onClientEvent((event) => { + if (event.type === 'reposChanged') { + notifications.push(event.type) + } + }) + try { + await expect( + runtime.setupProjectExistingFolder({ + projectId: 'github:elsewhere/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'elsewhere', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + ).rejects.toThrow(/points at me\/repo-a, not elsewhere\/repo-a/) + expect(repos).toHaveLength(1) + expect(repos[0].upstream).toEqual({ owner: 'acme', repo: 'repo-a' }) + expect(notifications).toEqual(['reposChanged']) + expect(parentProbe).toHaveBeenCalledTimes(1) + } finally { + unsubscribe() + } + }) +}) + +it.each(['recovered parent', 'unavailable'] as const)( + 'settles an explicit origin after ordinary alias enrichment: %s', + async (evidence) => { + await withGitFolder({ origin: 'git@gh-personal:me/repo-a.git' }, async (path) => { + const repos: Repo[] = [] + const runtime = createRuntime(repos) + const origin = { owner: 'me', repo: 'repo-a' } + const ordinary = Promise.withResolvers() + const ordinaryStarted = Promise.withResolvers() + const ordinaryFinished = Promise.withResolvers() + const required = Promise.withResolvers() + const requiredStarted = Promise.withResolvers() + parentProbe + .mockImplementationOnce(() => { + ordinaryStarted.resolve() + return ordinary.promise + }) + .mockImplementationOnce(() => { + requiredStarted.resolve() + return required.promise + }) + const unsubscribe = runtime.onClientEvent((event) => { + if (event.type === 'reposChanged' && repos[0]?.repoIcon?.type === 'image') { + ordinaryFinished.resolve() + } + }) + try { + const added = await runtime.addRepo(path, 'git', 'runtime:env-1') + await ordinaryStarted.promise + ordinary.resolve({ upstream: undefined, origin }) + await ordinaryFinished.promise + expect(added.id).toBe(repos[0].id) + expect(repos[0].gitRemoteIdentity).toEqual({ + canonicalKey: 'gh-personal/me/repo-a', + remoteName: 'origin', + remoteUrl: 'git@gh-personal:me/repo-a.git' + }) + expect(repos[0].repoIcon).toEqual({ + type: 'image', + source: 'github', + src: 'https://github.com/me.png?size=64', + label: 'me/repo-a' + }) + expect(repos[0].upstream).toBeUndefined() + + const setup = runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', ...origin }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + await requiredStarted.promise + const completion = runtime.repositoryForkBackfill.resolve(repos[0]) + required.resolve({ + upstream: evidence === 'recovered parent' ? { owner: 'acme', repo: 'repo-a' } : undefined, + origin + }) + const result = await setup + await completion + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toEqual(evidence === 'recovered parent' ? origin : null) + parentProbe.mockResolvedValue({ upstream: { owner: 'acme', repo: 'repo-a' }, origin }) + await runtime.repositoryForkBackfill.run() + expect(repos[0].upstream).toEqual(evidence === 'recovered parent' ? origin : null) + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe('github:me/repo-a') + } finally { + ordinary.resolve({ upstream: undefined, origin }) + required.resolve({ upstream: undefined, origin }) + unsubscribe() + } + }) + } +) + +it('accepts remote-less saved-avatar equality without a required probe or new stamp', async () => { + await withGitFolder({}, async (path) => { + const repos: Repo[] = [ + { + id: 'legacy', + path: realpathSync(path), + displayName: 'repo-a', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1', + repoIcon: { + type: 'image', + source: 'github', + src: 'https://github.com/me.png?size=64', + label: 'me/repo-a' + } + } + ] + const runtime = createRuntime(repos) + const background = Promise.withResolvers() + parentProbe.mockImplementationOnce(() => background.promise) + try { + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toBeUndefined() + } finally { + const completion = runtime.repositoryForkBackfill.resolve(repos[0]) + background.resolve({ upstream: undefined, origin: null }) + await completion + } + expect(repos[0].upstream).toBeUndefined() + }) +}) diff --git a/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts b/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts index 352aef26709..5849b9c1848 100644 --- a/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts +++ b/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts @@ -1,79 +1,291 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../shared/repo-types' -import * as repoSlugUpstream from '../../github/client/fetch/repo-slug-upstream' -import { OrcaRuntimeService } from '../orca-runtime' -import { repoTarget } from '../../persistence/repo-host-target-matcher.test-fixture' +import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' +import { + probeRepoUpstream, + type RepoUpstreamProbe +} from '../../github/client/fetch/repo-slug-upstream' +import { RuntimeRepositoryForkBackfill } from './runtime-repository-fork-backfill' vi.mock('../../github/client/fetch/repo-slug-upstream', async (importOriginal) => ({ ...(await importOriginal>()), - getRepoSlug: vi.fn(), - getRepoUpstream: vi.fn() + probeRepoUpstream: vi.fn() })) - -const getRepoUpstream = vi.mocked(repoSlugUpstream.getRepoUpstream) -const getRepoSlug = vi.mocked(repoSlugUpstream.getRepoSlug) - -type BackfillInternals = { repositoryForkBackfill: { run(): Promise } } - -function makeRepo(overrides: Partial = {}): Repo { +const probe = vi.mocked(probeRepoUpstream) +const origin = { owner: 'me', repo: 'widget', host: 'github.com' } +const originIcon = { + type: 'image', + src: 'https://github.com/me.png?size=64', + source: 'github', + label: 'me/widget' +} +const parent = { owner: 'acme', repo: 'widget', host: 'github.com' } +function makeRepo(id = 'repo-1', overrides: Partial = {}): Repo { return { - id: 'repo-1', - path: '/workspace/rocket-pro', - displayName: 'rocket-pro', - badgeColor: '#2563eb', + id, + path: `/workspace/${id}`, + displayName: 'widget', + badgeColor: 'blue', addedAt: 1, kind: 'git', - repoIcon: { - type: 'image', - src: 'https://github.com/acme.png?size=64', - source: 'github', - label: 'acme/rocket-pro' - }, ...overrides } } - -function attachStore(runtime: OrcaRuntimeService, repos: Repo[]) { +function fixture(repos: Repo[]) { const updateRepo = vi.fn((target: Pick, updates: Partial) => { const index = repos.findIndex((repo) => repo.id === target.id) + if (index === -1) { + return null + } repos[index] = { ...repos[index], ...updates } + return repos[index] }) - Object.assign(runtime, { store: { getRepos: () => repos, updateRepo } }) - return updateRepo + const store = partialRuntimeStore({ + getRepos: () => repos, + getRepo: (id) => repos.find((repo) => repo.id === id), + updateRepo + }) + const notify = vi.fn() + return { + owner: new RuntimeRepositoryForkBackfill(() => store, notify), + repos, + notify, + updateRepo + } } - afterEach(() => { - vi.clearAllMocks() + vi.resetAllMocks() + vi.useRealTimers() }) -describe('startup fork-upstream backfill', () => { - it('keeps an icon chosen while avatar detection is pending', async () => { - const runtime = new OrcaRuntimeService() - const repo = makeRepo() - const repos = [repo] - const updateRepo = attachStore(runtime, repos) - getRepoUpstream.mockResolvedValue({ owner: 'upstream-org', repo: 'rocket' }) - let resolveSlug!: (value: { owner: string; repo: string }) => void - let markSlugStarted!: () => void - const slugStarted = new Promise((resolve) => { - markSlugStarted = resolve - }) - getRepoSlug.mockImplementationOnce( - () => - new Promise((resolve) => { - resolveSlug = resolve - markSlugStarted() - }) - ) - - const backfill = (runtime as unknown as BackfillInternals).repositoryForkBackfill.run() - await slugStarted - repos[0] = { ...repo, repoIcon: { type: 'emoji', emoji: '🚀' } } - resolveSlug({ owner: 'acme', repo: 'rocket-pro' }) - await backfill - - expect(updateRepo).toHaveBeenCalledExactlyOnceWith(repoTarget('repo-1'), { - upstream: { owner: 'upstream-org', repo: 'rocket' } +describe('repository metadata ownership', () => { + it('keeps unavailable parent evidence unknown, fills origin avatar, and recovers on startup', async () => { + const f = fixture([makeRepo()]) + probe + .mockResolvedValueOnce({ upstream: undefined, origin }) + .mockResolvedValueOnce({ upstream: parent, origin }) + await f.owner.run() + expect(f.repos[0].upstream).toBeUndefined() + expect(f.repos[0].repoIcon).toEqual(originIcon) + await f.owner.run() + expect(f.repos[0].upstream).toEqual(parent) + expect(f.repos[0].repoIcon).toEqual({ + ...originIcon, + src: 'https://github.com/acme.png?size=64', + label: 'acme/widget' }) + expect(probe).toHaveBeenCalledTimes(2) + expect(f.notify).toHaveBeenCalledTimes(2) }) + + it('does not reprobe a proved negative or an explicit null icon', async () => { + const f = fixture([makeRepo('negative'), makeRepo('explicit', { repoIcon: null })]) + probe.mockResolvedValue({ upstream: null, origin: null }) + await f.owner.run() + await f.owner.run() + expect(f.repos.map((repo) => repo.upstream)).toEqual([null, null]) + expect(f.repos[1].repoIcon).toBeNull() + expect(probe).toHaveBeenCalledTimes(2) + expect(f.notify).toHaveBeenCalledTimes(1) + }) + + it.each(['removed', 'moved', 'folder', 'chosen-icon', 'selected-origin'] as const)( + 'rejects stale metadata after %s changes while hosted work is pending', + async (change) => { + const f = fixture([makeRepo()]) + const result = Promise.withResolvers() + const started = Promise.withResolvers() + probe.mockImplementationOnce(() => { + started.resolve() + return result.promise + }) + const work = f.owner.run() + await started.promise + if (change === 'removed') { + f.repos.splice(0, 1) + } + if (change === 'moved') { + f.repos[0] = { ...f.repos[0], path: '/elsewhere' } + } + if (change === 'folder') { + f.repos[0] = { ...f.repos[0], kind: 'folder' } + } + if (change === 'chosen-icon') { + f.repos[0] = { ...f.repos[0], repoIcon: { type: 'emoji', emoji: '🚀' } } + } + if (change === 'selected-origin') { + f.repos[0] = { ...f.repos[0], upstream: null } + } + result.resolve({ upstream: parent, origin }) + await work + if (change === 'chosen-icon') { + expect(f.repos[0].repoIcon).toEqual({ type: 'emoji', emoji: '🚀' }) + expect(f.repos[0].upstream).toEqual(parent) + } else if (change === 'selected-origin') { + expect(f.repos[0].upstream).toBeNull() + expect(f.repos[0].repoIcon).toEqual(originIcon) + } else { + expect(f.updateRepo).not.toHaveBeenCalled() + } + } + ) + + it.each([12, 120])( + 'serializes and deduplicates a finite %i-row batch with one notice', + async (count) => { + const f = fixture(Array.from({ length: count }, (_, index) => makeRepo(`repo-${index}`))) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + let active = 0 + let peak = 0 + probe.mockImplementation(async () => { + active++ + peak = Math.max(peak, active) + started.resolve() + await gate.promise + active-- + return { upstream: null, origin: null } + }) + const batch = f.owner.run() + await started.promise + const duplicate = f.owner.enqueue(f.repos) + const required = f.owner.resolve(f.repos[0]) + gate.resolve({ upstream: null, origin: null }) + await Promise.all([batch, duplicate, required]) + expect(peak).toBe(1) + expect(probe).toHaveBeenCalledTimes(count) + expect(f.updateRepo).toHaveBeenCalledTimes(count) + expect(f.notify).toHaveBeenCalledTimes(1) + await f.owner.run() + expect(probe).toHaveBeenCalledTimes(count) + } + ) + + it('publishes a completed finite batch while a later batch is still pending', async () => { + const f = fixture([makeRepo('first'), makeRepo('later')]) + const first = Promise.withResolvers() + const later = Promise.withResolvers() + probe.mockImplementationOnce(() => first.promise).mockImplementationOnce(() => later.promise) + const a = f.owner.enqueue([f.repos[0]]) + const b = f.owner.enqueue([f.repos[1]]) + first.resolve({ upstream: null, origin: null }) + await a + expect(f.notify).toHaveBeenCalledTimes(1) + later.resolve({ upstream: null, origin: null }) + await b + expect(f.notify).toHaveBeenCalledTimes(2) + }) + + it.each([12, 120])( + 'starts a required row ahead of %i unrelated background rows without duplicating it', + async (count) => { + const f = fixture(Array.from({ length: count }, (_, index) => makeRepo(`repo-${index}`))) + const blocker = Promise.withResolvers() + probe + .mockImplementationOnce(() => blocker.promise) + .mockResolvedValue({ upstream: parent, origin }) + const batch = f.owner.run() + const selected = f.owner.resolve(f.repos[count - 1]) + try { + await vi.waitFor(() => expect(f.repos[count - 1].upstream).toEqual(parent)) + await selected + expect(f.repos[0].upstream).toBeUndefined() + expect( + probe.mock.calls.filter(([path]) => path === `/workspace/repo-${count - 1}`) + ).toHaveLength(1) + } finally { + blocker.resolve({ upstream: null, origin: null }) + await batch + } + expect(probe).toHaveBeenCalledTimes(count) + expect(f.notify).toHaveBeenCalledTimes(1) + } + ) + + it('reserves optional capacity and admits required jobs in request order with at most four active', async () => { + const f = fixture(Array.from({ length: 8 }, (_, index) => makeRepo(`repo-${index}`))) + const pending = new Map>>() + const starts: string[] = [] + let active = 0 + let peak = 0 + probe.mockImplementation(async (path) => { + active++ + peak = Math.max(peak, active) + starts.push(path) + const result = Promise.withResolvers() + pending.set(path, result) + const value = await result.promise + active-- + return value + }) + const batch = f.owner.run() + // Request order differs from the older background inventory order. + const required = [5, 4, 3, 2, 1].map((index) => f.owner.resolve(f.repos[index])) + const join = f.owner.resolve(f.repos[0]) + try { + await vi.waitFor(() => expect(starts).toHaveLength(4)) + expect(starts).toEqual([ + '/workspace/repo-0', + '/workspace/repo-5', + '/workspace/repo-4', + '/workspace/repo-3' + ]) + pending.get('/workspace/repo-4')!.resolve({ upstream: null, origin: null }) + await vi.waitFor(() => expect(starts[4]).toBe('/workspace/repo-2')) + pending.get('/workspace/repo-5')!.resolve({ upstream: null, origin: null }) + await vi.waitFor(() => expect(starts[5]).toBe('/workspace/repo-1')) + expect(peak).toBe(4) + expect(starts).not.toContain('/workspace/repo-6') + } finally { + probe.mockResolvedValue({ upstream: null, origin: null }) + for (const result of pending.values()) { + result.resolve({ upstream: null, origin: null }) + } + await Promise.all([batch, join, ...required]) + } + expect(f.notify).toHaveBeenCalledTimes(1) + expect(probe).toHaveBeenCalledTimes(8) + }) + + it.each([12, 120])( + 'does not serialize protected image payloads across %i rows', + async (count) => { + const icons = Array.from({ length: count }, (_, index) => ({ + type: 'image' as const, + source: index % 2 ? ('upload' as const) : ('file' as const), + src: `data:image/png;base64,${'a'.repeat(350_000)}` + })) + const f = fixture(icons.map((repoIcon, index) => makeRepo(`repo-${index}`, { repoIcon }))) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + probe + .mockImplementationOnce(() => { + started.resolve() + return gate.promise + }) + .mockResolvedValue({ upstream: parent, origin }) + const protectedIcons = new Set(icons) + const serialized = vi.spyOn(JSON, 'stringify') + const batch = f.owner.run() + await started.promise + // A user replacing the captured protected image with an automatic icon must still survive. + f.repos[0] = { + ...f.repos[0], + repoIcon: { type: 'image', source: 'github', src: 'https://github.com/chosen.png' } + } + gate.resolve({ upstream: parent, origin }) + await batch + const protectedCopies = serialized.mock.calls.filter(([value]) => protectedIcons.has(value)) + serialized.mockRestore() + expect(protectedCopies).toHaveLength(0) + expect(f.repos.every((repo) => repo.upstream?.owner === 'acme')).toBe(true) + expect(f.repos[0].repoIcon).toEqual({ + type: 'image', + source: 'github', + src: 'https://github.com/chosen.png' + }) + expect(f.repos[1].repoIcon).toBe(icons[1]) + expect(f.notify).toHaveBeenCalledTimes(1) + } + ) }) diff --git a/src/main/runtime/repositories/repo-metadata-executable-absence.test.ts b/src/main/runtime/repositories/repo-metadata-executable-absence.test.ts new file mode 100644 index 00000000000..4c7afda5031 --- /dev/null +++ b/src/main/runtime/repositories/repo-metadata-executable-absence.test.ts @@ -0,0 +1,172 @@ +import { chmod, mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child' +import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' +import type { Repo } from '../../../shared/repo-types' + +const { spawnMock, gitMock } = vi.hoisted(() => ({ spawnMock: vi.fn(), gitMock: vi.fn() })) +vi.mock('node:child_process', async (importOriginal) => ({ + ...(await importOriginal>()), + spawn: spawnMock +})) +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: gitMock +})) + +import { RuntimeRepositoryForkBackfill } from './runtime-repository-fork-backfill' +import { ghExecFileAsync } from '../../git/command-runner/gh-exec-file' +import { GhExecutableAbsenceBatch } from '../../git/command-runner/gh-executable-absence-batch' + +const missing = () => Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT', path: 'gh' }) +function successfulSpawn() { + const child = createFakeSpawnedChild(4321) + queueMicrotask(() => { + child.stdout?.emit( + 'data', + Buffer.from('{"isFork":true,"parent":{"owner":{"login":"acme"},"name":"widget"}}') + ) + child.emit('exit', 0, null) + child.emit('close', 0, null) + }) + return child +} + +afterEach(() => { + vi.unstubAllEnvs() + vi.restoreAllMocks() + vi.resetAllMocks() +}) + +describe('finite metadata executable absence', () => { + it.each([12, 120])( + 'shares only the missing executable across a %i-row real probe batch and retries next batch', + async (count) => { + const root = await mkdtemp(join(tmpdir(), 'orca-metadata-absence-')) + const search = join(root, 'bin') + await mkdir(search) + vi.stubEnv('PATH', search) + const repos: Repo[] = [] + for (let i = 0; i < count; i++) { + const path = join(root, `repo-${i}`) + await mkdir(path) + repos.push({ + id: `repo-${i}`, + path, + displayName: 'widget', + kind: 'git', + badgeColor: 'blue', + addedAt: 1 + }) + } + gitMock.mockImplementation(async (args: string[], options: { cwd: string }) => { + if (args[2] === 'origin') { + return { stdout: 'https://github.com/me/widget.git', stderr: '' } + } + if (options.cwd === repos[1].path) { + return { stdout: 'https://github.com/acme/widget.git', stderr: '' } + } + throw Object.assign(new Error('No such remote'), { + code: 2, + stderr: "error: No such remote 'upstream'" + }) + }) + const notify = vi.fn() + const store = partialRuntimeStore({ + getRepos: () => repos, + getRepo: (id) => repos.find((repo) => repo.id === id), + updateRepo: (target, updates) => { + const repo = repos.find((repo) => repo.id === target.id) + if (!repo) { + return null + } + Object.assign(repo, updates) + return repo + } + }) + const owner = new RuntimeRepositoryForkBackfill(() => store, notify) + spawnMock.mockImplementation(() => { + throw missing() + }) + try { + await owner.run() + expect(spawnMock).toHaveBeenCalledTimes(1) + expect(repos[0].upstream).toBeUndefined() + expect(repos[0].repoIcon).toEqual({ + type: 'image', + source: 'github', + src: 'https://github.com/me.png?size=64', + label: 'me/widget' + }) + expect(repos[1].upstream).toEqual({ owner: 'acme', repo: 'widget', host: 'github.com' }) + expect(notify).toHaveBeenCalledTimes(1) + spawnMock.mockImplementation(successfulSpawn) + await owner.run() + expect(repos.every((repo) => repo.upstream?.owner === 'acme')).toBe(true) + expect(spawnMock).toHaveBeenCalledTimes(count) + expect(notify).toHaveBeenCalledTimes(2) + } finally { + await rm(root, { recursive: true, force: true }) + } + } + ) + + it('does not suppress a fresh explicit lookup, changed search context, or per-repository API failure', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-metadata-search-')) + const other = join(root, 'other') + await mkdir(other) + const batch = new GhExecutableAbsenceBatch() + const options = { cwd: root, env: { PATH: root } } + spawnMock.mockImplementation(() => { + throw missing() + }) + try { + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + ).rejects.toThrow('ENOENT') + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + ).rejects.toThrow('ENOENT') + expect(spawnMock).toHaveBeenCalledTimes(1) + await expect( + batch.run(() => + ghExecFileAsync(['repo', 'view', 'me/widget'], { ...options, env: { PATH: other } }) + ) + ).rejects.toThrow('ENOENT') + expect(spawnMock).toHaveBeenCalledTimes(2) + spawnMock.mockImplementation(successfulSpawn) + // A required action runs outside the batch's absence evidence and invalidates it on success. + await ghExecFileAsync(['repo', 'view', 'me/widget'], options) + await batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + expect(spawnMock).toHaveBeenCalledTimes(4) + spawnMock.mockImplementationOnce(() => { + throw new Error('repository not authorized') + }) + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'private/widget'], options)) + ).rejects.toThrow('not authorized') + await batch.run(() => ghExecFileAsync(['repo', 'view', 'public/widget'], options)) + expect(spawnMock).toHaveBeenCalledTimes(6) + // An existing wrapper with an absent interpreter is not proof that gh is absent. + await writeFile( + join(root, process.platform === 'win32' ? 'gh.exe' : 'gh'), + '#!/missing/interpreter\n' + ) + await chmod(join(root, process.platform === 'win32' ? 'gh.exe' : 'gh'), 0o755) + spawnMock.mockImplementation(() => { + throw missing() + }) + for (let i = 0; i < 2; i++) { + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + ).rejects.toThrow('ENOENT') + } + expect(spawnMock).toHaveBeenCalledTimes(8) + } finally { + batch.close() + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/runtime/repositories/runtime-project-host-setup-controller.ts b/src/main/runtime/repositories/runtime-project-host-setup-controller.ts index 87fd723ece6..5a0cb4ce49a 100644 --- a/src/main/runtime/repositories/runtime-project-host-setup-controller.ts +++ b/src/main/runtime/repositories/runtime-project-host-setup-controller.ts @@ -20,7 +20,10 @@ import { type ExecutionHostId } from '../../../shared/execution-host' import { getProjectHostSetupForRepo } from '../../../shared/project-host-setup-lookup' -import { resolveImportedFolderProjectLink } from '../../../shared/imported-folder-project-identity' +import { + linkImportedFolderToProject, + type RepositoryMetadataOwner +} from '../../workspaces/catalog/imported-folder-project-link' import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { runWorktreeChangeInvalidators } from '../../ipc/worktrees/listing/worktree-change-invalidators' @@ -47,7 +50,7 @@ import { type ProjectHostSetupTarget } from '../../../shared/project-host-setup-target' -type RuntimeProjectHostSetupDependencies = { +type RuntimeProjectHostSetupDependencies = RepositoryMetadataOwner & { getStore: () => RuntimeStore | null listRepos: () => Repo[] addRepo: (path: string, kind: 'folder' | 'git', hostId: ExecutionHostId) => Promise @@ -260,14 +263,16 @@ export class RuntimeProjectHostSetupController { } } - private completeSetup( + private async completeSetup( args: ProjectHostSetupExistingFolderArgs, initialRepo: Repo, repoWasCreated: boolean, folderRemote: Pick - ): ProjectHostSetupResult { + ): Promise { try { - return this.linkRepo(args, initialRepo, folderRemote) + const result = await this.linkRepo(args, initialRepo, folderRemote) + this.deps.notifyReposChanged() + return result } catch (error) { if (repoWasCreated) { // Rollback must remove only this host's row, never a same-id sibling. @@ -275,53 +280,25 @@ export class RuntimeProjectHostSetupController { this.deps.invalidateResolvedWorktrees() this.deps.invalidateWorktreeScan(initialRepo.id) invalidateAuthorizedRootsCache() - this.deps.notifyReposChanged() } + this.deps.notifyReposChanged() throw error } } - private linkRepo( + private async linkRepo( args: ProjectHostSetupExistingFolderArgs, initialRepo: Repo, folderRemote: Pick - ): ProjectHostSetupResult { - const store = this.deps.getStore() - if (!store) { - throw new Error('runtime_unavailable') - } - assertWslMoveHostSetupWritable(store, { - projectId: args.projectId, - hostId: getRepoExecutionHostId(initialRepo), - repoId: initialRepo.id - }) - let repo = initialRepo - let setup = getProjectHostSetupForRepo(this.listSetups(), repo) - if (setup.projectId !== args.projectId) { - const existingProject = this.listProjects().find((project) => project.id === args.projectId) - const updated = store.updateRepo( - repo, - resolveImportedFolderProjectLink( - { ...repo, ...folderRemote }, - args.projectId, - existingProject?.providerIdentity ?? args.projectProviderIdentity - ) - ) - if (!updated) { - throw new Error(`Project setup repo disappeared before it could be linked: ${repo.id}`) - } - repo = updated - setup = getProjectHostSetupForRepo(this.listSetups(), repo) - } - const setupMethod = args.setupMethod ?? 'imported-existing-folder' - const updated = store.updateRepo(repo, { projectHostSetupMethod: setupMethod }) - if (!updated) { - throw new Error( - `Project setup repo disappeared before setup metadata could be linked: ${repo.id}` - ) - } - repo = updated - setup = getProjectHostSetupForRepo(this.listSetups(), repo) + ): Promise { + const repo = await linkImportedFolderToProject( + this.deps.getStore, + initialRepo, + folderRemote, + args, + this.deps + ) + const setup = getProjectHostSetupForRepo(this.listSetups(), repo) const project = this.listProjects().find((entry) => entry.id === setup.projectId) if (!project) { throw new Error(`Project setup was created without a project record: ${setup.projectId}`) diff --git a/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts b/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts index 57936ac536f..718f6c32c17 100644 --- a/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts +++ b/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts @@ -26,6 +26,7 @@ async function clonedRepo(remoteUrl: string): Promise { function makeController(cloned: Repo) { const repos: Repo[] = [] const store = { + getRepos: () => repos, getProjects: () => projectHostSetupProjectionFromRepos(repos).projects, getProjectHostSetups: () => projectHostSetupProjectionFromRepos(repos).setups, updateRepo: ({ id }: Pick, updates: Partial) => { @@ -55,6 +56,8 @@ function makeController(cloned: Repo) { invalidateResolvedWorktrees: vi.fn(), invalidateWorktreeScan: vi.fn(), notifyReposChanged: vi.fn(), + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true), countLiveTerminalsForRepo: () => 0 }) return { controller, repos } diff --git a/src/main/runtime/repositories/runtime-repository-clone-controller.ts b/src/main/runtime/repositories/runtime-repository-clone-controller.ts index 7d74b2272e3..92fc7def209 100644 --- a/src/main/runtime/repositories/runtime-repository-clone-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-clone-controller.ts @@ -23,7 +23,7 @@ import type { } from '../../../shared/git/clone/clone-target-check' import { runWithGitReadCacheInvalidation } from '../../git/source-control/git-read-cache-invalidation' import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { getRepoName } from '../../git/repo' import { inspectGitRepoForRegistrationAsync } from '../../git/repo-detection' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' @@ -216,7 +216,7 @@ export class RuntimeRepositoryCloneController { // cloneRepo validated and cloned locally; runtime row stamps do not change where files live. // Register Git's checkout path so the clone stays its own selected checkout. const repoPath = (await inspectGitRepoForRegistrationAsync(clonePath)).rootPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: 'git', executionHostId: LOCAL_EXECUTION_HOST_ID diff --git a/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts b/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts index d4840037fed..869a7504ff3 100644 --- a/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts +++ b/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts @@ -9,7 +9,7 @@ import { RuntimeRepositoryCloneController } from './runtime-repository-clone-con import type { RuntimeStore } from '../construction/runtime-store-contract' vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) + detectRepoLocalMetadata: vi.fn().mockResolvedValue({}) })) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) diff --git a/src/main/runtime/repositories/runtime-repository-command-surface.ts b/src/main/runtime/repositories/runtime-repository-command-surface.ts index 8cc6306f3fb..4bf48c0edf9 100644 --- a/src/main/runtime/repositories/runtime-repository-command-surface.ts +++ b/src/main/runtime/repositories/runtime-repository-command-surface.ts @@ -3,6 +3,7 @@ import type { RuntimeHostedReviewCommands } from '../integrations/reviews/runtim import type { RuntimeNestedRepoImport } from './runtime-nested-repo-import' import type { RuntimeProjectGroupController } from './runtime-project-group-controller' import type { RuntimeProjectHostSetupController } from './runtime-project-host-setup-controller' +import type { RuntimeRepositoryForkBackfill } from './runtime-repository-fork-backfill' import type { RuntimeRepositoryCloneController } from './runtime-repository-clone-controller' import type { RuntimeRepositoryHooksCommands } from './runtime-repository-hooks-commands' import type { RuntimeRepositoryIssueCommand } from './runtime-repository-issue-command' @@ -97,7 +98,9 @@ type RuntimeRepositoryCommandOwners = { } export function installRuntimeRepositoryCommandSurface( - target: RuntimeRepositoryCommandSurface, + target: RuntimeRepositoryCommandSurface & { + readonly repositoryForkBackfill: RuntimeRepositoryForkBackfill + }, owners: RuntimeRepositoryCommandOwners ): void { const host = owners.projectHostSetups @@ -142,9 +145,23 @@ export function installRuntimeRepositoryCommandSurface( isGitAvailable: server.isGitAvailable.bind(server), listSparsePresets: sparse.list.bind(sparse), saveSparsePreset: sparse.save.bind(sparse), - addRepo: registrations.add.bind(registrations), - createRepo: registrations.create.bind(registrations), - cloneRepo: clones.clone.bind(clones), + addRepo: async (...args: Parameters) => { + const repo = await registrations.add(...args) + void target.repositoryForkBackfill.enqueue([repo]) + return repo + }, + createRepo: async (...args: Parameters) => { + const result = await registrations.create(...args) + if ('repo' in result) { + void target.repositoryForkBackfill.enqueue([result.repo]) + } + return result + }, + cloneRepo: async (...args: Parameters) => { + const repo = await clones.clone(...args) + void target.repositoryForkBackfill.enqueue([repo]) + return repo + }, checkCloneTarget: clones.checkTarget.bind(clones), showRepo: settings.show.bind(settings), setRepoBaseRef: settings.setBaseRef.bind(settings), diff --git a/src/main/runtime/repositories/runtime-repository-fork-backfill.ts b/src/main/runtime/repositories/runtime-repository-fork-backfill.ts index 94bedda433a..c4682c4c489 100644 --- a/src/main/runtime/repositories/runtime-repository-fork-backfill.ts +++ b/src/main/runtime/repositories/runtime-repository-fork-backfill.ts @@ -1,18 +1,30 @@ -import { - getRepoExecutionHostId, - getRepoSshConnectionId, - LOCAL_EXECUTION_HOST_ID -} from '../../../shared/execution-host' -import type { GitHubOwnerRepo } from '../../../shared/github/pull-request-types' +import { getRepoExecutionHostId, getRepoSshConnectionId } from '../../../shared/execution-host' import type { Repo } from '../../../shared/repo-types' -import { getRepoUpstream } from '../../github/client/fetch/repo-slug-upstream' -import { detectGitHubAvatarIcon } from '../../repository-icons/repo-icon-autodetect' +import { githubAvatarIcon, githubAvatarSlug } from '../../../shared/repo-icon' +import { probeRepoUpstream } from '../../github/client/fetch/repo-slug-upstream' +import { GhExecutableAbsenceBatch } from '../../git/command-runner/gh-executable-absence-batch' import type { RuntimeStore } from '../construction/runtime-store-contract' import { isWslMoveRepoBlocked } from '../../persistence/moving-wsl-projects/wsl-move-background-backoff' import { blockedWslDistroForPath, wslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' +type MetadataJob = { + store: RuntimeStore + repo: Repo + background: boolean + active: boolean + required: boolean + batch?: GhExecutableAbsenceBatch + done: Promise + finish: (changed: boolean) => void +} + export class RuntimeRepositoryForkBackfill { private started = false + private active = 0 + private backgroundActive = 0 + private readonly jobs = new Map>() + private readonly requiredQueue = new Set() + private readonly backgroundQueue = new Set() constructor( private readonly getStore: () => RuntimeStore | null, @@ -27,64 +39,204 @@ export class RuntimeRepositoryForkBackfill { void this.run() } - async run(): Promise { + run(): Promise { + return this.enqueue( + (this.getStore()?.getRepos() ?? []).filter((repo) => repo.upstream === undefined) + ) + } + + async enqueue(repos: readonly Repo[]): Promise { + const batch: Promise[] = [] + const availability = new GhExecutableAbsenceBatch() try { - const store = this.getStore() - if (!store) { - throw new Error('runtime_unavailable') + for (const repo of repos) { + const job = this.admit(repo) + if (!job || job.background) { + continue + } + job.background = true + job.batch = availability + if (!job.required && !job.active) { + this.backgroundQueue.add(job) + } + batch.push(job.done) } - let changed = false - for (const repo of store.getRepos()) { - // Resolve executionHostId too: raw connectionId misses SSH-only rows, whose gh/Git must never run here. - // WSL-move-fenced repos keep upstream unset for next startup retry. - if ( - repo.upstream !== undefined || - repo.kind === 'folder' || - getRepoSshConnectionId(repo) || - isWslMoveRepoBlocked(repo) - ) { - continue - } - // E9: gh/Git on a stopped distro's repo boots it; upstream stays unset for the next pass. - if (wslDistroForPath(repo.path) && (await blockedWslDistroForPath(repo.path))) { - continue - } - let upstream: GitHubOwnerRepo | null - try { - upstream = await getRepoUpstream(repo.path, null) - } catch { - continue - } - const repoIcon = - upstream && repo.repoIcon?.type === 'image' && repo.repoIcon.source === 'github' - ? await detectGitHubAvatarIcon(repo.path, LOCAL_EXECUTION_HOST_ID, upstream) - : null - // Qualify by host: WSL moves leave hidden local rows beside same-id host rows. - const hostId = getRepoExecutionHostId(repo) - const current = store - .getRepos() - .find( - (candidate) => candidate.id === repo.id && getRepoExecutionHostId(candidate) === hostId - ) - if (!current || current.upstream !== undefined || isWslMoveRepoBlocked(current)) { - continue - } - const updates: Partial = { upstream: upstream ?? null } - if ( - repoIcon && - current.repoIcon?.type === 'image' && - current.repoIcon.source === 'github' - ) { - updates.repoIcon = repoIcon - } - store.updateRepo(current, updates) - changed = true - } - if (changed) { + this.drain() + // Each admitted finite batch owns its notice, independent of later arrivals. + const changes = await Promise.all(batch) + if (changes.some(Boolean)) { this.notifyChanged() } - } catch { - // Best-effort startup migration. + } finally { + availability.close() } } + + async resolve(repo: Repo): Promise { + if (this.current(this.getStore(), repo)?.upstream !== undefined) { + return true + } + const job = this.admit(repo) + if (!job) { + return false + } + if (!job.required && !job.active) { + this.backgroundQueue.delete(job) + this.requiredQueue.add(job) + } + job.required = true + this.drain() + await job.done + return true + } + + private key(repo: Repo): string { + return `${repo.id}\0${getRepoExecutionHostId(repo)}\0${repo.path}\0${repo.kind}` + } + + private current(store: RuntimeStore | null, snapshot: Repo): Repo | undefined { + if (!store || store !== this.getStore()) { + return undefined + } + const host = getRepoExecutionHostId(snapshot) + const found = store.getRepo(snapshot.id) + const row = + found && getRepoExecutionHostId(found) === host + ? found + : store + .getRepos() + .find( + (candidate) => + candidate.id === snapshot.id && getRepoExecutionHostId(candidate) === host + ) + return row && + row.path === snapshot.path && + row.kind === snapshot.kind && + row.kind !== 'folder' && + !getRepoSshConnectionId(row) && + !isWslMoveRepoBlocked(row) + ? row + : undefined + } + + private admit(repo: Repo): MetadataJob | undefined { + const store = this.getStore() + const current = this.current(store, repo) + if (!store || !current || (current.upstream !== undefined && current.repoIcon !== undefined)) { + return undefined + } + let jobs = this.jobs.get(store) + if (!jobs) { + this.jobs.set(store, (jobs = new Map())) + } + const key = this.key(current) + const existing = jobs.get(key) + if (existing) { + return existing + } + let finish!: MetadataJob['finish'] + const done = new Promise((resolve) => { + finish = resolve + }) + const job: MetadataJob = { + store, + repo: { ...current }, + background: false, + active: false, + required: false, + done, + finish + } + jobs.set(key, job) + return job + } + + private drain(): void { + while (this.active < 4) { + const queue = this.requiredQueue.size ? this.requiredQueue : this.backgroundQueue + if (queue === this.backgroundQueue && this.backgroundActive > 0) { + return + } + const job = queue.values().next().value + if (!job) { + return + } + queue.delete(job) + job.active = true + this.active++ + const background = !job.required + if (background) { + this.backgroundActive++ + } + void this.processJob(job, background) + } + } + + private async processJob(job: MetadataJob, background: boolean): Promise { + let changed = false + try { + changed = await (background && job.batch + ? job.batch.run(() => this.probe(job)) + : this.probe(job)) + } catch { + /* Optional metadata stays retryable. */ + } finally { + this.active-- + if (background) { + this.backgroundActive-- + } + this.retire(job, changed) + this.drain() + } + } + + private retire(job: MetadataJob, changed: boolean): void { + const jobs = this.jobs.get(job.store) + jobs?.delete(this.key(job.repo)) + if (jobs?.size === 0) { + this.jobs.delete(job.store) + } + job.finish(changed) + } + + private async probe(job: MetadataJob): Promise { + const { store, repo } = job + let current = this.current(store, repo) + if (!current) { + return false + } + if (wslDistroForPath(repo.path) && (await blockedWslDistroForPath(repo.path))) { + return false + } + current = this.current(store, repo) + if (!current) { + return false + } + const result = await probeRepoUpstream(repo.path, null, {}, current.upstream === undefined) + current = this.current(store, repo) + if (!current) { + return false + } + const updates: Partial = {} + if (current.upstream === undefined && result.upstream !== undefined) { + updates.upstream = result.upstream + } + if ( + current.repoIcon === undefined || + (current.repoIcon?.type === 'image' && + current.repoIcon.source === 'github' && + repo.repoIcon?.type === 'image' && + repo.repoIcon.source === 'github' && + JSON.stringify(current.repoIcon) === JSON.stringify(repo.repoIcon)) + ) { + // Defined null is an explicit origin choice or a proved negative, never the late parent. + const upstream = current.upstream === undefined ? result.upstream : current.upstream + const slug = githubAvatarSlug(result.origin, upstream) + const icon = slug ? githubAvatarIcon(slug) : undefined + if (icon && JSON.stringify(icon) !== JSON.stringify(current.repoIcon)) { + updates.repoIcon = icon + } + } + return Object.keys(updates).length > 0 && !!store.updateRepo(current, updates) + } } diff --git a/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts b/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts index 5374f64d9a1..8584ec06815 100644 --- a/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts +++ b/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts @@ -9,7 +9,7 @@ import { RuntimeRepositoryRegistrationController } from './runtime-repository-re import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) + detectRepoLocalMetadata: vi.fn().mockResolvedValue({}) })) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) diff --git a/src/main/runtime/repositories/runtime-repository-registration-controller.ts b/src/main/runtime/repositories/runtime-repository-registration-controller.ts index bca8931391f..61d975024ee 100644 --- a/src/main/runtime/repositories/runtime-repository-registration-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-registration-controller.ts @@ -16,7 +16,7 @@ import { getClonePathComparisonKey, getSavedProjectPathKeys } from '../../git/re import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' import { findProjectAtSameRealPath } from '../../workspaces/catalog/project-realpath-identity' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import type { RuntimeStore } from '../construction/runtime-store-contract' import { runtimePathsEqual } from '../workspaces/catalog/runtime-worktree-path-identity' @@ -96,7 +96,7 @@ export class RuntimeRepositoryRegistrationController { return this.reuseExisting(store, existing, executionHostId) } // This controller validated/read the path locally; runtime: is the paired-client address, not another machine. - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind, executionHostId: LOCAL_EXECUTION_HOST_ID @@ -229,7 +229,7 @@ export class RuntimeRepositoryRegistrationController { repoKind === 'git' ? (await inspectGitRepoForRegistrationAsync(targetPath)).rootPath : targetPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: repoKind, executionHostId: LOCAL_EXECUTION_HOST_ID diff --git a/src/main/runtime/rpc/methods/browser/browser-core.ts b/src/main/runtime/rpc/methods/browser/browser-core.ts index d9d6d14ed1f..6edf1f772ba 100644 --- a/src/main/runtime/rpc/methods/browser/browser-core.ts +++ b/src/main/runtime/rpc/methods/browser/browser-core.ts @@ -118,6 +118,12 @@ export const BROWSER_CORE_METHODS = [ params: TabCurrent, handler: async (params, { runtime }) => runtime.browserTabCurrent(params) }), + defineMethod({ + name: 'browser.tabAnnotations', + permission: 'workspace', + params: BrowserTarget, + handler: async (params, { runtime }) => runtime.browserTabAnnotations(params) + }), defineMethod({ name: 'browser.tabSwitch', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts b/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts index eac4e3e6047..8780e8f932b 100644 --- a/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts +++ b/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts @@ -2,6 +2,7 @@ import { DESKTOP_BROWSER_BRIDGE_CANCEL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY, + DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY, DesktopBrowserBridgeAttachParams, DesktopBrowserBridgeResultParams } from '../../../../../shared/desktop-browser-bridge-protocol' @@ -45,6 +46,9 @@ export const DESKTOP_BROWSER_BRIDGE_RPC_METHODS = [ enforcesExpectUrl: context.clientCapabilities?.includes(DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY) ?? false, + readsTabAnnotations: + context.clientCapabilities?.includes(DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY) ?? + false, emit }) let release = (): void => {} diff --git a/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts b/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts index 62878b48a72..3cc62c1c7f9 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts @@ -1,8 +1,9 @@ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { getAppEnvironment, hasAppEnvironment } from '../../../../../shared/app-environment' import { - MobileWebBundleManifestSchema, + InstalledMobileWebBundleManifestSchema, type MobileWebBundleManifest } from '../../../../../shared/mobile-web-bundle/manifest-contract' @@ -14,47 +15,63 @@ export type BundledMobileWebBundle = { } /** AppEnvironment keeps runtime imports Node-safe; absent environment means no install root. - * Probe app.asar/out and unpacked entrypoint layouts like getBundledWebClientRoot. */ + * Probe packaged and unpacked entrypoint layouts like findBundledWebClientRoot. */ export function getBundledMobileWebBundleRoot(): string | undefined { if (!hasAppEnvironment()) { return undefined } const appPath = getAppEnvironment().getAppPath() - const roots = [ - join(appPath, 'out', 'mobile-web'), - // Unpacked electron-vite sets appPath to out/main. - join(appPath, '..', 'mobile-web') - ] - return roots.find((root) => existsSync(join(root, MANIFEST_FILENAME))) -} - -// Installs are immutable until restart; undefined means unprobed, null means absent. -let cachedBundle: BundledMobileWebBundle | null | undefined - -export function loadBundledMobileWebBundle(): BundledMobileWebBundle | null { - if (cachedBundle === undefined) { - cachedBundle = readBundledMobileWebBundle() + if (probedRoot?.appPath === appPath) { + return probedRoot.root } - return cachedBundle + // Electron reads app.asar paths through the header it parsed at launch, which misses files an in-place update wrote. + const filesPath = appPath.endsWith('.asar') ? `${appPath}.unpacked` : appPath + const roots = [ + join(filesPath, 'out', 'mobile-web'), + // Unpacked electron-vite sets appPath to out/main. + join(filesPath, '..', 'mobile-web') + ] + const root = roots.find((candidate) => existsSync(join(candidate, MANIFEST_FILENAME))) + // An install keeps its layout, so only a miss is probed again (a dev build may produce the bundle later). + if (root) { + probedRoot = { appPath, root } + } + return root } -export function resetBundledMobileWebBundleCacheForTests(): void { - cachedBundle = undefined -} +let probedRoot: { appPath: string; root: string } | undefined -function readBundledMobileWebBundle(): BundledMobileWebBundle | null { +// Linux package managers replace the install under a running app, so the cache holds only while manifest.json's bytes do. +let cached: { root: string; raw: Buffer; bundle: BundledMobileWebBundle | null } | undefined + +export async function loadBundledMobileWebBundle(): Promise { const root = getBundledMobileWebBundleRoot() if (!root) { return null } const manifestPath = join(root, MANIFEST_FILENAME) - let raw: string + let raw: Buffer try { - raw = readFileSync(manifestPath, 'utf8') + raw = await readFile(manifestPath) } catch (error) { console.warn(`[mobile-web-bundle] cannot read ${manifestPath}:`, error) return null } + if (cached?.root !== root || !cached.raw.equals(raw)) { + cached = { + root, + raw, + bundle: parseBundledMobileWebBundle(root, manifestPath, raw.toString('utf8')) + } + } + return cached.bundle +} + +function parseBundledMobileWebBundle( + root: string, + manifestPath: string, + raw: string +): BundledMobileWebBundle | null { let parsed: unknown try { parsed = JSON.parse(raw) @@ -62,7 +79,7 @@ function readBundledMobileWebBundle(): BundledMobileWebBundle | null { console.warn(`[mobile-web-bundle] ${manifestPath} is not valid JSON:`, error) return null } - const manifest = MobileWebBundleManifestSchema.safeParse(parsed) + const manifest = InstalledMobileWebBundleManifestSchema.safeParse(parsed) if (!manifest.success) { // Bad dev/hand-edited bundles must degrade to absent, not crash a phone-accessible path. console.warn(`[mobile-web-bundle] ${manifestPath} does not match the manifest contract:`, { diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts index e429c63e881..4d8167004a4 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts @@ -11,7 +11,7 @@ export function resetMobileWebBundleAssetVerdictsForTests(): void { verdicts.clear() } -/** Cache one asset hash verdict per build; store the pending promise before await so concurrent readers share the hash. */ +/** Cache one passing asset hash verdict per build; store the pending promise before await so concurrent readers share the hash. */ export function verifyMobileWebBundleAsset( root: string, buildId: string, @@ -22,11 +22,16 @@ export function verifyMobileWebBundleAsset( if (cached) { return cached } - const verdict = hashAsset(root, asset).then(undefined, (error: unknown) => { - // A read that failed is not evidence the bytes changed, so it is not remembered as a verdict. - verdicts.delete(key) - throw error - }) + const verdict = hashAsset(root, asset) + // Keep only a match: a package install may still be writing this build's files, and a failed read proves nothing. + void verdict.then( + (matches) => { + if (!matches) { + verdicts.delete(key) + } + }, + () => verdicts.delete(key) + ) verdicts.set(key, verdict) return verdict } diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts index 5553b263030..ec3cab87d4d 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts @@ -13,8 +13,6 @@ import { type MobileWebBundleRangeResult } from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract' -import { resetBundledMobileWebBundleCacheForTests } from './bundled-mobile-web-bundle' - import type { RpcResponse } from '../../core' import type { RpcDispatcher } from '../../dispatcher' @@ -66,7 +64,6 @@ const INCOMPRESSIBLE: SyntheticAsset = (() => { beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), 'orca-mobile-web-bundle-range-')) installMobileWebBundleAppPath(scratch) - resetBundledMobileWebBundleCacheForTests() resetMobileWebBundleAssetVerdictsForTests() resetMobileWebBundleReadAdmissionForTests() vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts index e4ffbf35e4b..33ee1e2c731 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts @@ -7,7 +7,6 @@ import { MOBILE_WEB_BUNDLE_CHUNK_METHOD, MOBILE_WEB_BUNDLE_RANGE_METHOD } from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract' -import { resetBundledMobileWebBundleCacheForTests } from './bundled-mobile-web-bundle' import type { RpcResponse } from '../../core' import type { RpcDispatcher } from '../../dispatcher' import { resetMobileWebBundleAssetVerdictsForTests } from './mobile-web-bundle-asset-reader' @@ -32,7 +31,6 @@ function errorMessage(response: RpcResponse): string | undefined { beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), 'orca-mobile-web-bundle-window-')) installMobileWebBundleAppPath(scratch) - resetBundledMobileWebBundleCacheForTests() resetMobileWebBundleAssetVerdictsForTests() resetMobileWebBundleReadAdmissionForTests() vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts index 4ad687cb8f2..71549b9a859 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts @@ -1,4 +1,12 @@ -import { mkdirSync, mkdtempSync, rmSync, truncateSync, unlinkSync, writeFileSync } from 'node:fs' +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + truncateSync, + unlinkSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' @@ -18,8 +26,6 @@ import type { RpcRequest, RpcResponse } from '../../core' import '../../../../../shared/orcad-artifacts' import type { RpcDispatcher } from '../../dispatcher' -import { resetBundledMobileWebBundleCacheForTests } from './bundled-mobile-web-bundle' - import { fillMobileWebBundleReadWindow, resetMobileWebBundleAssetVerdictsForTests @@ -85,7 +91,6 @@ async function download(buildId: string, path: string): Promise<{ bytes: Buffer; beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), 'orca-mobile-web-bundle-')) installMobileWebBundleAppPath(scratch) - resetBundledMobileWebBundleCacheForTests() resetMobileWebBundleAssetVerdictsForTests() resetMobileWebBundleReadAdmissionForTests() vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -140,19 +145,43 @@ describe('an install that carries a mobile web bundle', () => { expect(body).toMatchObject({ dataBase64: '', eof: true, assetByteLength: 0 }) }) - // After auto-update, report build-changed before path lookup so clients restart from the manifest. - it('refuses the old buildId after the install swaps bundles mid-download', async () => { + // Linux package managers replace the install under a running host (STA-14385): serve the new build, never the gone one. + it('serves the replacement build after the install swaps bundles under a running host', async () => { const script = bundle.assets.find((asset) => asset.path.endsWith('.js'))! + expect((await call('mobileWeb.bundle.manifest')).ok).toBe(true) expect((await chunk({ buildId: bundle.buildId, path: script.path, offset: 0 })).ok).toBe(true) rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true }) const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 2) - resetBundledMobileWebBundleCacheForTests() expect(replacement.buildId).not.toBe(bundle.buildId) const stale = await chunk({ buildId: bundle.buildId, path: script.path, offset: 0 }) + const manifest = await call('mobileWeb.bundle.manifest') + const fresh = await chunk({ buildId: replacement.buildId, path: 'index.html', offset: 0 }) expect(errorMessage(stale)).toBe('mobile_web_bundle_build_changed') + expect( + MobileWebBundleManifestResultSchema.parse(manifest.ok && manifest.result).manifest.buildId + ).toBe(replacement.buildId) + expect(errorMessage(fresh)).toBeUndefined() + }) + + // A newer release written in place may add schema-v1 fields this host predates; it serves only the ones it knows. + it('serves a replacement manifest that carries fields this host does not know', async () => { + rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true }) + const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 5) + const manifestPath = join(replacement.root, 'manifest.json') + const written = JSON.parse(readFileSync(manifestPath, 'utf8')) + written.assets[0].laterAssetField = 1 + written.laterManifestField = true + writeFileSync(manifestPath, JSON.stringify(written), 'utf8') + + const response = await call('mobileWeb.bundle.manifest') + + const manifest = MobileWebBundleManifestResultSchema.parse( + response.ok && response.result + ).manifest + expect(manifest.buildId).toBe(replacement.buildId) }) // A path survives rebuild; key verdicts by build too so an old failure cannot poison new bytes. @@ -164,13 +193,26 @@ describe('an install that carries a mobile web bundle', () => { rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true }) const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 8) - resetBundledMobileWebBundleCacheForTests() const response = await chunk({ buildId: replacement.buildId, path: 'index.html', offset: 0 }) expect(errorMessage(response)).toBeUndefined() }) + // A package install writes the manifest and assets one file at a time; a mismatch mid-install must not stick. + it('serves an asset once its bytes match again, after a mismatch for the same build', async () => { + const original = mobileWebBundleFiller(640, 3) + writeFileSync(join(bundle.root, 'index.html'), mobileWebBundleFiller(640, 99)) + expect( + errorMessage(await chunk({ buildId: bundle.buildId, path: 'index.html', offset: 0 })) + ).toBe('mobile_web_bundle_asset_changed') + + writeFileSync(join(bundle.root, 'index.html'), original) + const response = await chunk({ buildId: bundle.buildId, path: 'index.html', offset: 0 }) + + expect(errorMessage(response)).toBeUndefined() + }) + // Map post-verification filesystem failure to a contract code without exposing the host install path. it('answers a changed asset, not the filesystem error, when the asset is gone after its verdict', async () => { const script = bundle.assets.find((asset) => asset.path.endsWith('.js'))! @@ -259,7 +301,20 @@ describe('where the resolver probes', () => { it('finds the bundle beside an out/main app path', async () => { const bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 3) installMobileWebBundleAppPath(join(scratch, 'out', 'main')) - resetBundledMobileWebBundleCacheForTests() + + const response = await call('mobileWeb.bundle.manifest') + + expect( + MobileWebBundleManifestResultSchema.parse(response.ok && response.result).manifest.buildId + ).toBe(bundle.buildId) + }) + + it('reads a packaged app from app.asar.unpacked, where an in-place update writes its files', async () => { + const bundle = writeSyntheticMobileWebBundle( + join(scratch, 'app.asar.unpacked', 'out', 'mobile-web'), + 4 + ) + installMobileWebBundleAppPath(join(scratch, 'app.asar')) const response = await call('mobileWeb.bundle.manifest') @@ -282,7 +337,6 @@ describe('an install with no mobile web bundle', () => { const root = join(scratch, 'out', 'mobile-web') mkdirSync(root, { recursive: true }) writeFileSync(join(root, 'manifest.json'), 'not json', 'utf8') - resetBundledMobileWebBundleCacheForTests() expect(errorMessage(await call('mobileWeb.bundle.manifest'))).toBe( 'mobile_web_bundle_unavailable' diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts index c7fe1de157b..3f763acedca 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts @@ -50,8 +50,8 @@ function bundleError(code: MobileWebBundleErrorCode): InvalidArgumentError { return new InvalidArgumentError(code) } -function requireBundle(): BundledMobileWebBundle { - const bundle = loadBundledMobileWebBundle() +async function requireBundle(): Promise { + const bundle = await loadBundledMobileWebBundle() if (!bundle) { throw bundleError('mobile_web_bundle_unavailable') } @@ -69,7 +69,7 @@ async function readLocaleCatalog( params: MobileWebBundleLocaleCatalogParams, ctx: RpcContext ): Promise { - const bundle = requireBundle() + const bundle = await requireBundle() const entry = bundle.manifest.catalogs?.find((catalog) => catalog.locale === params.locale) if (!entry) { throw bundleError('mobile_web_bundle_asset_unknown') @@ -157,7 +157,7 @@ async function readVerifiedWindow( encode: (window: VerifiedWindow) => Promise, sourceOf: (asset: MobileWebBundleAsset) => WindowSource = (asset) => asset ): Promise { - const bundle = requireBundle() + const bundle = await requireBundle() // Check build before path: auto-update means restart from the manifest, not missing-asset. if (params.buildId !== bundle.manifest.buildId) { throw bundleError('mobile_web_bundle_build_changed') @@ -212,7 +212,7 @@ export const MOBILE_WEB_BUNDLE_METHODS = [ permission: 'workspace', params: null, handler: async (): Promise => ({ - manifest: requireBundle().manifest, + manifest: (await requireBundle()).manifest, chunkBytes: MOBILE_WEB_BUNDLE_CHUNK_BYTES, // Complete replies must arrive within the phone's stall budget even on slow relays. rangeBytes: MOBILE_WEB_BUNDLE_CHUNK_BYTES diff --git a/src/main/runtime/rpc/repo-add-cli.integration.test.ts b/src/main/runtime/rpc/repo-add-cli.integration.test.ts index e5e71c09e88..4e0332a61df 100644 --- a/src/main/runtime/rpc/repo-add-cli.integration.test.ts +++ b/src/main/runtime/rpc/repo-add-cli.integration.test.ts @@ -13,14 +13,17 @@ import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial import type { RpcRequest } from './core' import { repoDispatcher } from './methods/projects/repo-rpc.test-fixture' import { UnixSocketTransport } from './unix-socket-transport' +import { acquire, release } from '../../github/gh-utils' +import { RuntimeRepositoryForkBackfill } from '../repositories/runtime-repository-fork-backfill' -vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) -})) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) })) +vi.mock('../../git/command-runner/gh-exec-file', () => ({ + ghExecFileAsync: vi.fn(async () => ({ stdout: '{"isFork":false}' })) +})) + const cliPath = '../../../cli/index' const { main }: { main: (argv: string[], cwd: string) => Promise } = await import(cliPath) const repoReply = z.object({ @@ -43,9 +46,19 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git invalidateWorktreeScan: () => {}, notifyReposChanged: () => {} }) + const metadata = new RuntimeRepositoryForkBackfill( + () => store, + () => {} + ) + let background = Promise.resolve() + let heldSlots = 0 const dispatcher = repoDispatcher({ getRuntimeId: () => 'repo-cli-test', - addRepo: (...args) => controller.add(...args), + addRepo: async (...args) => { + const repo = await controller.add(...args) + background = metadata.enqueue([repo]) + return repo + }, listVisibleRepos: () => repos, requireStore: () => store }) @@ -79,6 +92,11 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git const git = runProcessSync({ program: 'git', args: ['init', '-q', path] }) expect(git.code, git.stderr).toBe(0) } + const remote = runProcessSync({ + program: 'git', + args: ['-C', project, 'remote', 'add', 'origin', 'https://github.com/me/widget.git'] + }) + expect(remote.code, remote.stderr).toBe(0) await socket.start() await writeFile( getRuntimeMetadataPath(root), @@ -114,6 +132,10 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git expect(repos).toHaveLength(1) expect(await cli(['repo', 'list'])).toMatchObject({ result: { repos: [first] } }) + for (let slot = 0; slot < 4; slot++) { + await acquire() + heldSlots++ + } const subproject = repoReply.parse( await cli(['repo', 'add', '--path', project, '--kind', 'git']) ).result.repo @@ -122,6 +144,19 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git normalizeRuntimePathForComparison(project) ) expect(subproject.kind).toBe('git') + expect(await cli(['repo', 'list'])).toMatchObject({ + result: { + repos: [ + expect.objectContaining({ id: first.id }), + expect.objectContaining({ id: subproject.id }) + ] + } + }) + while (heldSlots > 0) { + release() + heldSlots-- + } + await background expect(repos).toHaveLength(2) const beforeInvalid = requests.length @@ -132,6 +167,11 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git expect(requests).toHaveLength(beforeInvalid) expect(repos).toHaveLength(2) } finally { + while (heldSlots > 0) { + release() + heldSlots-- + } + await background await socket.stop() vi.unstubAllEnvs() process.exitCode = previousExitCode diff --git a/src/main/runtime/terminal/driver/terminal-driver-resources.ts b/src/main/runtime/terminal/driver/terminal-driver-resources.ts index c9655ef980e..3cbe25f462c 100644 --- a/src/main/runtime/terminal/driver/terminal-driver-resources.ts +++ b/src/main/runtime/terminal/driver/terminal-driver-resources.ts @@ -43,6 +43,7 @@ import { RuntimeWorktreeBaseReconciliation } from '../../workspaces/metadata/run import { RuntimeWorktreeRemovalInFlight } from '../../workspaces/removal/runtime-worktree-removal-in-flight' import { ServeBrowserTabs } from '../../browser/headless/serve-browser-tabs' import { readBrowserTabBar } from '../../browser/tabs/browser-tab-listing' +import { readSavedBrowserPageAnnotations } from '../../browser/tabs/browser-tab-annotations' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' import type { ServeBrowserPageState } from '../../browser/headless/serve-browser-tab-layout' @@ -201,6 +202,8 @@ export abstract class OrcaRuntimeWithTerminalDrivers extends OrcaRuntimeWithFitO markHeadlessBrowserSessionTabActive: this.markHeadlessBrowserSessionTabActive.bind(this), notifyHeadlessBrowserSessionTabsChanged: (worktreeId) => this.notifyMobileSessionTabsChanged(worktreeId), + readBrowserPageAnnotations: (browserPageId) => + readSavedBrowserPageAnnotations(this.store, browserPageId), readBrowserTabBar: (worktreeId) => readBrowserTabBar(this.mobileSessionTabsByWorktree, worktreeId, (id) => { // Why: an SSH host's bridged workspace may have no row here, yet its pages render in this window. diff --git a/src/main/workspaces/catalog/imported-folder-project-link.ts b/src/main/workspaces/catalog/imported-folder-project-link.ts new file mode 100644 index 00000000000..022b9f06583 --- /dev/null +++ b/src/main/workspaces/catalog/imported-folder-project-link.ts @@ -0,0 +1,120 @@ +import { getRepoExecutionHostId } from '../../../shared/execution-host' +import { + assertImportedFolderRemoteMatchesProject, + resolveImportedFolderProjectLink +} from '../../../shared/imported-folder-project-identity' +import { + getProjectIdentityKey, + getProjectIdForProviderIdentity, + hasProjectRemoteIdentity +} from '../../../shared/project-host-setup-projection' +import type { ProjectHostSetupExistingFolderArgs } from '../../../shared/project-types' +import type { Repo } from '../../../shared/repo-types' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { assertWslMoveHostSetupWritable } from '../../persistence/moving-wsl-projects/wsl-move-scope-guard' +import { readCurrentGitRemoteIdentity } from './repo-git-remote-identity' + +export type RepositoryMetadataOwner = { + enqueueRepositoryMetadata: (repos: readonly Repo[]) => void + resolveRepositoryMetadata: (repo: Repo) => Promise +} + +export async function linkImportedFolderToProject( + getStore: () => RuntimeStore | null, + initialRepo: Repo, + folderRemote: Pick, + args: ProjectHostSetupExistingFolderArgs, + metadata: RepositoryMetadataOwner +): Promise { + const store = getStore() + if (!store) { + throw new Error('runtime_unavailable') + } + const currentRow = (): Repo => { + const repo = store + .getRepos() + .find( + (entry) => + entry.id === initialRepo.id && + getRepoExecutionHostId(entry) === getRepoExecutionHostId(initialRepo) + ) + if ( + getStore() !== store || + !repo || + repo.path !== initialRepo.path || + repo.kind !== initialRepo.kind + ) { + throw new Error(`Project setup repo disappeared before it could be linked: ${initialRepo.id}`) + } + assertWslMoveHostSetupWritable(store, { + projectId: args.projectId, + hostId: getRepoExecutionHostId(repo), + repoId: repo.id + }) + return repo + } + const project = store.getProjects?.().find((entry) => entry.id === args.projectId) + const provider = project?.providerIdentity ?? args.projectProviderIdentity + const selectedProvider = + provider && getProjectIdForProviderIdentity(provider) === args.projectId ? provider : undefined + let repo = currentRow() + // Legacy icon-only matches keep their existing acceptance without a new probe or stamp. + const legacyMatch = + getProjectIdentityKey(repo) === args.projectId && + repo.repoIcon?.type === 'image' && + repo.repoIcon.source === 'github' && + !hasProjectRemoteIdentity({ gitRemoteIdentity: folderRemote.gitRemoteIdentity }) + const needsEvidence = !!selectedProvider && repo.upstream === undefined && !legacyMatch + let metadataFinished = false + if (needsEvidence) { + metadataFinished = await metadata.resolveRepositoryMetadata(repo) + repo = currentRow() + folderRemote = await readCurrentGitRemoteIdentity({ ...repo, ...folderRemote }) + repo = currentRow() + } + const updates: Partial = { + projectHostSetupMethod: args.setupMethod ?? 'imported-existing-folder' + } + const keepsCurrentIdentity = + repo.upstream !== undefined && getProjectIdentityKey(repo) === args.projectId + if (needsEvidence && !keepsCurrentIdentity) { + updates.gitRemoteIdentity = folderRemote.gitRemoteIdentity + } + const candidate = { ...repo, ...updates } + const projectedId = getProjectIdentityKey(candidate) + if ( + projectedId === args.projectId && + needsEvidence && + repo.upstream === undefined && + selectedProvider + ) { + assertImportedFolderRemoteMatchesProject(folderRemote, selectedProvider) + } + if (projectedId !== args.projectId) { + Object.assign( + updates, + resolveImportedFolderProjectLink( + { ...candidate, ...folderRemote }, + args.projectId, + selectedProvider + ) + ) + } else if (needsEvidence && repo.upstream === undefined) { + // This successful explicit origin choice is terminal; ordinary failed probes stay unknown. + updates.upstream = null + } + if (getProjectIdentityKey({ ...repo, ...updates }) !== args.projectId) { + throw new Error('Imported folder does not match the selected project identity.') + } + const updated = store.updateRepo(repo, updates) + if (!updated) { + throw new Error(`Project setup repo disappeared before it could be linked: ${repo.id}`) + } + if (getProjectIdentityKey(updated) !== args.projectId) { + throw new Error('Imported folder does not match the selected project identity.') + } + if (!needsEvidence || !metadataFinished) { + metadata.enqueueRepositoryMetadata([updated]) + } + return updated +} diff --git a/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts b/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts index 3e6cee6b328..97457fb3d2c 100644 --- a/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts +++ b/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts @@ -26,7 +26,7 @@ vi.mock('electron', () => ({ })) vi.mock('./repo-git-remote-identity', () => ({ probeGitRemoteIdentity: vi.fn() })) vi.mock('../../github/client/fetch/repo-slug-upstream', () => ({ - getRepoUpstream: vi.fn(async () => ({ owner: 'acme', repo: 'app' })) + probeRepoUpstream: vi.fn(async () => ({ upstream: { owner: 'acme', repo: 'app' }, origin: null })) })) vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ detectGitHubAvatarIcon: vi.fn(async () => null) diff --git a/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts b/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts index bb26b30562e..70374e1457c 100644 --- a/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts +++ b/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts @@ -5,7 +5,7 @@ import type { BrowserAnnotationIntent, BrowserPageAnnotation } from '../../../../../shared/browser/element-grab/browser-grab-types' -import { formatBrowserAnnotationsAsMarkdown } from './browser-annotation-output' +import { formatBrowserAnnotationsAsMarkdown } from '../../../../../shared/browser/annotations/browser-annotation-output' import { EMPTY_BROWSER_ANNOTATIONS } from '../describe-page/browser-annotation-geometry' import { holdNotesForSend, diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts index 257250b024a..7f10e7912b4 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts @@ -12,9 +12,15 @@ vi.mock('@/lib/workspace/tabs/workspace-tab-commands', () => ({ import { handleGuestWindowCloseMessage } from './browser-page-window-close' import { BROWSER_GUEST_WINDOW_CLOSE_CHANNEL } from '../../../../../shared/browser-guest-window-close' -function seedTab(pageId: string, isPinned = false, siblingPageIds: string[] = []): void { +function seedTab( + pageId: string, + isPinned = false, + siblingPageIds: string[] = [], + browserAnnotationsByPageId: Record = {} +): void { storeState.value = { closeBrowserPage: closeBrowserPageMock, + browserAnnotationsByPageId, browserTabsByWorktree: { 'wt-1': [{ id: 'ws-1' }] }, browserPagesByWorkspace: { 'ws-1': [{ id: pageId }, ...siblingPageIds.map((id) => ({ id }))] }, unifiedTabsByWorktree: { @@ -40,6 +46,13 @@ describe('window.close() from a browser page', () => { expect(dispatchMock).not.toHaveBeenCalled() }) + it('never discards unsent notes', () => { + seedTab('page-n', false, [], { 'page-n': [{ id: 'note-1' }] }) + closeFrom('page-n', { back: false, forward: false }) + expect(dispatchMock).not.toHaveBeenCalled() + expect(closeBrowserPageMock).not.toHaveBeenCalled() + }) + it('closes only the calling page when its Orca tab holds other pages', () => { seedTab('page-e', false, ['page-sibling']) closeFrom('page-e', { back: false, forward: false }) diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts index 452f602c2b1..5b37f60164e 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts @@ -32,7 +32,8 @@ export function handleGuestWindowCloseMessage( const tab = (state.unifiedTabsByWorktree[owner.worktreeId] ?? []).find( (candidate) => candidate.contentType === 'browser' && candidate.entityId === owner.workspaceId ) - if (tab?.isPinned) { + // A script may not discard what the user pinned or left unsent; the page's notes are all it closes. + if (tab?.isPinned || (state.browserAnnotationsByPageId[pageId]?.length ?? 0) > 0) { return } pagesOpenedByPage.delete(pageId) diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx index 34290b57abf..e749f5645d1 100644 --- a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx +++ b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx @@ -158,17 +158,20 @@ async function render(visible = true) { ) } -it('labels same-repo sections by worktree name and a detached section by its HEAD', async () => { +it('identifies same-repo cards by name and shows their branch when collapsed', async () => { const [onBranch, detached] = setup(2) useAppStore.setState({ worktreesByRepo: { repo: [onBranch!, { ...detached!, branch: '', head: 'abc1234def' }] } }) await render() - expect( - [...container.querySelectorAll('section button[aria-expanded]')].map( - (toggle) => toggle.textContent - ) - ).toEqual(['ChildChild 0feature-0', 'ChildChild 1Detached HEAD · abc1234']) + const toggles = [ + ...container.querySelectorAll('section button[aria-expanded]') + ] + expect(toggles.map((toggle) => toggle.textContent)).toEqual(['ChildChild 0', 'ChildChild 1']) + expect([...container.querySelectorAll('section')].map((section) => section.textContent)).toEqual([ + 'ChildChild 0feature-0', + 'ChildChild 1Detached HEAD · abc1234' + ]) }) function ScopedStatusObserver({ owner }: { owner: SourceControlScope }) { diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx index b8424d28834..13cc391236b 100644 --- a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx +++ b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx @@ -26,6 +26,8 @@ import { SourceControlScopeProvider, type SourceControlScope } from './source-control/panel/worktree-scope' +import { SourceControlHeaderOverflowMenu } from './source-control/panel/header-overflow-menu' +import { SourceControlHeaderActionsSlot } from './source-control/panel/header-actions-slot' import { useWorktreeGitStatusObservation } from './source-control/sync/use-worktree-git-status-observation' import { useSourceControlWatchConsumer } from '@/hooks/source-control-watch-consumers' import { useSectionOnScreen } from './source-control/panel/section-viewport-presence' @@ -112,6 +114,7 @@ const WorktreeSection = memo( : null ) const panel = useMemo(() => , []) + const [actionsSlot, setActionsSlot] = useState(null) const identity = getWorktreeGitIdentityDisplay(owner.worktree) return (
+ ) : null + } onToggle={() => setExpanded(!isExpanded)} onOpen={() => useAppStore.getState().setActiveWorktree(id, owner.executionHostId)} + actionsSlotRef={setActionsSlot} /> {isExpanded && (!connected ? ( @@ -154,9 +164,11 @@ const WorktreeSection = memo( // A read error renders the body's existing failure banner with Retry. )} diff --git a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx index 9d82daa4d4a..d40e0025386 100644 --- a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx +++ b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx @@ -36,6 +36,7 @@ function Cards() { expanded onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} />
@@ -48,6 +49,7 @@ function Cards() { expanded onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} /> @@ -59,6 +61,7 @@ function Cards() { expanded={false} onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} /> @@ -82,6 +85,7 @@ export const narrow = defineFixture({ expanded={false} onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} /> diff --git a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx index 6df52b72b5d..66641f4b678 100644 --- a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx +++ b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx @@ -15,8 +15,31 @@ type FolderWorktreeSectionHeaderProps = { behind?: number changeCount: number expanded: boolean + showBranchInHeader?: boolean + actions?: React.ReactNode onToggle: () => void onOpen: () => void + /** Receives the embedded panel's filter and overflow buttons while expanded. */ + actionsSlotRef: (element: HTMLDivElement | null) => void +} + +function AheadBehind({ ahead, behind }: { ahead?: number; behind?: number }): React.JSX.Element { + return ( + <> + {!!ahead && ( + + + {ahead} + + )} + {!!behind && ( + + + {behind} + + )} + + ) } export function FolderWorktreeSectionHeader({ @@ -27,86 +50,101 @@ export function FolderWorktreeSectionHeader({ behind, changeCount, expanded, + showBranchInHeader = !expanded, + actions, onToggle, - onOpen + onOpen, + actionsSlotRef }: FolderWorktreeSectionHeaderProps): React.JSX.Element { const t = useTranslate() const openLabel = t( 'auto.components.rightSidebar.FolderWorkspaceSourceControl.openWorktree', 'Open this worktree' ) + const showWorktreeName = !!worktreeName && worktreeName !== branch + // Expanded cards show the branch once, in the body's picker; collapsed cards have no body. + const showSummaryRow = showBranchInHeader && (!!branch || !!ahead || !!behind || changeCount > 0) return ( // Pinned within its own card, above the panel's sticky COMMITS dock.
- + + + + + {openLabel} + + + {expanded && ( + + + + )} +
+ {actions} +
+
+ {showSummaryRow && ( + + {branch && ( + + + + {branch} + )} - - {(branch || !!ahead || !!behind) && ( - - {branch && ( - - - {branch} - - )} - {!!ahead && ( - - - {ahead} - - )} - {!!behind && ( - - - {behind} + + {!expanded && } + {!expanded && changeCount > 0 && ( + + {t( + 'auto.components.rightSidebar.FolderWorkspaceSourceControl.changeCount', + '{{count}} changes', + { count: changeCount, defaultValue_one: '{{count}} change' } + )} )} - )} - - - - - - {openLabel} - + + )}
) } diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx b/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx index e6b95041d57..00a38832642 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx @@ -3,6 +3,7 @@ import { ChevronDown } from 'lucide-react' import { cn } from '@/lib/class-names' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' +import { useSourceControlScope } from '../panel/worktree-scope' export function SectionHeader({ label, @@ -23,22 +24,27 @@ export function SectionHeader({ actions?: React.ReactNode }): React.JSX.Element { const t = useTranslate() + // Folder cards keep the gap above the first file equal to the one below the last. + const compact = useSourceControlScope() !== null // Share the rounded container so hover styling spans the whole row. return ( -
+
-
{actions}
+
+ {actions} +
) diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx b/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx index c80dea85b36..6c77ceaf81a 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx @@ -14,6 +14,7 @@ import { import { ActionButton } from './action-button' import { SectionHeader } from './section-header' import { SourceControlSectionFileList } from './section-file-list' +import { useSourceControlScope } from '../panel/worktree-scope' import { getSourceControlSectionViewAction, type SourceControlDisplaySection, @@ -89,6 +90,7 @@ export function SourceControlUncommittedSections(props: { requestDiscardEntry: (entry: GitStatusEntry) => void diffCommentCountByPath: Map }): React.JSX.Element { + const embedded = useSourceControlScope() !== null const t = useTranslate() return ( <> @@ -176,35 +178,37 @@ export function SourceControlUncommittedSections(props: { } /> {!isCollapsed && ( - +
+ +
)}
) diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts b/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts index 9888f31b182..9cc0b17c0d0 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts +++ b/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts @@ -190,7 +190,8 @@ export function useSourceControlSelection({ return } - const container = containerRef.current + const panel = containerRef.current + const container = panel?.closest('[data-source-control-worktree]') ?? panel const target = e.target if (!container || !(target instanceof Node) || container.contains(target)) { return diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx b/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx index af4712d35a9..940a009f98c 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx @@ -103,6 +103,7 @@ export function SourceControlBranchContextRow({ headControl, manualReviewUrl, branchLineTotal, + reviewControl, onChangeBaseRef, onRetry }: { @@ -112,6 +113,7 @@ export function SourceControlBranchContextRow({ headControl?: React.ReactNode manualReviewUrl?: string | null branchLineTotal?: GitBranchLineTotal | null + reviewControl?: React.ReactNode onChangeBaseRef: () => void onRetry: () => void }): React.JSX.Element | null { @@ -124,8 +126,11 @@ export function SourceControlBranchContextRow({ return null } return ( -
- {headControl ?? } +
+ + {headControl ?? } + + {reviewControl}
) } @@ -159,7 +164,12 @@ export function SourceControlBranchContextRow({ onChangeBaseRef={onChangeBaseRef} changeBaseTitle={changeBaseTitle} leading={