mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
Merge remote-tracking branch 'origin/main' into brennanb2025/github-issue-link-title
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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`)
|
||||
|
||||
@@ -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', () => ({
|
||||
|
||||
@@ -71,6 +71,7 @@ Browser rules:
|
||||
- Pass `--page <browserPageId>` on every command that acts on one page; `ORCA <command> --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 <browserPageId>` (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-<n>` page with `openerBrowserPageId`. If a click seems to do nothing, check `tab list`, then drive the popup with `--page popup-<n>`. 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 <selector>`. 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.
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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<string, CommandHandler> = {
|
||||
const result = await client.call<BrowserTabShowResult>('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<BrowserTabAnnotationsResult>('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<BrowserTabCurrentResult>('browser.tabCurrent', { worktree })
|
||||
|
||||
@@ -740,6 +740,7 @@ const ORCA_CLI_BROWSER_REFERENCE_MARKDOWN = [
|
||||
"- Pass `--page <browserPageId>` on every command that acts on one page; `ORCA <command> --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 <browserPageId>` (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-<n>` page with `openerBrowserPageId`. If a click seems to do nothing, check `tab list`, then drive the popup with `--page popup-<n>`. 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 <selector>`. 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.",
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -206,6 +206,12 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = withBrowserPageTarget(
|
||||
usage: 'orca tab show --page <id> [--worktree <selector>] [--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 <id>] [--worktree <selector>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'page', 'worktree']
|
||||
},
|
||||
{
|
||||
path: ['tab', 'current'],
|
||||
summary: 'Show the current browser tab',
|
||||
|
||||
@@ -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 === ''
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<GhExecutableAbsenceBatch>()
|
||||
const batches = new Set<GhExecutableAbsenceBatch>()
|
||||
|
||||
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<string, unknown>()
|
||||
|
||||
constructor() {
|
||||
batches.add(this)
|
||||
}
|
||||
|
||||
run<T>(operation: () => Promise<T>): Promise<T> {
|
||||
return currentBatch.run(this, operation)
|
||||
}
|
||||
|
||||
close(): void {
|
||||
batches.delete(this)
|
||||
this.missing.clear()
|
||||
}
|
||||
|
||||
static assertAvailable(command: ResolvedCommand, env: NodeJS.ProcessEnv): Promise<void> | 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<void> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<RepoUpstreamProbe> {
|
||||
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<OwnerRepo | null> {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<string, Record<string, string>> = {
|
||||
[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 })
|
||||
})
|
||||
|
||||
@@ -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
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
+12
-4
@@ -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<typeof runtime.repositoryForkBackfill.enqueue>[0]
|
||||
) => void runtime.repositoryForkBackfill.enqueue(repos),
|
||||
resolveRepositoryMetadata: (
|
||||
repo: Parameters<typeof runtime.repositoryForkBackfill.resolve>[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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<ProjectGroupImportResult> => {
|
||||
@@ -65,6 +70,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store
|
||||
const importedProjectIdsByRepoPath = new Map<string, string>()
|
||||
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
|
||||
|
||||
@@ -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<Repo, 'gitRemoteIdentity'>,
|
||||
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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<string, number>()
|
||||
const pendingAbortCleanupByPath = new Map<string, Promise<void>>()
|
||||
|
||||
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<void> {
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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' ||
|
||||
|
||||
@@ -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<RuntimeBrowserCommands['browserTabAnnotations']>) => {
|
||||
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[]) => {
|
||||
|
||||
@@ -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<RepoIcon | undefined> {
|
||||
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<RepoIcon | undefined> {
|
||||
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 } : {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<RuntimeStore, 'getWorkspaceSession' | 'getWorkspaceSessionHostIds'>
|
||||
| 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))
|
||||
}
|
||||
}
|
||||
@@ -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<BrowserTabAnnotationsResult> {
|
||||
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<BrowserTabCurrentResult> {
|
||||
const tab = (await this.browserTabList(params)).tabs.find((candidate) => candidate.active)
|
||||
if (!tab) {
|
||||
|
||||
@@ -47,6 +47,7 @@ const BROWSER_COMMAND_NAMES = [
|
||||
'browserProceedCertificate',
|
||||
'browserTabShow',
|
||||
'browserTabCurrent',
|
||||
'browserTabAnnotations',
|
||||
'browserTabSwitch',
|
||||
'browserHover',
|
||||
'browserDrag',
|
||||
|
||||
@@ -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()
|
||||
)
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<forkMetadata.RepoUpstreamProbe>()
|
||||
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<forkMetadata.RepoUpstreamProbe>()
|
||||
const started = Promise.withResolvers<void>()
|
||||
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<forkMetadata.RepoUpstreamProbe>()
|
||||
const started = Promise.withResolvers<void>()
|
||||
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<forkMetadata.RepoUpstreamProbe>()
|
||||
const ordinaryStarted = Promise.withResolvers<void>()
|
||||
const ordinaryFinished = Promise.withResolvers<void>()
|
||||
const required = Promise.withResolvers<forkMetadata.RepoUpstreamProbe>()
|
||||
const requiredStarted = Promise.withResolvers<void>()
|
||||
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<forkMetadata.RepoUpstreamProbe>()
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<Record<string, unknown>>()),
|
||||
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<void> } }
|
||||
|
||||
function makeRepo(overrides: Partial<Repo> = {}): 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> = {}): 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<Repo, 'id'>, updates: Partial<Repo>) => {
|
||||
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<void>((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<RepoUpstreamProbe>()
|
||||
const started = Promise.withResolvers<void>()
|
||||
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<RepoUpstreamProbe>()
|
||||
const started = Promise.withResolvers<void>()
|
||||
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<RepoUpstreamProbe>()
|
||||
const later = Promise.withResolvers<RepoUpstreamProbe>()
|
||||
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<RepoUpstreamProbe>()
|
||||
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<string, ReturnType<typeof Promise.withResolvers<RepoUpstreamProbe>>>()
|
||||
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<RepoUpstreamProbe>()
|
||||
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<RepoUpstreamProbe>()
|
||||
const started = Promise.withResolvers<void>()
|
||||
probe
|
||||
.mockImplementationOnce(() => {
|
||||
started.resolve()
|
||||
return gate.promise
|
||||
})
|
||||
.mockResolvedValue({ upstream: parent, origin })
|
||||
const protectedIcons = new Set<unknown>(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)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
@@ -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<Record<string, unknown>>()),
|
||||
spawn: spawnMock
|
||||
}))
|
||||
vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
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 })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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<Repo>
|
||||
@@ -260,14 +263,16 @@ export class RuntimeProjectHostSetupController {
|
||||
}
|
||||
}
|
||||
|
||||
private completeSetup(
|
||||
private async completeSetup(
|
||||
args: ProjectHostSetupExistingFolderArgs,
|
||||
initialRepo: Repo,
|
||||
repoWasCreated: boolean,
|
||||
folderRemote: Pick<Repo, 'gitRemoteIdentity'>
|
||||
): ProjectHostSetupResult {
|
||||
): Promise<ProjectHostSetupResult> {
|
||||
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<Repo, 'gitRemoteIdentity'>
|
||||
): 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<ProjectHostSetupResult> {
|
||||
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}`)
|
||||
|
||||
@@ -26,6 +26,7 @@ async function clonedRepo(remoteUrl: string): Promise<Repo> {
|
||||
function makeController(cloned: Repo) {
|
||||
const repos: Repo[] = []
|
||||
const store = {
|
||||
getRepos: () => repos,
|
||||
getProjects: () => projectHostSetupProjectionFromRepos(repos).projects,
|
||||
getProjectHostSetups: () => projectHostSetupProjectionFromRepos(repos).setups,
|
||||
updateRepo: ({ id }: Pick<Repo, 'id'>, updates: Partial<Repo>) => {
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<typeof registrations.add>) => {
|
||||
const repo = await registrations.add(...args)
|
||||
void target.repositoryForkBackfill.enqueue([repo])
|
||||
return repo
|
||||
},
|
||||
createRepo: async (...args: Parameters<typeof registrations.create>) => {
|
||||
const result = await registrations.create(...args)
|
||||
if ('repo' in result) {
|
||||
void target.repositoryForkBackfill.enqueue([result.repo])
|
||||
}
|
||||
return result
|
||||
},
|
||||
cloneRepo: async (...args: Parameters<typeof clones.clone>) => {
|
||||
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),
|
||||
|
||||
@@ -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<boolean>
|
||||
finish: (changed: boolean) => void
|
||||
}
|
||||
|
||||
export class RuntimeRepositoryForkBackfill {
|
||||
private started = false
|
||||
private active = 0
|
||||
private backgroundActive = 0
|
||||
private readonly jobs = new Map<RuntimeStore, Map<string, MetadataJob>>()
|
||||
private readonly requiredQueue = new Set<MetadataJob>()
|
||||
private readonly backgroundQueue = new Set<MetadataJob>()
|
||||
|
||||
constructor(
|
||||
private readonly getStore: () => RuntimeStore | null,
|
||||
@@ -27,64 +39,204 @@ export class RuntimeRepositoryForkBackfill {
|
||||
void this.run()
|
||||
}
|
||||
|
||||
async run(): Promise<void> {
|
||||
run(): Promise<void> {
|
||||
return this.enqueue(
|
||||
(this.getStore()?.getRepos() ?? []).filter((repo) => repo.upstream === undefined)
|
||||
)
|
||||
}
|
||||
|
||||
async enqueue(repos: readonly Repo[]): Promise<void> {
|
||||
const batch: Promise<boolean>[] = []
|
||||
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<Repo> = { 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<boolean> {
|
||||
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<boolean>((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<void> {
|
||||
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<boolean> {
|
||||
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<Repo> = {}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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 => {}
|
||||
|
||||
@@ -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<BundledMobileWebBundle | null> {
|
||||
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:`, {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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(() => {})
|
||||
|
||||
@@ -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(() => {})
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -50,8 +50,8 @@ function bundleError(code: MobileWebBundleErrorCode): InvalidArgumentError {
|
||||
return new InvalidArgumentError(code)
|
||||
}
|
||||
|
||||
function requireBundle(): BundledMobileWebBundle {
|
||||
const bundle = loadBundledMobileWebBundle()
|
||||
async function requireBundle(): Promise<BundledMobileWebBundle> {
|
||||
const bundle = await loadBundledMobileWebBundle()
|
||||
if (!bundle) {
|
||||
throw bundleError('mobile_web_bundle_unavailable')
|
||||
}
|
||||
@@ -69,7 +69,7 @@ async function readLocaleCatalog(
|
||||
params: MobileWebBundleLocaleCatalogParams,
|
||||
ctx: RpcContext
|
||||
): Promise<MobileWebBundleLocaleCatalogResult> {
|
||||
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<T>(
|
||||
encode: (window: VerifiedWindow) => Promise<T>,
|
||||
sourceOf: (asset: MobileWebBundleAsset) => WindowSource = (asset) => asset
|
||||
): Promise<T> {
|
||||
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<MobileWebBundleManifestResult> => ({
|
||||
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
|
||||
|
||||
@@ -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<void> } = 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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<boolean>
|
||||
}
|
||||
|
||||
export async function linkImportedFolderToProject(
|
||||
getStore: () => RuntimeStore | null,
|
||||
initialRepo: Repo,
|
||||
folderRemote: Pick<Repo, 'gitRemoteIdentity'>,
|
||||
args: ProjectHostSetupExistingFolderArgs,
|
||||
metadata: RepositoryMetadataOwner
|
||||
): Promise<Repo> {
|
||||
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<Repo> = {
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
+1
-1
@@ -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,
|
||||
|
||||
+14
-1
@@ -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<string, unknown[]> = {}
|
||||
): 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 })
|
||||
|
||||
@@ -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)
|
||||
|
||||
+9
-6
@@ -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<HTMLButtonElement>('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 }) {
|
||||
|
||||
@@ -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(() => <SourceControlPanel />, [])
|
||||
const [actionsSlot, setActionsSlot] = useState<HTMLDivElement | null>(null)
|
||||
const identity = getWorktreeGitIdentityDisplay(owner.worktree)
|
||||
return (
|
||||
<section
|
||||
@@ -131,8 +134,15 @@ const WorktreeSection = memo(
|
||||
behind={remote?.behind}
|
||||
changeCount={entries.length}
|
||||
expanded={isExpanded}
|
||||
showBranchInHeader={!bodyShown || !bodyMounted || isFolderRepo(owner.repo)}
|
||||
actions={
|
||||
isExpanded && (!bodyShown || !bodyMounted || isFolderRepo(owner.repo)) ? (
|
||||
<SourceControlHeaderOverflowMenu worktree={owner.worktree} />
|
||||
) : 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.
|
||||
<div hidden={!bodyShown}>
|
||||
<OverlayActivityOwner.Provider value={onOverlayActivity}>
|
||||
<SourceControlScopeProvider owner={owner} active={bodyActive}>
|
||||
{panel}
|
||||
</SourceControlScopeProvider>
|
||||
<SourceControlHeaderActionsSlot.Provider value={bodyShown ? actionsSlot : null}>
|
||||
<SourceControlScopeProvider owner={owner} active={bodyActive}>
|
||||
{panel}
|
||||
</SourceControlScopeProvider>
|
||||
</SourceControlHeaderActionsSlot.Provider>
|
||||
</OverlayActivityOwner.Provider>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -36,6 +36,7 @@ function Cards() {
|
||||
expanded
|
||||
onToggle={() => {}}
|
||||
onOpen={() => {}}
|
||||
actionsSlotRef={() => {}}
|
||||
/>
|
||||
<SectionBody files={['src/main/index.ts', 'src/renderer/App.tsx', 'README.md']} />
|
||||
</section>
|
||||
@@ -48,6 +49,7 @@ function Cards() {
|
||||
expanded
|
||||
onToggle={() => {}}
|
||||
onOpen={() => {}}
|
||||
actionsSlotRef={() => {}}
|
||||
/>
|
||||
<SectionBody files={['package.json']} />
|
||||
</section>
|
||||
@@ -59,6 +61,7 @@ function Cards() {
|
||||
expanded={false}
|
||||
onToggle={() => {}}
|
||||
onOpen={() => {}}
|
||||
actionsSlotRef={() => {}}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
@@ -82,6 +85,7 @@ export const narrow = defineFixture({
|
||||
expanded={false}
|
||||
onToggle={() => {}}
|
||||
onOpen={() => {}}
|
||||
actionsSlotRef={() => {}}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -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 && (
|
||||
<span className="flex shrink-0 items-center tabular-nums">
|
||||
<ArrowUp className="size-3" />
|
||||
{ahead}
|
||||
</span>
|
||||
)}
|
||||
{!!behind && (
|
||||
<span className="flex shrink-0 items-center tabular-nums">
|
||||
<ArrowDown className="size-3" />
|
||||
{behind}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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.
|
||||
<div
|
||||
className={`sticky top-0 z-20 flex items-center gap-1 bg-card pr-1 ${expanded ? 'border-b border-input' : ''}`}
|
||||
className={`group/card-header sticky top-0 z-20 flex flex-col gap-0.5 bg-card py-1.5 pl-2 pr-1 text-xs hover:bg-accent ${expanded ? 'border-b border-input' : ''}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
onClick={onToggle}
|
||||
className="flex min-w-0 flex-1 flex-col gap-0.5 py-1.5 pl-2 text-left text-xs hover:bg-accent focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
|
||||
>
|
||||
<span className="flex w-full min-w-0 items-center gap-1.5">
|
||||
<span className="flex min-h-5 w-full min-w-0 items-center gap-1.5">
|
||||
{/* Its ::after covers the header so any empty space toggles; the other controls sit above it. */}
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
aria-label={[repoName, showWorktreeName ? worktreeName : null, branch]
|
||||
.filter(Boolean)
|
||||
.join(', ')}
|
||||
onClick={onToggle}
|
||||
className="flex min-w-0 items-center gap-1.5 text-left after:absolute after:inset-0 focus-visible:outline-none focus-visible:after:ring-1 focus-visible:after:ring-inset focus-visible:after:ring-ring"
|
||||
>
|
||||
<ChevronRight
|
||||
className={`size-3 shrink-0 text-muted-foreground ${expanded ? 'rotate-90' : ''}`}
|
||||
/>
|
||||
<FolderGit2 className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 truncate text-[13px] font-semibold">{repoName}</span>
|
||||
<span className="min-w-0 truncate text-[13px] font-semibold" title={repoName}>
|
||||
{repoName}
|
||||
</span>
|
||||
{/* Same-repo worktrees are told apart by name, as main did. */}
|
||||
{worktreeName && worktreeName !== branch && (
|
||||
<span
|
||||
title={worktreeName}
|
||||
className="min-w-0 flex-1 basis-0 truncate text-muted-foreground"
|
||||
>
|
||||
{showWorktreeName && (
|
||||
<span className="min-w-0 truncate text-muted-foreground" title={worktreeName}>
|
||||
{worktreeName}
|
||||
</span>
|
||||
)}
|
||||
{changeCount > 0 && (
|
||||
<span className="ml-auto shrink-0 rounded-full bg-muted px-1.5 text-2xs text-foreground">
|
||||
{changeCount}
|
||||
</button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative z-10 -my-0.5 size-5 shrink-0"
|
||||
onClick={onOpen}
|
||||
aria-label={openLabel}
|
||||
>
|
||||
<ArrowUpRight className="size-3.5 text-muted-foreground group-hover/card-header:text-foreground" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{openLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
<span className="min-w-0 flex-1" />
|
||||
{expanded && (
|
||||
<span className="flex shrink-0 items-center gap-1 text-muted-foreground">
|
||||
<AheadBehind ahead={ahead} behind={behind} />
|
||||
</span>
|
||||
)}
|
||||
<div
|
||||
ref={actionsSlotRef}
|
||||
className="relative z-10 -my-1 flex shrink-0 items-center empty:hidden"
|
||||
>
|
||||
{actions}
|
||||
</div>
|
||||
</span>
|
||||
{showSummaryRow && (
|
||||
<span className="flex w-full min-w-0 items-center gap-1 pl-[2.375rem] pr-1 text-muted-foreground">
|
||||
{branch && (
|
||||
<span className="flex min-w-0 items-center gap-1 rounded-full border border-input px-1.5">
|
||||
<GitBranch className="size-3 shrink-0" />
|
||||
<span className="truncate" title={branch}>
|
||||
{branch}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{(branch || !!ahead || !!behind) && (
|
||||
<span className="flex w-full min-w-0 items-center gap-1 pl-[1.625rem] text-muted-foreground">
|
||||
{branch && (
|
||||
<span
|
||||
title={branch}
|
||||
className="flex min-w-0 items-center gap-1 rounded-full border border-input px-1.5"
|
||||
>
|
||||
<GitBranch className="size-3 shrink-0" />
|
||||
<span className="truncate">{branch}</span>
|
||||
</span>
|
||||
)}
|
||||
{!!ahead && (
|
||||
<span className="ml-auto flex shrink-0 items-center">
|
||||
<ArrowUp className="size-3" />
|
||||
{ahead}
|
||||
</span>
|
||||
)}
|
||||
{!!behind && (
|
||||
<span className={`flex shrink-0 items-center ${ahead ? '' : 'ml-auto'}`}>
|
||||
<ArrowDown className="size-3" />
|
||||
{behind}
|
||||
<span className="ml-auto flex shrink-0 items-center gap-1">
|
||||
{!expanded && <AheadBehind ahead={ahead} behind={behind} />}
|
||||
{!expanded && changeCount > 0 && (
|
||||
<span className="text-2xs tabular-nums">
|
||||
{t(
|
||||
'auto.components.rightSidebar.FolderWorkspaceSourceControl.changeCount',
|
||||
'{{count}} changes',
|
||||
{ count: changeCount, defaultValue_one: '{{count}} change' }
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 shrink-0"
|
||||
onClick={onOpen}
|
||||
aria-label={openLabel}
|
||||
>
|
||||
<ArrowUpRight className="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{openLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+13
-5
@@ -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 (
|
||||
<div className="pl-1 pr-3 pt-3 pb-1">
|
||||
<div className={cn('pl-1 pr-3 pt-3', compact ? 'pb-0' : 'pb-1')}>
|
||||
<div className="group/section flex items-center gap-x-1 rounded-md pr-1 hover:bg-accent hover:text-accent-foreground">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
className="h-auto min-h-6 min-w-0 flex-1 justify-start gap-x-1 gap-y-0 py-0.5 text-left font-semibold uppercase tracking-wider text-foreground/70 group-hover/section:text-accent-foreground"
|
||||
size={compact ? 'chip' : 'xs'}
|
||||
className={cn(
|
||||
'h-auto min-w-0 flex-1 justify-start text-left',
|
||||
compact ? 'min-h-4' : 'min-h-6'
|
||||
)}
|
||||
onClick={onToggle}
|
||||
aria-expanded={!isCollapsed}
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn('size-3.5 shrink-0 transition-transform', isCollapsed && '-rotate-90')}
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="min-w-0 flex-1 text-xs font-semibold uppercase tracking-wider text-foreground/70 group-hover/section:text-accent-foreground">
|
||||
<span className="flex min-w-0 items-center gap-1">
|
||||
<span className="min-w-0 truncate" title={label}>
|
||||
{label}
|
||||
@@ -59,7 +65,9 @@ export function SectionHeader({
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
<div className="ml-auto flex shrink-0 items-center justify-end">{actions}</div>
|
||||
<div className={cn('ml-auto flex shrink-0 items-center justify-end', compact && '-my-1')}>
|
||||
{actions}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
+33
-29
@@ -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<string, number>
|
||||
}): React.JSX.Element {
|
||||
const embedded = useSourceControlScope() !== null
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<>
|
||||
@@ -176,35 +178,37 @@ export function SourceControlUncommittedSections(props: {
|
||||
}
|
||||
/>
|
||||
{!isCollapsed && (
|
||||
<SourceControlSectionFileList
|
||||
treeRows={props.visibleTreeRowsBySection[id] ?? []}
|
||||
listRows={props.visibleListRowsBySection[id] ?? []}
|
||||
sourceControlViewMode={props.sourceControlViewMode}
|
||||
fileListScrollElement={props.fileListScrollElement}
|
||||
normalizedFilter={props.normalizedFilter}
|
||||
isExecutingBulk={props.isExecutingBulk}
|
||||
collapsedTreeDirs={props.collapsedTreeDirs}
|
||||
toggleTreeDir={props.toggleTreeDir}
|
||||
requestDiscardPaths={props.requestDiscardPaths}
|
||||
handleStageAllPaths={props.handleStageAllPaths}
|
||||
handleUnstagePaths={props.handleUnstagePaths}
|
||||
expandedSubmoduleKeys={props.expandedSubmoduleKeys}
|
||||
toggleSubmodule={props.toggleSubmodule}
|
||||
currentWorktreeId={props.currentWorktreeId}
|
||||
worktreePath={props.worktreePath}
|
||||
selectedKeySet={props.selectedKeySet}
|
||||
activeOpenRowKeys={props.activeOpenRowKeys}
|
||||
handleSelect={props.handleSelect}
|
||||
handleContextMenu={props.handleContextMenu}
|
||||
revealInExplorer={props.revealInExplorer}
|
||||
activeConnectionId={props.activeConnectionId}
|
||||
handleOpenDiff={props.handleOpenDiff}
|
||||
handleStage={props.handleStage}
|
||||
handleResolveConflict={props.handleResolveConflict}
|
||||
handleUnstage={props.handleUnstage}
|
||||
requestDiscardEntry={props.requestDiscardEntry}
|
||||
diffCommentCountByPath={props.diffCommentCountByPath}
|
||||
/>
|
||||
<div className={embedded ? 'py-px' : undefined}>
|
||||
<SourceControlSectionFileList
|
||||
treeRows={props.visibleTreeRowsBySection[id] ?? []}
|
||||
listRows={props.visibleListRowsBySection[id] ?? []}
|
||||
sourceControlViewMode={props.sourceControlViewMode}
|
||||
fileListScrollElement={props.fileListScrollElement}
|
||||
normalizedFilter={props.normalizedFilter}
|
||||
isExecutingBulk={props.isExecutingBulk}
|
||||
collapsedTreeDirs={props.collapsedTreeDirs}
|
||||
toggleTreeDir={props.toggleTreeDir}
|
||||
requestDiscardPaths={props.requestDiscardPaths}
|
||||
handleStageAllPaths={props.handleStageAllPaths}
|
||||
handleUnstagePaths={props.handleUnstagePaths}
|
||||
expandedSubmoduleKeys={props.expandedSubmoduleKeys}
|
||||
toggleSubmodule={props.toggleSubmodule}
|
||||
currentWorktreeId={props.currentWorktreeId}
|
||||
worktreePath={props.worktreePath}
|
||||
selectedKeySet={props.selectedKeySet}
|
||||
activeOpenRowKeys={props.activeOpenRowKeys}
|
||||
handleSelect={props.handleSelect}
|
||||
handleContextMenu={props.handleContextMenu}
|
||||
revealInExplorer={props.revealInExplorer}
|
||||
activeConnectionId={props.activeConnectionId}
|
||||
handleOpenDiff={props.handleOpenDiff}
|
||||
handleStage={props.handleStage}
|
||||
handleResolveConflict={props.handleResolveConflict}
|
||||
handleUnstage={props.handleUnstage}
|
||||
requestDiscardEntry={props.requestDiscardEntry}
|
||||
diffCommentCountByPath={props.diffCommentCountByPath}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
+15
-3
@@ -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 (
|
||||
<div className="min-w-0 text-[11px] text-muted-foreground">
|
||||
{headControl ?? <HeadIdentity display={headDisplay} />}
|
||||
<div className="flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||
<span className="min-w-0 flex-1">
|
||||
{headControl ?? <HeadIdentity display={headDisplay} />}
|
||||
</span>
|
||||
{reviewControl}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -159,7 +164,12 @@ export function SourceControlBranchContextRow({
|
||||
onChangeBaseRef={onChangeBaseRef}
|
||||
changeBaseTitle={changeBaseTitle}
|
||||
leading={<Loader2 className="size-3 shrink-0 animate-spin" aria-hidden="true" />}
|
||||
trailing={<ManualReviewLinkButton url={manualReviewUrl} />}
|
||||
trailing={
|
||||
<>
|
||||
<ManualReviewLinkButton url={manualReviewUrl} />
|
||||
{reviewControl}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<span className="sr-only">
|
||||
{t('auto.components.right.sidebar.SourceControl.11b5dd8e41', 'Comparing against')}
|
||||
@@ -189,6 +199,7 @@ export function SourceControlBranchContextRow({
|
||||
label={t('auto.components.right.sidebar.SourceControl.286dbda4d6', 'Retry')}
|
||||
onClick={onRetry}
|
||||
/>
|
||||
{reviewControl}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
@@ -224,6 +235,7 @@ export function SourceControlBranchContextRow({
|
||||
<>
|
||||
{compareStatNodes}
|
||||
<ManualReviewLinkButton url={manualReviewUrl} />
|
||||
{reviewControl}
|
||||
</>
|
||||
}
|
||||
headTrailing={<SourceControlBranchLineTotalChip branchLineTotal={branchLineTotal} />}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
|
||||
// A folder card's header hosts its panel's filter and overflow buttons; null while the card is collapsed.
|
||||
export const SourceControlHeaderActionsSlot = createContext<HTMLElement | null>(null)
|
||||
|
||||
export function useSourceControlHeaderActionsSlot(): HTMLElement | null {
|
||||
return useContext(SourceControlHeaderActionsSlot)
|
||||
}
|
||||
+78
-38
@@ -1,5 +1,14 @@
|
||||
import React from 'react'
|
||||
import { List, ListTree, MessageSquare, MoreHorizontal, RefreshCw, Settings2 } from 'lucide-react'
|
||||
import {
|
||||
List,
|
||||
ListTree,
|
||||
MessageSquare,
|
||||
MoreHorizontal,
|
||||
RefreshCw,
|
||||
Settings2,
|
||||
Unlink
|
||||
} from 'lucide-react'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
import type { SourceControlViewMode } from '../../../../../../shared/ui-chrome-types'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
@@ -11,17 +20,11 @@ import {
|
||||
DropdownMenuTrigger
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { useAppStore } from '@/store'
|
||||
import { unnestWorktrees } from '../../../sidebar/workspace-actions/parenting/worktree-unnest'
|
||||
import { useSourceControlScopeOwner } from './worktree-scope'
|
||||
|
||||
export function SourceControlHeaderOverflowMenu({
|
||||
sourceControlViewMode,
|
||||
viewModeToggleDisabled,
|
||||
onToggleViewMode,
|
||||
onChangeBaseRef,
|
||||
onRefreshBranchCompare,
|
||||
branchCompareRefreshDisabled,
|
||||
diffCommentCount,
|
||||
onExpandNotes
|
||||
}: {
|
||||
type PanelActions = {
|
||||
sourceControlViewMode: SourceControlViewMode
|
||||
viewModeToggleDisabled: boolean
|
||||
onToggleViewMode: () => void
|
||||
@@ -30,10 +33,20 @@ export function SourceControlHeaderOverflowMenu({
|
||||
branchCompareRefreshDisabled: boolean
|
||||
diffCommentCount: number
|
||||
onExpandNotes: () => void
|
||||
}
|
||||
|
||||
export function SourceControlHeaderOverflowMenu({
|
||||
panelActions,
|
||||
worktree
|
||||
}: {
|
||||
panelActions?: PanelActions
|
||||
worktree?: Worktree
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const scopeOwner = useSourceControlScopeOwner()
|
||||
const ownerWorktree = worktree ?? scopeOwner?.worktree
|
||||
const viewModeLabel =
|
||||
sourceControlViewMode === 'tree'
|
||||
panelActions?.sourceControlViewMode === 'tree'
|
||||
? t('auto.components.right.sidebar.SourceControl.a91f8e2b01', 'View as list')
|
||||
: t('auto.components.right.sidebar.SourceControl.b82e9f3c12', 'View as tree')
|
||||
|
||||
@@ -46,13 +59,13 @@ export function SourceControlHeaderOverflowMenu({
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="size-7 text-muted-foreground hover:text-foreground"
|
||||
className={ownerWorktree ? 'size-6' : 'size-7'}
|
||||
aria-label={t(
|
||||
'auto.components.right.sidebar.SourceControl.f71c4a8d90',
|
||||
'More source control actions'
|
||||
)}
|
||||
>
|
||||
<MoreHorizontal className="size-3.5" />
|
||||
<MoreHorizontal className="size-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
</TooltipTrigger>
|
||||
@@ -64,31 +77,58 @@ export function SourceControlHeaderOverflowMenu({
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<DropdownMenuContent align="end" className="min-w-[180px]">
|
||||
<DropdownMenuItem disabled={viewModeToggleDisabled} onSelect={onToggleViewMode}>
|
||||
{sourceControlViewMode === 'tree' ? (
|
||||
<List className="size-3.5" />
|
||||
) : (
|
||||
<ListTree className="size-3.5" />
|
||||
)}
|
||||
{viewModeLabel}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={onChangeBaseRef}>
|
||||
<Settings2 className="size-3.5" />
|
||||
{t('auto.components.right.sidebar.SourceControl.476b77745b', 'Change Base Ref')}…
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem disabled={branchCompareRefreshDisabled} onSelect={onRefreshBranchCompare}>
|
||||
<RefreshCw className="size-3.5" />
|
||||
{t('auto.components.right.sidebar.SourceControl.ed34038d0d', 'Refresh branch compare')}
|
||||
</DropdownMenuItem>
|
||||
{diffCommentCount > 0 ? (
|
||||
{panelActions ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={onExpandNotes}>
|
||||
<MessageSquare className="size-3.5" />
|
||||
{t('auto.components.right.sidebar.SourceControl.cc474e0b8c', 'Notes')}
|
||||
<span className="ml-auto text-[11px] tabular-nums text-muted-foreground">
|
||||
{diffCommentCount}
|
||||
</span>
|
||||
<DropdownMenuItem
|
||||
disabled={panelActions.viewModeToggleDisabled}
|
||||
onSelect={panelActions.onToggleViewMode}
|
||||
>
|
||||
{panelActions.sourceControlViewMode === 'tree' ? (
|
||||
<List className="size-3.5" />
|
||||
) : (
|
||||
<ListTree className="size-3.5" />
|
||||
)}
|
||||
{viewModeLabel}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={panelActions.onChangeBaseRef}>
|
||||
<Settings2 className="size-3.5" />
|
||||
{t('auto.components.right.sidebar.SourceControl.476b77745b', 'Change Base Ref')}…
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
disabled={panelActions.branchCompareRefreshDisabled}
|
||||
onSelect={panelActions.onRefreshBranchCompare}
|
||||
>
|
||||
<RefreshCw className="size-3.5" />
|
||||
{t(
|
||||
'auto.components.right.sidebar.SourceControl.ed34038d0d',
|
||||
'Refresh branch compare'
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
{panelActions.diffCommentCount > 0 ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={panelActions.onExpandNotes}>
|
||||
<MessageSquare className="size-3.5" />
|
||||
{t('auto.components.right.sidebar.SourceControl.cc474e0b8c', 'Notes')}
|
||||
<span className="ml-auto text-[11px] tabular-nums text-muted-foreground">
|
||||
{panelActions.diffCommentCount}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{ownerWorktree ? (
|
||||
<>
|
||||
{panelActions ? <DropdownMenuSeparator /> : null}
|
||||
{/* Same unlink as the sidebar's Parent & Children menu; the worktree itself stays. */}
|
||||
<DropdownMenuItem
|
||||
onSelect={() =>
|
||||
void unnestWorktrees([ownerWorktree], useAppStore.getState().updateWorktreeLineage)
|
||||
}
|
||||
>
|
||||
<Unlink className="size-3.5" />
|
||||
{t('auto.components.sidebar.WorktreeContextMenu.579b1a8e61', 'Remove from Parent')}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
+143
-97
@@ -1,5 +1,6 @@
|
||||
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
|
||||
import React, { useCallback, useEffect, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Search, X } from 'lucide-react'
|
||||
import type { GitBranchCompareSummary } from '../../../../../../shared/git/diff/git-diff-compare-types'
|
||||
import type { GitBranchLineTotal } from '../../../../../../shared/git/status/git-status-types'
|
||||
@@ -18,6 +19,8 @@ import {
|
||||
import { SourceControlBranchContextRow } from './branch-context-row'
|
||||
import { shouldShowSourceControlBranchContextChrome } from './branch-context-stats'
|
||||
import { SourceControlHeaderOverflowMenu } from './header-overflow-menu'
|
||||
import { useSourceControlHeaderActionsSlot } from './header-actions-slot'
|
||||
import { useSourceControlScope } from './worktree-scope'
|
||||
|
||||
type SourceControlHeaderToolbarProps = {
|
||||
filterQuery: string
|
||||
@@ -61,7 +64,7 @@ function renderOverflowMenu(
|
||||
| 'onExpandNotes'
|
||||
>
|
||||
): React.JSX.Element {
|
||||
return <SourceControlHeaderOverflowMenu {...props} />
|
||||
return <SourceControlHeaderOverflowMenu panelActions={props} />
|
||||
}
|
||||
|
||||
export function SourceControlHeaderToolbar({
|
||||
@@ -93,6 +96,8 @@ export function SourceControlHeaderToolbar({
|
||||
branchLineTotal
|
||||
}: SourceControlHeaderToolbarProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const embedded = useSourceControlScope() !== null
|
||||
const actionsSlot = useSourceControlHeaderActionsSlot()
|
||||
const filterInputRef = useRef<HTMLInputElement>(null)
|
||||
const normalizedFilter = filterQuery.trim()
|
||||
const showCollapsedToolbar = !filterExpanded
|
||||
@@ -134,6 +139,139 @@ export function SourceControlHeaderToolbar({
|
||||
})
|
||||
: t('auto.components.right.sidebar.SourceControl.b3c8f1a902', 'Filter files by name')
|
||||
|
||||
const reviewControl = hostedReview ? (
|
||||
<HostedReviewToolbarLink
|
||||
review={hostedReview}
|
||||
compact={embedded}
|
||||
onOpenHostedReviewInChecks={onOpenHostedReviewInChecks}
|
||||
/>
|
||||
) : suppressedGitHubPRNumber !== null ? (
|
||||
<SuppressedGitHubPRToolbar
|
||||
number={suppressedGitHubPRNumber}
|
||||
onRelink={onRelinkSuppressedGitHubPR}
|
||||
/>
|
||||
) : visibleCreatePrHeaderAction ? (
|
||||
<CreatePrHeaderButton
|
||||
action={visibleCreatePrHeaderAction}
|
||||
isCreatePrIntentInFlight={isCreatePrIntentInFlight}
|
||||
isCreatingPr={isCreatingPr}
|
||||
onClick={onCreatePrHeaderClick}
|
||||
/>
|
||||
) : null
|
||||
|
||||
const filterToggle = (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="source-control-filter-toggle"
|
||||
className={cn(
|
||||
'relative inline-flex shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
|
||||
embedded ? 'size-6' : 'size-7',
|
||||
(normalizedFilter || (embedded && filterExpanded)) && 'bg-muted text-foreground'
|
||||
)}
|
||||
onClick={embedded && filterExpanded ? collapseFilter : expandFilter}
|
||||
aria-label={filterToggleTitle}
|
||||
title={filterToggleTitle}
|
||||
aria-expanded={embedded ? filterExpanded : false}
|
||||
>
|
||||
<Search className="size-3.5" />
|
||||
{normalizedFilter ? (
|
||||
<span className="absolute right-1 top-1 size-1.5 rounded-full bg-foreground" />
|
||||
) : null}
|
||||
</button>
|
||||
)
|
||||
|
||||
const filterRow = (
|
||||
<>
|
||||
{/* Give expanded search the row so PR links and overflow controls do not squeeze typing. */}
|
||||
<div className="flex min-w-0 w-full flex-1 items-center gap-1.5">
|
||||
<Search className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<ImeInput
|
||||
ref={filterInputRef}
|
||||
data-testid="source-control-filter-input"
|
||||
type="text"
|
||||
value={filterQuery}
|
||||
onChange={(event) => onFilterQueryChange(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
collapseFilter()
|
||||
}
|
||||
}}
|
||||
placeholder={t('auto.components.right.sidebar.SourceControl.c35baf2f1e', 'Filter files…')}
|
||||
className="min-w-0 w-full flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-muted-foreground"
|
||||
aria-label={t('auto.components.right.sidebar.SourceControl.c35baf2f1e', 'Filter files…')}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="size-7 shrink-0 text-muted-foreground hover:text-foreground"
|
||||
aria-label={t(
|
||||
'auto.components.right.sidebar.SourceControl.d4f8c2a901',
|
||||
'Clear and close filter'
|
||||
)}
|
||||
title={t(
|
||||
'auto.components.right.sidebar.SourceControl.d4f8c2a901',
|
||||
'Clear and close filter'
|
||||
)}
|
||||
onClick={clearAndCollapseFilter}
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
|
||||
const showBranchContext = shouldShowSourceControlBranchContextChrome(
|
||||
branchSummary,
|
||||
compareBaseRef,
|
||||
headDisplay
|
||||
)
|
||||
const branchContextRow = (reviewTrailing?: React.ReactNode) => (
|
||||
<SourceControlBranchContextRow
|
||||
summary={branchSummary}
|
||||
compareBaseRef={compareBaseRef}
|
||||
headDisplay={headDisplay}
|
||||
headControl={headControl}
|
||||
manualReviewUrl={manualReviewUrl}
|
||||
branchLineTotal={branchLineTotal}
|
||||
reviewControl={reviewTrailing}
|
||||
onChangeBaseRef={onChangeBaseRef}
|
||||
onRetry={onRefreshBranchCompare}
|
||||
/>
|
||||
)
|
||||
|
||||
if (embedded) {
|
||||
// The card header owns filter and overflow; the PR control joins the compare row's base line.
|
||||
const reviewRowShown = reviewControl !== null && !showBranchContext
|
||||
return (
|
||||
<>
|
||||
{actionsSlot
|
||||
? createPortal(
|
||||
<>
|
||||
{filterToggle}
|
||||
{renderOverflowMenu(overflowProps)}
|
||||
</>,
|
||||
actionsSlot
|
||||
)
|
||||
: null}
|
||||
{filterExpanded || showBranchContext || reviewRowShown ? (
|
||||
<div className="flex flex-col gap-1 border-b border-border px-3 py-1.5">
|
||||
{filterExpanded ? (
|
||||
<div className="mb-1.5 flex min-w-0 items-center gap-1.5 border-b border-border pb-1.5">
|
||||
{filterRow}
|
||||
</div>
|
||||
) : null}
|
||||
{showBranchContext ? branchContextRow(reviewControl) : null}
|
||||
{reviewRowShown ? (
|
||||
<div className="flex min-w-0 items-center">{reviewControl}</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-b border-border px-3 pt-1.5 pb-1">
|
||||
<div
|
||||
@@ -142,112 +280,20 @@ export function SourceControlHeaderToolbar({
|
||||
>
|
||||
{showCollapsedToolbar ? (
|
||||
<>
|
||||
{hostedReview ? (
|
||||
<HostedReviewToolbarLink
|
||||
review={hostedReview}
|
||||
onOpenHostedReviewInChecks={onOpenHostedReviewInChecks}
|
||||
/>
|
||||
) : suppressedGitHubPRNumber !== null ? (
|
||||
<SuppressedGitHubPRToolbar
|
||||
number={suppressedGitHubPRNumber}
|
||||
onRelink={onRelinkSuppressedGitHubPR}
|
||||
/>
|
||||
) : visibleCreatePrHeaderAction ? (
|
||||
<CreatePrHeaderButton
|
||||
action={visibleCreatePrHeaderAction}
|
||||
isCreatePrIntentInFlight={isCreatePrIntentInFlight}
|
||||
isCreatingPr={isCreatingPr}
|
||||
onClick={onCreatePrHeaderClick}
|
||||
/>
|
||||
) : (
|
||||
<span className="min-w-0 flex-1" aria-hidden="true" />
|
||||
)}
|
||||
{reviewControl ?? <span className="min-w-0 flex-1" aria-hidden="true" />}
|
||||
{(visibleCreatePrHeaderAction || suppressedGitHubPRNumber !== null) && !hostedReview ? (
|
||||
// Pin filter/overflow right without stretching Create PR.
|
||||
<span className="min-w-0 flex-1" aria-hidden="true" />
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
data-testid="source-control-filter-toggle"
|
||||
className={cn(
|
||||
'relative inline-flex size-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
|
||||
normalizedFilter && 'bg-muted text-foreground'
|
||||
)}
|
||||
onClick={expandFilter}
|
||||
aria-label={filterToggleTitle}
|
||||
title={filterToggleTitle}
|
||||
aria-expanded={false}
|
||||
>
|
||||
<Search className="size-3.5" />
|
||||
{normalizedFilter ? (
|
||||
<span className="absolute right-1 top-1 size-1.5 rounded-full bg-foreground" />
|
||||
) : null}
|
||||
</button>
|
||||
{filterToggle}
|
||||
{renderOverflowMenu(overflowProps)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* Give expanded search the row so PR links and overflow controls do not squeeze typing. */}
|
||||
<div className="flex min-w-0 w-full flex-1 items-center gap-1.5">
|
||||
<Search className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<ImeInput
|
||||
ref={filterInputRef}
|
||||
data-testid="source-control-filter-input"
|
||||
type="text"
|
||||
value={filterQuery}
|
||||
onChange={(event) => onFilterQueryChange(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
collapseFilter()
|
||||
}
|
||||
}}
|
||||
placeholder={t(
|
||||
'auto.components.right.sidebar.SourceControl.c35baf2f1e',
|
||||
'Filter files…'
|
||||
)}
|
||||
className="min-w-0 w-full flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-muted-foreground"
|
||||
aria-label={t(
|
||||
'auto.components.right.sidebar.SourceControl.c35baf2f1e',
|
||||
'Filter files…'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="size-7 shrink-0 text-muted-foreground hover:text-foreground"
|
||||
aria-label={t(
|
||||
'auto.components.right.sidebar.SourceControl.d4f8c2a901',
|
||||
'Clear and close filter'
|
||||
)}
|
||||
title={t(
|
||||
'auto.components.right.sidebar.SourceControl.d4f8c2a901',
|
||||
'Clear and close filter'
|
||||
)}
|
||||
onClick={clearAndCollapseFilter}
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
filterRow
|
||||
)}
|
||||
</div>
|
||||
|
||||
{shouldShowSourceControlBranchContextChrome(branchSummary, compareBaseRef, headDisplay) ? (
|
||||
<div className="mt-1">
|
||||
<SourceControlBranchContextRow
|
||||
summary={branchSummary}
|
||||
compareBaseRef={compareBaseRef}
|
||||
headDisplay={headDisplay}
|
||||
headControl={headControl}
|
||||
manualReviewUrl={manualReviewUrl}
|
||||
branchLineTotal={branchLineTotal}
|
||||
onChangeBaseRef={onChangeBaseRef}
|
||||
onRetry={onRefreshBranchCompare}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{showBranchContext ? <div className="mt-1">{branchContextRow()}</div> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ export function AgentDefaultSurfaceSection({
|
||||
role="radiogroup"
|
||||
aria-label={title}
|
||||
aria-busy={pending}
|
||||
className="grid gap-3.5 @3xl:grid-cols-2"
|
||||
className="grid gap-3.5 @2xl:grid-cols-2"
|
||||
>
|
||||
<SurfaceTile
|
||||
name={name}
|
||||
|
||||
+67
-19
@@ -4,6 +4,7 @@ import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
import { getProjectIdentityKey } from '../../../../../../shared/project-host-setup-projection'
|
||||
import { RepositoryIconPicker } from './RepositoryIconPicker'
|
||||
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
|
||||
@@ -15,7 +16,9 @@ vi.mock('./RepositoryIconColorSection', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('./RepositoryIconTabs', () => ({
|
||||
RepositoryIconTabs: () => null
|
||||
RepositoryIconTabs: ({ onUseGitHubAvatar }: { onUseGitHubAvatar: () => void }) => (
|
||||
<button data-avatar-action onClick={onUseGitHubAvatar} />
|
||||
)
|
||||
}))
|
||||
|
||||
const apiMocks = {
|
||||
@@ -48,7 +51,7 @@ async function flushEffects(): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
describe('RepositoryIconPicker GitHub avatar refresh', () => {
|
||||
describe('RepositoryIconPicker GitHub identity', () => {
|
||||
beforeEach(() => {
|
||||
apiMocks.repoSlug.mockReset()
|
||||
apiMocks.repoUpstream.mockReset()
|
||||
@@ -63,27 +66,72 @@ describe('RepositoryIconPicker GitHub avatar refresh', () => {
|
||||
document.body.replaceChildren()
|
||||
})
|
||||
|
||||
it('does not clobber a fork identity when the live upstream lookup fails offline', async () => {
|
||||
const updateRepo = vi.fn()
|
||||
// A fork whose avatar tracks its parent org, resolved earlier while online.
|
||||
const repo = makeRepo({
|
||||
upstream: { owner: 'stablyai', repo: 'orca' },
|
||||
repoIcon: {
|
||||
type: 'image',
|
||||
src: 'https://github.com/stablyai.png?size=64',
|
||||
source: 'github',
|
||||
label: 'stablyai/orca'
|
||||
}
|
||||
it.each([
|
||||
{ state: 'selected origin', upstream: { owner: 'brennanb2025', repo: 'learnsomething' } },
|
||||
{ state: 'defined nonfork', upstream: null },
|
||||
{ state: 'unavailable metadata', upstream: undefined }
|
||||
])('preserves saved $state when settings opens and reopens', async ({ upstream }) => {
|
||||
const original = makeRepo({
|
||||
upstream,
|
||||
gitRemoteIdentity: {
|
||||
canonicalKey: 'github.com/brennanb2025/learnsomething',
|
||||
remoteName: 'origin',
|
||||
remoteUrl: 'https://github.com/brennanb2025/learnsomething.git'
|
||||
},
|
||||
...(upstream !== undefined
|
||||
? {
|
||||
repoIcon: {
|
||||
type: 'image',
|
||||
src: 'https://github.com/echavemann.png?size=64',
|
||||
source: 'github',
|
||||
label: upstream === null ? 'brennanb2025/learnsomething' : 'echavemann/learnsomething'
|
||||
} as const
|
||||
}
|
||||
: {})
|
||||
})
|
||||
// Failed upstream probes are ambiguous; never replace a known parent identity with same-name origin.
|
||||
apiMocks.repoUpstream.mockResolvedValueOnce(null)
|
||||
apiMocks.repoSlug.mockResolvedValueOnce({ owner: 'parkerrex', repo: 'orca' })
|
||||
let saved: Repo = JSON.parse(JSON.stringify(original))
|
||||
apiMocks.repoUpstream.mockResolvedValue(
|
||||
upstream === undefined ? null : { owner: 'echavemann', repo: 'learnsomething' }
|
||||
)
|
||||
apiMocks.repoSlug.mockResolvedValue({ owner: 'brennanb2025', repo: 'learnsomething' })
|
||||
const updateRepo = (_id: string, updates: Partial<Repo>) => {
|
||||
saved = { ...saved, ...updates }
|
||||
}
|
||||
|
||||
act(() => {
|
||||
root.render(<RepositoryIconPicker repo={repo} updateRepo={updateRepo} />)
|
||||
act(() => root.render(<RepositoryIconPicker repo={saved} updateRepo={updateRepo} />))
|
||||
await flushEffects()
|
||||
act(() => root.unmount())
|
||||
saved = JSON.parse(JSON.stringify(saved))
|
||||
root = createRoot(container)
|
||||
act(() => root.render(<RepositoryIconPicker repo={saved} updateRepo={updateRepo} />))
|
||||
await flushEffects()
|
||||
|
||||
expect(saved.upstream).toEqual(upstream)
|
||||
expect(saved.repoIcon).toEqual(original.repoIcon)
|
||||
expect(getProjectIdentityKey(saved)).toBe('github:brennanb2025/learnsomething')
|
||||
})
|
||||
|
||||
it('still applies a live GitHub avatar when the user requests it', async () => {
|
||||
let saved = makeRepo({ upstream: null })
|
||||
apiMocks.repoUpstream.mockResolvedValue({ owner: 'echavemann', repo: 'learnsomething' })
|
||||
apiMocks.repoSlug.mockResolvedValue({ owner: 'brennanb2025', repo: 'learnsomething' })
|
||||
const updateRepo = (_id: string, updates: Partial<Repo>) => {
|
||||
saved = { ...saved, ...updates }
|
||||
}
|
||||
act(() => root.render(<RepositoryIconPicker repo={saved} updateRepo={updateRepo} />))
|
||||
await flushEffects()
|
||||
await act(async () => {
|
||||
container.querySelector<HTMLButtonElement>('[data-avatar-action]')?.click()
|
||||
})
|
||||
await flushEffects()
|
||||
|
||||
expect(updateRepo).not.toHaveBeenCalled()
|
||||
expect(saved.upstream).toEqual({ owner: 'echavemann', repo: 'learnsomething' })
|
||||
expect(saved.repoIcon).toEqual({
|
||||
type: 'image',
|
||||
src: 'https://github.com/echavemann.png?size=64',
|
||||
source: 'github',
|
||||
label: 'echavemann/learnsomething'
|
||||
})
|
||||
expect(getProjectIdentityKey(saved)).toBe('github:echavemann/learnsomething')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { RotateCcw } from 'lucide-react'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
@@ -20,8 +20,7 @@ import { RepositoryIconColorSection } from './RepositoryIconColorSection'
|
||||
import { RepositoryIconTabs } from './RepositoryIconTabs'
|
||||
import {
|
||||
buildRepositoryGitHubAvatarUpdate,
|
||||
resolveRepositoryGitHubAvatar,
|
||||
resolveRepositoryUpstreamLive
|
||||
resolveRepositoryGitHubAvatar
|
||||
} from '../../../../runtime/repository-github/repository-icon-github'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
|
||||
@@ -71,11 +70,6 @@ export function RepositoryIconPicker({
|
||||
const setIcon = (repoIcon: RepoIcon | null) => updateRepo(repo.id, { repoIcon })
|
||||
const setBadgeColor = (badgeColor: string) => updateRepo(repo.id, { badgeColor })
|
||||
|
||||
const resolveUpstreamLive = useCallback(
|
||||
() => resolveRepositoryUpstreamLive(runtimeTarget, repo),
|
||||
[runtimeTarget, repo]
|
||||
)
|
||||
|
||||
const resolveGitHubAvatar = useCallback(
|
||||
(options?: { forceLive?: boolean }) =>
|
||||
resolveRepositoryGitHubAvatar(runtimeTarget, repo, options),
|
||||
@@ -138,39 +132,6 @@ export function RepositoryIconPicker({
|
||||
}
|
||||
}
|
||||
|
||||
const githubIdentityRefreshedRef = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
const hasGitHubAvatar = repo.repoIcon?.type === 'image' && repo.repoIcon.source === 'github'
|
||||
const shouldRefresh = hasGitHubAvatar || repo.upstream === undefined
|
||||
if (!shouldRefresh || githubIdentityRefreshedRef.current === repo.id) {
|
||||
return
|
||||
}
|
||||
githubIdentityRefreshedRef.current = repo.id
|
||||
let cancelled = false
|
||||
void (async () => {
|
||||
let updates: Partial<Repo> | null
|
||||
try {
|
||||
if (hasGitHubAvatar) {
|
||||
// Stored GitHub avatar metadata can outlive transfers; refresh live only when opening affected repo settings.
|
||||
const resolution = await resolveGitHubAvatar({ forceLive: true })
|
||||
updates = buildRepositoryGitHubAvatarUpdate(repo, resolution)
|
||||
} else {
|
||||
const upstream = await resolveUpstreamLive()
|
||||
updates = { upstream: upstream ?? null }
|
||||
}
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (cancelled || !mountedRef.current || !updates) {
|
||||
return
|
||||
}
|
||||
updateRepo(repo.id, updates)
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [repo, resolveGitHubAvatar, resolveUpstreamLive, updateRepo, mountedRef])
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -119,7 +119,7 @@ export function ShortcutCommandBlock({
|
||||
className="group/shortcut flex max-w-none flex-col"
|
||||
>
|
||||
<div className="flex min-h-9 items-center gap-3 rounded-md px-2 py-1 transition-colors hover:bg-accent/40 focus-within:bg-accent/40">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<TruncatedSidebarLabel
|
||||
text={item.title}
|
||||
className={cn('text-sm', isDisabled ? 'text-muted-foreground' : 'text-foreground')}
|
||||
|
||||
@@ -25,6 +25,7 @@ export default function PinnedTabCloseDialog(): React.JSX.Element {
|
||||
const [previousRequest, setPreviousRequest] = useState(request)
|
||||
|
||||
const tabLabel = request?.tabLabel.trim()
|
||||
const unsentNotes = request?.unsentNotes === true
|
||||
|
||||
// Reset new requests before paint without reviving a cancelled request’s checkbox state.
|
||||
if (request !== previousRequest) {
|
||||
@@ -53,16 +54,26 @@ export default function PinnedTabCloseDialog(): React.JSX.Element {
|
||||
<DialogContent className="max-w-sm" showCloseButton={false}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-sm">
|
||||
{t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.6c190f295a',
|
||||
'Close pinned tab?'
|
||||
)}
|
||||
{unsentNotes
|
||||
? t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.unsent_notes_title',
|
||||
'Discard unsent notes?'
|
||||
)
|
||||
: t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.6c190f295a',
|
||||
'Close pinned tab?'
|
||||
)}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs">
|
||||
{t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.0d1963f4a6',
|
||||
'This tab is pinned. Are you sure you want to close it?'
|
||||
)}
|
||||
{unsentNotes
|
||||
? t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.unsent_notes_description',
|
||||
"This tab has notes you haven't sent. Closing it discards them."
|
||||
)
|
||||
: t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.0d1963f4a6',
|
||||
'This tab is pinned. Are you sure you want to close it?'
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{tabLabel ? (
|
||||
@@ -70,19 +81,21 @@ export default function PinnedTabCloseDialog(): React.JSX.Element {
|
||||
{tabLabel}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={checkboxId}
|
||||
checked={dontAskAgain}
|
||||
onCheckedChange={(checked) => setDontAskAgain(checked === true)}
|
||||
/>
|
||||
<Label htmlFor={checkboxId} className="text-xs font-normal text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.dont_ask_again',
|
||||
"Don't ask again for pinned tabs"
|
||||
)}
|
||||
</Label>
|
||||
</div>
|
||||
{unsentNotes ? null : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={checkboxId}
|
||||
checked={dontAskAgain}
|
||||
onCheckedChange={(checked) => setDontAskAgain(checked === true)}
|
||||
/>
|
||||
<Label htmlFor={checkboxId} className="text-xs font-normal text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.terminal.pane.PinnedTabCloseDialog.dont_ask_again',
|
||||
"Don't ask again for pinned tabs"
|
||||
)}
|
||||
</Label>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter className="gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={dismissPinnedTabClose}>
|
||||
{t('auto.components.terminal.pane.PinnedTabCloseDialog.0b38ee2f86', 'Cancel')}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback } from 'react'
|
||||
import { hasUnsentBrowserNotes } from '@/store/slices/browser/annotations/browser-page-annotation'
|
||||
import { useAppStore } from '../store'
|
||||
import { editorTabsNeedingSavePrompt } from '@/store/slices/editor/tabs/editor-tab-close-target'
|
||||
import { isEditorTabContentType } from '@/store/slices/editor/tabs/editor-tab-content-type'
|
||||
@@ -46,7 +47,12 @@ export function useTerminalBulkCloseActions(
|
||||
.map((tab) => tab.id)
|
||||
for (const id of tabIds) {
|
||||
const unifiedTab = byId.get(id) ?? byEntity.get(id)
|
||||
if (unifiedTab?.isPinned) {
|
||||
// Bulk closes keep pinned tabs and tabs holding unsent browser notes open.
|
||||
if (
|
||||
unifiedTab?.isPinned ||
|
||||
(unifiedTab?.contentType === 'browser' &&
|
||||
hasUnsentBrowserNotes(state, unifiedTab.entityId))
|
||||
) {
|
||||
continue
|
||||
}
|
||||
if (unifiedTab && isEditorTabContentType(unifiedTab.contentType)) {
|
||||
|
||||
@@ -107,6 +107,7 @@ export async function useIpcEventsForCloseRouting({
|
||||
activeBrowserTabIdByWorktree: { 'wt-1': 'workspace-1' },
|
||||
browserTabsByWorktree: { 'wt-1': [{ id: 'workspace-1' }] },
|
||||
browserPagesByWorkspace: {},
|
||||
browserAnnotationsByPageId: {},
|
||||
openFiles: [],
|
||||
unifiedTabsByWorktree: {},
|
||||
closeBrowserTab: vi.fn(),
|
||||
|
||||
@@ -73,6 +73,7 @@ function storeState(activeWorktreeId: string) {
|
||||
[LOCAL_WT]: [{ id: 'ws-local' }],
|
||||
[REMOTE_WT]: [{ id: 'ws-remote' }]
|
||||
},
|
||||
browserAnnotationsByPageId: {},
|
||||
browserPagesByWorkspace: {
|
||||
'ws-local': [{ id: 'page-local' }],
|
||||
'ws-remote': [{ id: 'page-remote' }]
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { destroyPersistentWebview } from '@/components/browser-pane/host-guest/webview-registry'
|
||||
import {
|
||||
guardPinnedTabClose,
|
||||
isUnifiedTabPinned,
|
||||
resolvePinnedTabLabel
|
||||
} from '../../store/slices/tabs/closing/pinned-tab-close-guard'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { closeBrowserTabWithReply } from './browser-tab-close-with-reply'
|
||||
import { useAppStore } from '../../store'
|
||||
import { acquireBrowserAutomationBootstrapLease } from './browser-automation-bootstrap-lease'
|
||||
import {
|
||||
@@ -209,28 +205,8 @@ export function registerBrowserRequestIpcBridge(unsubs: (() => void)[]): void {
|
||||
)
|
||||
})
|
||||
}
|
||||
const replyPinnedBrowserCloseCanceled = (tabId: string): void => {
|
||||
window.api.ui.replyTabClose({
|
||||
requestId: data.requestId,
|
||||
error: translate(
|
||||
'auto.hooks.useIpcEvents.2f6637fe6c',
|
||||
'Browser tab {{value0}} is pinned',
|
||||
{ value0: tabId }
|
||||
)
|
||||
})
|
||||
}
|
||||
const closeBrowserWorkspaceWithReply = (worktreeId: string, workspaceId: string): void => {
|
||||
const currentStore = useAppStore.getState()
|
||||
guardPinnedTabClose({
|
||||
isPinned: isUnifiedTabPinned(currentStore, worktreeId, workspaceId),
|
||||
tabLabel: resolvePinnedTabLabel(currentStore, worktreeId, workspaceId),
|
||||
onClose: () => {
|
||||
useAppStore.getState().closeBrowserTab(workspaceId)
|
||||
window.api.ui.replyTabClose({ requestId: data.requestId })
|
||||
},
|
||||
onCancel: () => replyPinnedBrowserCloseCanceled(workspaceId)
|
||||
})
|
||||
}
|
||||
const closeWithReply = (worktreeId: string, workspaceId: string, pageId?: string): void =>
|
||||
closeBrowserTabWithReply({ requestId: data.requestId, worktreeId, workspaceId, pageId })
|
||||
const tabToClose =
|
||||
explicitTargetId ??
|
||||
(data.worktreeId
|
||||
@@ -273,11 +249,15 @@ export function registerBrowserRequestIpcBridge(unsubs: (() => void)[]): void {
|
||||
replyBrowserTabNotFound(tabToClose)
|
||||
return
|
||||
}
|
||||
if (owningWorktreeId) {
|
||||
closeWithReply(
|
||||
owningWorktreeId,
|
||||
workspaceId,
|
||||
pages.length > 1 ? tabToClose : undefined
|
||||
)
|
||||
return
|
||||
}
|
||||
if (pages.length <= 1) {
|
||||
if (owningWorktreeId) {
|
||||
closeBrowserWorkspaceWithReply(owningWorktreeId, workspaceId)
|
||||
return
|
||||
}
|
||||
store.closeBrowserTab(workspaceId)
|
||||
} else {
|
||||
store.closeBrowserPage(tabToClose)
|
||||
@@ -295,7 +275,7 @@ export function registerBrowserRequestIpcBridge(unsubs: (() => void)[]): void {
|
||||
replyBrowserTabNotFound(tabToClose)
|
||||
return
|
||||
}
|
||||
closeBrowserWorkspaceWithReply(owningWorktreeId, tabToClose)
|
||||
closeWithReply(owningWorktreeId, tabToClose)
|
||||
return
|
||||
}
|
||||
if (explicitTargetId) {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { useAppStore } from '../../store'
|
||||
import { hasUnsentBrowserNotes } from '@/store/slices/browser/annotations/browser-page-annotation'
|
||||
import {
|
||||
guardPinnedTabClose,
|
||||
isUnifiedTabPinned,
|
||||
resolvePinnedTabLabel
|
||||
} from '../../store/slices/tabs/closing/pinned-tab-close-guard'
|
||||
|
||||
/** Closes a browser tab, or one page of it, for a CLI or extension request once the user allows it, then replies to main. */
|
||||
export function closeBrowserTabWithReply(params: {
|
||||
requestId: string
|
||||
worktreeId: string
|
||||
workspaceId: string
|
||||
/** Closes only this page, so the tab's pin does not guard it; its notes do. */
|
||||
pageId?: string
|
||||
}): void {
|
||||
const { requestId, worktreeId, workspaceId, pageId } = params
|
||||
const state = useAppStore.getState()
|
||||
const unsentNotes = pageId
|
||||
? (state.browserAnnotationsByPageId[pageId]?.length ?? 0) > 0
|
||||
: hasUnsentBrowserNotes(state, workspaceId)
|
||||
const closedId = pageId ?? workspaceId
|
||||
guardPinnedTabClose({
|
||||
isPinned: !pageId && isUnifiedTabPinned(state, worktreeId, workspaceId),
|
||||
tabLabel: resolvePinnedTabLabel(state, worktreeId, workspaceId),
|
||||
onClose: () => {
|
||||
const latest = useAppStore.getState()
|
||||
// Siblings may have closed while the prompt was open; the last page closes its tab.
|
||||
if (pageId && (latest.browserPagesByWorkspace[workspaceId]?.length ?? 0) > 1) {
|
||||
latest.closeBrowserPage(pageId)
|
||||
} else {
|
||||
latest.closeBrowserTab(workspaceId)
|
||||
}
|
||||
window.api.ui.replyTabClose({ requestId })
|
||||
},
|
||||
onCancel: () =>
|
||||
window.api.ui.replyTabClose({
|
||||
requestId,
|
||||
error: unsentNotes
|
||||
? translate(
|
||||
'auto.hooks.useIpcEvents.unsent_notes_close_canceled',
|
||||
'Browser tab {{value0}} has unsent notes, and the user kept it open',
|
||||
{ value0: closedId }
|
||||
)
|
||||
: translate('auto.hooks.useIpcEvents.2f6637fe6c', 'Browser tab {{value0}} is pinned', {
|
||||
value0: closedId
|
||||
})
|
||||
}),
|
||||
unsentNotes
|
||||
})
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { hasUnsentBrowserNotes } from '@/store/slices/browser/annotations/browser-page-annotation'
|
||||
import { isLocalSessionTabCloseOwned } from '@/runtime/web-session-tabs-sync/closing/local-session-tab-close-owner'
|
||||
import { closeMobileSessionTabInStore } from '@/runtime/web-session-tabs-sync/closing/mobile-session-tab-close'
|
||||
import {
|
||||
@@ -35,7 +36,8 @@ export function registerSessionTabIpcBridge(unsubs: (() => void)[]): void {
|
||||
guardPinnedTabClose({
|
||||
isPinned: isUnifiedTabPinned(store, worktreeId, browserTarget.workspaceId),
|
||||
tabLabel: resolvePinnedTabLabel(store, worktreeId, browserTarget.workspaceId),
|
||||
onClose: () => useAppStore.getState().closeBrowserTab(browserTarget.workspaceId)
|
||||
onClose: () => useAppStore.getState().closeBrowserTab(browserTarget.workspaceId),
|
||||
unsentNotes: hasUnsentBrowserNotes(store, browserTarget.workspaceId)
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -111,7 +113,8 @@ export function registerSessionTabIpcBridge(unsubs: (() => void)[]): void {
|
||||
isPinned: isUnifiedTabPinned(store, worktreeId, visibleId),
|
||||
tabLabel: resolvePinnedTabLabel(store, worktreeId, visibleId),
|
||||
onClose: closeAndRespond,
|
||||
onCancel: () => respond(SESSION_TAB_CLOSE_CANCELED_ERROR)
|
||||
onCancel: () => respond(SESSION_TAB_CLOSE_CANCELED_ERROR),
|
||||
unsentNotes: browserTarget ? hasUnsentBrowserNotes(store, browserTarget.workspaceId) : false
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
+4
@@ -624,6 +624,10 @@
|
||||
"worktreeCountLabel_one": "{{count}} worktree",
|
||||
"worktreeCountLabel_other": "{{count}} worktrees"
|
||||
},
|
||||
"FolderWorkspaceSourceControl": {
|
||||
"changeCount_one": "{{count}} change",
|
||||
"changeCount_other": "{{count}} changes"
|
||||
},
|
||||
"FolderWorkspaceWorktreesPanel": {
|
||||
"attachedCount_one": "{{count}} attached worktree",
|
||||
"attachedCount_other": "{{count}} attached worktrees"
|
||||
|
||||
@@ -2288,6 +2288,7 @@
|
||||
"useIpcEvents": {
|
||||
"0e3cf53060": "Browser tab {{value0}} not found",
|
||||
"2f6637fe6c": "Browser tab {{value0}} is pinned",
|
||||
"unsent_notes_close_canceled": "Browser tab {{value0}} has unsent notes, and the user kept it open",
|
||||
"a8d2bf8e9e": "No active browser tab to close",
|
||||
"f000b2ff76": "No active worktree",
|
||||
"7a64b31991": "Local terminal creation is unavailable while a remote runtime is active",
|
||||
@@ -4511,7 +4512,9 @@
|
||||
"0d1963f4a6": "This tab is pinned. Are you sure you want to close it?",
|
||||
"dont_ask_again": "Don't ask again for pinned tabs",
|
||||
"0b38ee2f86": "Cancel",
|
||||
"c337c9d75c": "Close"
|
||||
"c337c9d75c": "Close",
|
||||
"unsent_notes_title": "Discard unsent notes?",
|
||||
"unsent_notes_description": "This tab has notes you haven't sent. Closing it discards them."
|
||||
},
|
||||
"TerminalSshReconnectOverlay": {
|
||||
"authFailed": "Authentication failed for {{value0}}. Connect again to continue this terminal session.",
|
||||
@@ -18869,6 +18872,8 @@
|
||||
"reloaded": "Reloaded"
|
||||
},
|
||||
"FolderWorkspaceSourceControl": {
|
||||
"changeCount_one": "{{count}} change",
|
||||
"changeCount_other": "{{count}} changes",
|
||||
"openWorktree": "Open this worktree",
|
||||
"reconnect": "Reconnect to see this worktree’s changes."
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { BrowserPage, BrowserWorkspace } from '../../../../../shared/browser-workspace-types'
|
||||
import type { BrowserPageAnnotation } from '../../../../../shared/browser/element-grab/browser-grab-types'
|
||||
import type { WorkspaceSessionState } from '../../../../../shared/workspace-session/workspace-session-state-types'
|
||||
import type { RemoteBrowserPageHandle } from '../../../store/slices/browser/browser-slice-contract'
|
||||
|
||||
@@ -6,7 +7,8 @@ export function buildBrowserSessionData(
|
||||
browserTabsByWorktree: Record<string, BrowserWorkspace[]>,
|
||||
browserPagesByWorkspace: Record<string, BrowserPage[]>,
|
||||
activeBrowserTabIdByWorktree: Record<string, string | null>,
|
||||
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>
|
||||
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>,
|
||||
browserAnnotationsByPageId: Record<string, BrowserPageAnnotation[]>
|
||||
): Pick<
|
||||
WorkspaceSessionState,
|
||||
'browserTabsByWorktree' | 'browserPagesByWorkspace' | 'activeBrowserTabIdByWorktree'
|
||||
@@ -16,7 +18,8 @@ export function buildBrowserSessionData(
|
||||
browserTabsByWorktree: buildPersistedBrowserTabsByWorktree(browserTabsByWorktree),
|
||||
browserPagesByWorkspace: buildPersistedBrowserPagesByWorkspace(
|
||||
browserPagesByWorkspace,
|
||||
remoteBrowserPageHandlesByPageId
|
||||
remoteBrowserPageHandlesByPageId,
|
||||
browserAnnotationsByPageId
|
||||
),
|
||||
activeBrowserTabIdByWorktree
|
||||
}
|
||||
@@ -35,16 +38,21 @@ export function buildPersistedBrowserTabsByWorktree(
|
||||
|
||||
export function buildPersistedBrowserPagesByWorkspace(
|
||||
browserPagesByWorkspace: Record<string, BrowserPage[]>,
|
||||
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>
|
||||
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>,
|
||||
browserAnnotationsByPageId: Record<string, BrowserPageAnnotation[]>
|
||||
): WorkspaceSessionState['browserPagesByWorkspace'] {
|
||||
return Object.fromEntries(
|
||||
Object.entries(browserPagesByWorkspace).map(([workspaceId, pages]) => [
|
||||
workspaceId,
|
||||
pages.map((page) => ({
|
||||
...page,
|
||||
loading: false,
|
||||
...persistedRemoteBrowserPageIdentity(remoteBrowserPageHandlesByPageId[page.id])
|
||||
}))
|
||||
pages.map((page) => {
|
||||
const annotations = browserAnnotationsByPageId[page.id]
|
||||
return {
|
||||
...page,
|
||||
loading: false,
|
||||
...persistedRemoteBrowserPageIdentity(remoteBrowserPageHandlesByPageId[page.id]),
|
||||
...(annotations?.length ? { annotations } : {})
|
||||
}
|
||||
})
|
||||
])
|
||||
)
|
||||
}
|
||||
|
||||
@@ -155,10 +155,15 @@ export function buildWorkspaceSessionPatch(
|
||||
snapshot.browserTabsByWorktree
|
||||
)
|
||||
}
|
||||
if (stagedVisibilityChanged || changed.has('browserPagesByWorkspace')) {
|
||||
if (
|
||||
stagedVisibilityChanged ||
|
||||
changed.has('browserPagesByWorkspace') ||
|
||||
changed.has('browserAnnotationsByPageId')
|
||||
) {
|
||||
patch.browserPagesByWorkspace = buildPersistedBrowserPagesByWorkspace(
|
||||
snapshot.browserPagesByWorkspace,
|
||||
snapshot.remoteBrowserPageHandlesByPageId
|
||||
snapshot.remoteBrowserPageHandlesByPageId,
|
||||
snapshot.browserAnnotationsByPageId
|
||||
)
|
||||
}
|
||||
if (stagedVisibilityChanged || changed.has('activeBrowserTabIdByWorktree')) {
|
||||
|
||||
@@ -42,6 +42,7 @@ export type WorkspaceSessionSnapshot = Pick<
|
||||
| 'activeTabTypeByWorktree'
|
||||
| 'browserTabsByWorktree'
|
||||
| 'browserPagesByWorkspace'
|
||||
| 'browserAnnotationsByPageId'
|
||||
| 'activeBrowserTabIdByWorktree'
|
||||
| 'browserUrlHistory'
|
||||
| 'workspaceDocHistory'
|
||||
@@ -84,6 +85,7 @@ export const SESSION_RELEVANT_FIELDS = [
|
||||
'activeTabTypeByWorktree',
|
||||
'browserTabsByWorktree',
|
||||
'browserPagesByWorkspace',
|
||||
'browserAnnotationsByPageId',
|
||||
'activeBrowserTabIdByWorktree',
|
||||
'browserUrlHistory',
|
||||
'workspaceDocHistory',
|
||||
@@ -310,7 +312,8 @@ export function buildWorkspaceSessionPayload(
|
||||
snapshot.browserTabsByWorktree,
|
||||
snapshot.browserPagesByWorkspace,
|
||||
snapshot.activeBrowserTabIdByWorktree,
|
||||
snapshot.remoteBrowserPageHandlesByPageId
|
||||
snapshot.remoteBrowserPageHandlesByPageId,
|
||||
snapshot.browserAnnotationsByPageId
|
||||
),
|
||||
// Why: enforce the history storage cap here so stale renderer state can't make every write stringify an oversized legacy array.
|
||||
browserUrlHistory: normalizeBrowserHistoryEntries(snapshot.browserUrlHistory),
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
resolvePinnedTabLabel
|
||||
} from '@/store/slices/tabs/closing/pinned-tab-close-guard'
|
||||
import { createWorkspaceTabCloseCommands } from '@/components/tab-group/workspace-tab-close-commands'
|
||||
import { hasUnsentBrowserNotes } from '@/store/slices/browser/annotations/browser-page-annotation'
|
||||
import { captureWorkspaceEmptiedReaction } from '@/components/tab-group/workspace-emptied-reaction'
|
||||
import {
|
||||
handleSwitchRecentTab,
|
||||
@@ -174,6 +175,11 @@ export function dispatchWorkspaceTabCommand(command: WorkspaceTabCommand): boole
|
||||
if ((command.bulk || command.skipEmptyCheck) && tab.isPinned) {
|
||||
return true
|
||||
}
|
||||
const unsentNotes = tab.contentType === 'browser' && hasUnsentBrowserNotes(state, tab.entityId)
|
||||
// Bulk closes keep a tab holding unsent notes open, as they keep pinned tabs.
|
||||
if (command.bulk && unsentNotes) {
|
||||
return true
|
||||
}
|
||||
// Why before the pin guard: its prompt takes focus, and the floating panel's reaction reads focus.
|
||||
const whenEmptied =
|
||||
command.bulk || command.skipEmptyCheck
|
||||
@@ -189,7 +195,8 @@ export function dispatchWorkspaceTabCommand(command: WorkspaceTabCommand): boole
|
||||
guardPinnedTabClose({
|
||||
isPinned: tab.isPinned === true,
|
||||
tabLabel: resolvePinnedTabLabel(state, target.worktreeId, tab.id),
|
||||
onClose: close
|
||||
onClose: close,
|
||||
unsentNotes
|
||||
})
|
||||
}
|
||||
return true
|
||||
|
||||
@@ -42,3 +42,16 @@ export function retainBrowserAnnotationMarkerIds(
|
||||
}
|
||||
return nextByPageId
|
||||
}
|
||||
|
||||
/** Closing a browser tab discards the notes its pages hold unsent. */
|
||||
export function hasUnsentBrowserNotes(
|
||||
state: {
|
||||
browserPagesByWorkspace: Record<string, readonly { id: string }[]>
|
||||
browserAnnotationsByPageId: Record<string, readonly BrowserPageAnnotation[]>
|
||||
},
|
||||
browserWorkspaceId: string
|
||||
): boolean {
|
||||
return (state.browserPagesByWorkspace[browserWorkspaceId] ?? []).some(
|
||||
(page) => (state.browserAnnotationsByPageId[page.id]?.length ?? 0) > 0
|
||||
)
|
||||
}
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import '../../../../../../shared/constants'
|
||||
import { parseWorkspaceSession } from '../../../../../../shared/workspace-session/workspace-session-schema'
|
||||
import type { WorkspaceSessionState } from '../../../../../../shared/workspace-session/workspace-session-state-types'
|
||||
import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session'
|
||||
import { createTestStore } from '../../../testing/app-store-test-fixture'
|
||||
import { createStoreSessionMockApi } from '../../../testing/app-store-session-api.test-fixture'
|
||||
import { makeWorktree } from '../../worktrees/worktree.test-fixture'
|
||||
import { makeBrowserTab } from '../browser-tab.test-fixture'
|
||||
import { makeAnnotation } from '../annotations/browser-annotation-test-fixture'
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
|
||||
|
||||
createStoreSessionMockApi()
|
||||
|
||||
const WT = 'repo1::/path/wt1'
|
||||
|
||||
function createHydratedStore(session: WorkspaceSessionState) {
|
||||
const store = createTestStore()
|
||||
store.setState({
|
||||
repos: [{ id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }],
|
||||
worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt1' })] },
|
||||
activeWorktreeId: WT
|
||||
})
|
||||
store.getState().hydrateBrowserSession(session)
|
||||
return store
|
||||
}
|
||||
|
||||
describe('unsent browser notes across a restart', () => {
|
||||
it('restores a page’s unsent notes from the saved session', () => {
|
||||
const before = createHydratedStore({
|
||||
activeRepoId: 'repo1',
|
||||
activeWorktreeId: WT,
|
||||
activeTabId: null,
|
||||
tabsByWorktree: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
browserTabsByWorktree: {
|
||||
[WT]: [makeBrowserTab({ id: 'workspace-1', worktreeId: WT, url: 'https://example.com/' })]
|
||||
},
|
||||
browserPagesByWorkspace: {
|
||||
'workspace-1': [
|
||||
{
|
||||
id: 'page-1',
|
||||
workspaceId: 'workspace-1',
|
||||
worktreeId: WT,
|
||||
url: 'https://example.com/',
|
||||
title: 'Example',
|
||||
loading: false,
|
||||
faviconUrl: null,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
loadError: null,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
activeBrowserTabIdByWorktree: { [WT]: 'workspace-1' }
|
||||
})
|
||||
before.getState().addBrowserPageAnnotation(makeAnnotation('page-1'))
|
||||
|
||||
const saved = parseWorkspaceSession(
|
||||
JSON.parse(JSON.stringify(buildWorkspaceSessionPayload(before.getState())))
|
||||
)
|
||||
if (!saved.ok) {
|
||||
throw new Error(saved.error)
|
||||
}
|
||||
const after = createHydratedStore(saved.value)
|
||||
|
||||
expect(after.getState().browserAnnotationsByPageId).toEqual({
|
||||
'page-1': [makeAnnotation('page-1')]
|
||||
})
|
||||
expect(after.getState().browserPagesByWorkspace['workspace-1']?.[0]).not.toHaveProperty(
|
||||
'annotations'
|
||||
)
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user