Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

perf: fix six scan findings (STA-12863, 12852, 12864, 12865, 12867, 12871) (#36103)

Neil09f58f120b87
diff --git a/src/main/plugins/catalog/plugin-auto-updater.test.ts b/src/main/plugins/catalog/plugin-auto-updater.test.ts
index d02105e7d99..7443d01f875 100644
--- a/src/main/plugins/catalog/plugin-auto-updater.test.ts
+++ b/src/main/plugins/catalog/plugin-auto-updater.test.ts
@@ -9,6 +9,7 @@ import {
normalizePluginUpdatePolicySettings,
type PluginAutoUpdateState
} from '../../../shared/plugins/catalog/plugin-update-policy'
+import { emptyPluginLockfile } from '../../../shared/plugins/installation/plugin-install-lockfile'
import type { ValidDiscoveredPlugin } from '../plugin-discovery'
import { PLUGIN_AUTO_UPDATE_HOLD_BACK_MS, PluginAutoUpdater } from './plugin-auto-updater'
@@ -102,6 +103,7 @@ function setup(
}
},
installer: {
+ readInstallLockfile: async () => emptyPluginLockfile(),
findInstalledUpdateListing: vi.fn(async () => ({
listing: {
marketplaceSourceId: 'a'.repeat(32),
diff --git a/src/main/plugins/catalog/plugin-auto-updater.ts b/src/main/plugins/catalog/plugin-auto-updater.ts
index e6c7cb1a17f..b18ba0672aa 100644
--- a/src/main/plugins/catalog/plugin-auto-updater.ts
+++ b/src/main/plugins/catalog/plugin-auto-updater.ts
@@ -12,6 +12,7 @@ import {
readPreviewAccessGrowth,
type PluginCatalogInstallOutcome
} from './plugin-update-approval'
+import type { PluginLockfile } from '../../../shared/plugins/installation/plugin-install-lockfile'
import type { PluginPolicySource } from '../plugin-activation-policy'
import type { PluginMarketplaceInstaller } from './plugin-marketplace-installer'
import type { PluginReleaseFirstSeenStore } from './plugin-release-first-seen-store'
@@ -30,7 +31,7 @@ type AutoUpdatePluginService = {
type AutoUpdateInstaller = Pick<
PluginMarketplaceInstaller,
- 'findInstalledUpdateListing' | 'previewInstalledUpdate' | 'install'
+ 'readInstallLockfile' | 'findInstalledUpdateListing' | 'previewInstalledUpdate' | 'install'
>
/**
@@ -104,6 +105,14 @@ export class PluginAutoUpdater {
let killListFresh: Promise<void> | null = null
const refreshKillList = (): Promise<void> =>
(killListFresh ??= this.options.refreshKillList().then(() => undefined))
+ // Why per pass: installs only rewrite their own entry, and preview/install reread the lock.
+ let installLock: Promise<PluginLockfile> | null = null
+ const readInstallLock = (): Promise<PluginLockfile> =>
+ (installLock ??= this.options.installer.readInstallLockfile().catch((error: unknown) => {
+ // Why: a transient read error fails only this plugin, as the per-plugin reads did.
+ installLock = null
+ throw error
+ }))
const updatedNow: PluginAutoUpdateState['updated'] = {}
const needsReview: PluginAutoUpdateState['needsReview'] = {}
for (const plugin of this.options.pluginService.getDiscovered()) {
@@ -111,7 +120,7 @@ export class PluginAutoUpdater {
continue
}
try {
- const verdict = await this.updateOne(plugin, startedAt, refreshKillList)
+ const verdict = await this.updateOne(plugin, startedAt, refreshKillList, readInstallLock)
// Why logged: a headless or remote host has no toast, so the log is the only record.
if (verdict?.kind === 'updated') {
updatedNow[plugin.pluginKey] = verdict.version
@@ -135,14 +144,18 @@ export class PluginAutoUpdater {
private async updateOne(
plugin: ValidDiscoveredPlugin,
now: number,
- refreshKillList: () => Promise<void>
+ refreshKillList: () => Promise<void>,
+ readInstallLock: () => Promise<PluginLockfile>
): Promise<{ kind: 'updated' | 'needs-review'; version: string } | null> {
const { pluginService, installer } = this.options
// Why approved only: a disabled or never-approved plugin is the user's to update.
if (!readApprovedPredecessor(pluginService.options, plugin)) {
return null
}
- const found = await installer.findInstalledUpdateListing(plugin.pluginKey)
+ const found = await installer.findInstalledUpdateListing(
+ plugin.pluginKey,
+ await readInstallLock()
+ )
// Why pinned only: an unpinned listing installs a branch head, which can move after the hold.
const release = found?.listing.release
if (
@@ -164,8 +177,9 @@ export class PluginAutoUpdater {
}
}
const preview = await installer.previewInstalledUpdate(plugin.pluginKey)
- // Why: a catalog refresh since the hold check can list another release; install only the held one.
+ // Why: a catalog refresh or source switch since the hold check can list another release; install only the held one.
if (
+ preview.marketplaceSourceId !== found.listing.marketplaceSourceId ||
preview.resolvedCommit !== release.commit ||
preview.contentHash !== release.contentHash ||
preview.contentHash === plugin.contentHash
diff --git a/src/main/plugins/catalog/plugin-catalog-image-extraction.ts b/src/main/plugins/catalog/plugin-catalog-image-extraction.ts
index 9fd11023d9a..91ec1ab5d94 100644
--- a/src/main/plugins/catalog/plugin-catalog-image-extraction.ts
+++ b/src/main/plugins/catalog/plugin-catalog-image-extraction.ts
@@ -6,7 +6,10 @@ import {
type PluginCatalogImages,
type PluginImageKind
} from '../../../shared/plugins/images/plugin-image-fields'
-import type { PluginMarketplace } from '../../../shared/plugins/catalog/plugin-marketplace'
+import type {
+ PluginMarketplace,
+ PluginMarketplaceEntry
+} from '../../../shared/plugins/catalog/plugin-marketplace'
import { sha256Hex } from '../plugin-image-cache'
// Why a catalog-wide cap: a large catalog must not turn one refresh into an unbounded download.
@@ -16,16 +19,27 @@ type CatalogImage = NonNullable<PluginCatalogImages['cover']>
export type CatalogBlobReader = (path: string, maxBytes: number) => Promise<Buffer | null>
+/** Gives an entry images before they are checked, with a reader for the bytes it already read. */
+export type CatalogEntryImageFill = (
+ entry: PluginMarketplaceEntry,
+ readBlob: CatalogBlobReader
+) => Promise<{ entry: PluginMarketplaceEntry; readBlob: CatalogBlobReader }>
+
/** Reads every image a catalog references from the catalog repository at its commit, keeps the
* ones whose bytes match their hash, size and format, and drops the rest from the listing. */
export async function extractCatalogImages(
marketplace: PluginMarketplace,
- readBlob: CatalogBlobReader
+ readBlob: CatalogBlobReader,
+ fill?: CatalogEntryImageFill
): Promise<{ marketplace: PluginMarketplace; images: Buffer[] }> {
const verified = new Map<string, Buffer>()
const rejected = new Set<string>()
let budget = CATALOG_IMAGES_MAX_BYTES
- const check = async (image: CatalogImage, kind: PluginImageKind): Promise<boolean> => {
+ const check = async (
+ image: CatalogImage,
+ kind: PluginImageKind,
+ read: CatalogBlobReader
+ ): Promise<boolean> => {
if (verified.has(image.sha256)) {
return true
}
@@ -33,7 +47,7 @@ export async function extractCatalogImages(
return false
}
const maxBytes = Math.min(PLUGIN_IMAGE_RULES[kind].maxBytes, budget)
- const bytes = maxBytes > 0 ? await readBlob(image.path, maxBytes).catch(() => null) : null
+ const bytes = maxBytes > 0 ? await read(image.path, maxBytes).catch(() => null) : null
const info = bytes ? readPluginImageHeader(bytes) : 'missing'
const ok =
bytes !== null &&
@@ -50,12 +64,16 @@ export async function extractCatalogImages(
}
return ok
}
- const keep = async (images: PluginCatalogImages): Promise<PluginCatalogImages> => {
- const icon = images.icon && (await check(images.icon, 'icon')) ? images.icon : undefined
- const cover = images.cover && (await check(images.cover, 'cover')) ? images.cover : undefined
+ const keep = async (
+ images: PluginCatalogImages,
+ read: CatalogBlobReader
+ ): Promise<PluginCatalogImages> => {
+ const icon = images.icon && (await check(images.icon, 'icon', read)) ? images.icon : undefined
+ const cover =
+ images.cover && (await check(images.cover, 'cover', read)) ? images.cover : undefined
const screenshots: CatalogImage[] = []
for (const shot of images.screenshots ?? []) {
- if (await check(shot, 'screenshot')) {
+ if (await check(shot, 'screenshot', read)) {
screenshots.push(shot)
}
}
@@ -66,7 +84,10 @@ export async function extractCatalogImages(
}
}
const plugins: PluginMarketplace['plugins'] = []
- for (const entry of marketplace.plugins) {
+ for (const listed of marketplace.plugins) {
+ const { entry, readBlob: read } = fill
+ ? await fill(listed, readBlob)
+ : { entry: listed, readBlob }
if (!entry.releases) {
plugins.push(entry)
continue
@@ -78,7 +99,7 @@ export async function extractCatalogImages(
continue
}
const { images, ...rest } = release
- const kept = await keep(images)
+ const kept = await keep(images, read)
releases.push(Object.keys(kept).length ? { ...rest, images: kept } : rest)
}
plugins.push({ ...entry, releases })
diff --git a/src/main/plugins/catalog/plugin-catalog-monorepo-images.test.ts b/src/main/plugins/catalog/plugin-catalog-monorepo-images.test.ts
index c244a329792..3ef9dd7000c 100644
--- a/src/main/plugins/catalog/plugin-catalog-monorepo-images.test.ts
+++ b/src/main/plugins/catalog/plugin-catalog-monorepo-images.test.ts
@@ -1,6 +1,9 @@
import { createHash } from 'node:crypto'
import { describe, expect, it } from 'vitest'
-import type { PluginMarketplace } from '../../../shared/plugins/catalog/plugin-marketplace'
+import type {
+ PluginMarketplace,
+ PluginMarketplaceEntry
+} from '../../../shared/plugins/catalog/plugin-marketplace'
import { extractCatalogImages } from './plugin-catalog-image-extraction'
import { fillMonorepoReleaseImages } from './plugin-catalog-monorepo-images'
@@ -65,11 +68,19 @@ const files: Record<string, Buffer> = {
'plugins/midnight-theme/images/cover.png': cover
}
const read = async (path: string): Promise<Buffer | null> => files[path] ?? null
+const fill = (entry: PluginMarketplaceEntry) =>
+ fillMonorepoReleaseImages(entry, CATALOG_URL, read).then((filled) => filled.entry)
describe('fillMonorepoReleaseImages', () => {
it('lists the manifest cover for a same-repository release published without images', async () => {
- const filled = await fillMonorepoReleaseImages(catalog(CATALOG_URL), CATALOG_URL, read)
- const extracted = await extractCatalogImages(filled, read)
+ const reads: string[] = []
+ const counted = async (path: string): Promise<Buffer | null> => {
+ reads.push(path)
+ return read(path)
+ }
+ const extracted = await extractCatalogImages(catalog(CATALOG_URL), counted, (entry, blob) =>
+ fillMonorepoReleaseImages(entry, CATALOG_URL, blob)
+ )
expect(extracted.marketplace.plugins[0]?.releases?.[0]?.images).toEqual({
cover: {
path: 'plugins/midnight-theme/images/cover.png',
@@ -80,12 +91,13 @@ describe('fillMonorepoReleaseImages', () => {
}
})
expect(extracted.images).toEqual([cover])
+ expect(reads.filter((path) => path.endsWith('cover.png'))).toHaveLength(1)
})
it('leaves plugins hosted elsewhere and releases that declare images untouched', async () => {
- const elsewhere = catalog('https://github.com/acme/midnight.git')
- expect(await fillMonorepoReleaseImages(elsewhere, CATALOG_URL, read)).toEqual(elsewhere)
- const declared = catalog(CATALOG_URL, {})
- expect(await fillMonorepoReleaseImages(declared, CATALOG_URL, read)).toEqual(declared)
+ const elsewhere = catalog('https://github.com/acme/midnight.git').plugins[0]!
+ expect(await fill(elsewhere)).toEqual(elsewhere)
+ const declared = catalog(CATALOG_URL, {}).plugins[0]!
+ expect(await fill(declared)).toEqual(declared)
})
})
diff --git a/src/main/plugins/catalog/plugin-catalog-monorepo-images.ts b/src/main/plugins/catalog/plugin-catalog-monorepo-images.ts
index 0e84f465733..cf6e751e6d5 100644
--- a/src/main/plugins/catalog/plugin-catalog-monorepo-images.ts
+++ b/src/main/plugins/catalog/plugin-catalog-monorepo-images.ts
@@ -1,6 +1,6 @@
import {
isSameGitRepository,
- type PluginMarketplace
+ type PluginMarketplaceEntry
} from '../../../shared/plugins/catalog/plugin-marketplace'
import { catalogImagesFromManifest } from '../../../shared/plugins/images/plugin-manifest-catalog-images'
import { sha256Hex } from '../plugin-image-cache'
@@ -11,37 +11,49 @@ const MANIFEST_MAX_BYTES = 256 * 1024
/**
* A catalog that keeps its plugins in its own repository already holds their images, so a newest
* release listed without `images` borrows the manifest's from the catalog commit. Extraction then
- * checks those bytes like any declared image.
+ * checks those bytes like any declared image, through the returned reader so they are not read twice.
*/
export async function fillMonorepoReleaseImages(
- marketplace: PluginMarketplace,
+ entry: PluginMarketplaceEntry,
catalogUrl: string,
readBlob: CatalogBlobReader
-): Promise<PluginMarketplace> {
- const plugins: PluginMarketplace['plugins'] = []
- for (const entry of marketplace.plugins) {
- const [newest, ...older] = entry.releases ?? []
- const prefix = entry.source.path
- if (!newest || newest.images || !prefix || !isSameGitRepository(entry.source.url, catalogUrl)) {
- plugins.push(entry)
- continue
- }
- const manifestBytes = await readBlob(`${prefix}/orca-plugin.json`, MANIFEST_MAX_BYTES).catch(
- () => null
- )
- let manifest: unknown = null
- try {
- manifest = manifestBytes ? JSON.parse(manifestBytes.toString('utf8')) : null
- } catch {
- manifest = null
+): Promise<{ entry: PluginMarketplaceEntry; readBlob: CatalogBlobReader }> {
+ const [newest, ...older] = entry.releases ?? []
+ const prefix = entry.source.path
+ if (!newest || newest.images || !prefix || !isSameGitRepository(entry.source.url, catalogUrl)) {
+ return { entry, readBlob }
+ }
+ const manifestBytes = await readBlob(`${prefix}/orca-plugin.json`, MANIFEST_MAX_BYTES).catch(
+ () => null
+ )
+ let manifest: unknown = null
+ try {
+ manifest = manifestBytes ? JSON.parse(manifestBytes.toString('utf8')) : null
+ } catch {
+ manifest = null
+ }
+ const read = new Map<string, Buffer>()
+ const images = await catalogImagesFromManifest({
+ manifest,
+ prefix,
+ read: async (path, maxBytes) => {
+ const bytes = await readBlob(path, maxBytes)
+ if (bytes) {
+ read.set(path, bytes)
+ }
+ return bytes
+ },
+ sha256: (bytes) => sha256Hex(Buffer.from(bytes))
+ })
+ if (!images) {
+ return { entry, readBlob }
+ }
+ return {
+ entry: { ...entry, releases: [{ ...newest, images }, ...older] },
+ // Why the size check: a pinned blob larger than `maxBytes` reads as null, as readBlob would.
+ readBlob: async (path, maxBytes) => {
+ const bytes = read.get(path)
+ return bytes ? (bytes.byteLength <= maxBytes ? bytes : null) : readBlob(path, maxBytes)
}
- const images = await catalogImagesFromManifest({
- manifest,
- prefix,
- read: readBlob,
- sha256: (bytes) => sha256Hex(Buffer.from(bytes))
- })
- plugins.push(images ? { ...entry, releases: [{ ...newest, images }, ...older] } : entry)
}
- return { ...marketplace, plugins }
}
diff --git a/src/main/plugins/catalog/plugin-marketplace-fetch.ts b/src/main/plugins/catalog/plugin-marketplace-fetch.ts
index 22930f64d45..62063846914 100644
--- a/src/main/plugins/catalog/plugin-marketplace-fetch.ts
+++ b/src/main/plugins/catalog/plugin-marketplace-fetch.ts
@@ -79,12 +79,11 @@ async function readMarketplaceAtCommit(
})
const readBlob = (path: string, maxBytes: number): Promise<Buffer | null> =>
readCatalogBlob(repository, commit, path, maxBytes)
- const marketplace = await fillMonorepoReleaseImages(
+ return extractCatalogImages(
parsePluginMarketplaceIndex(filename, bytes.stdout),
- catalogUrl,
- readBlob
+ readBlob,
+ (entry, read) => fillMonorepoReleaseImages(entry, catalogUrl, read)
)
- return extractCatalogImages(marketplace, readBlob)
}
/** One file from the catalog commit, refused before reading when it is larger than allowed. */
diff --git a/src/main/plugins/catalog/plugin-marketplace-installer.ts b/src/main/plugins/catalog/plugin-marketplace-installer.ts
index 32db4f4831b..4484f9df43f 100644
--- a/src/main/plugins/catalog/plugin-marketplace-installer.ts
+++ b/src/main/plugins/catalog/plugin-marketplace-installer.ts
@@ -31,7 +31,10 @@ import type {
} from './plugin-marketplace-service'
import { marketplaceSourceId } from './plugin-marketplace-store'
import { isSamePluginSource } from '../../../shared/plugins/catalog/plugin-marketplace'
-import type { PluginInstallSource } from '../../../shared/plugins/installation/plugin-install-lockfile'
+import type {
+ PluginInstallSource,
+ PluginLockfile
+} from '../../../shared/plugins/installation/plugin-install-lockfile'
export type PluginMarketplaceInstallPreview = {
marketplaceSourceId: string
@@ -190,13 +193,17 @@ export class PluginMarketplaceInstaller {
return result.ok && repositoryMoved ? { ...result, repositoryMoved: true } : result
}
+ /** Why: one read lets a pass over every plugin skip a full lockfile recovery per plugin. */
+ readInstallLockfile(): Promise<PluginLockfile> {
+ return readPluginLockfile(getUserPluginsDir(this.userDataPath))
+ }
+
/** The catalog an installed plugin came from, or null when it was not a marketplace install. */
private async readMarketplaceInstall(
- pluginKey: string
+ pluginKey: string,
+ lock?: PluginLockfile
): Promise<{ sourceId: string; plugin: MarketplaceInstallSource['plugin'] } | null> {
- const entry = (await readPluginLockfile(getUserPluginsDir(this.userDataPath))).plugins[
- pluginKey
- ]
+ const entry = (lock ?? (await this.readInstallLockfile())).plugins[pluginKey]
if (entry?.source.kind !== 'marketplace') {
return null
}
@@ -219,11 +226,14 @@ export class PluginMarketplaceInstaller {
}
/** The own-catalog listing an installed plugin would update from, read from caches only. */
- async findInstalledUpdateListing(pluginKey: string): Promise<{
+ async findInstalledUpdateListing(
+ pluginKey: string,
+ lock?: PluginLockfile
+ ): Promise<{
listing: PluginMarketplaceListing
officialCatalog: boolean
} | null> {
- const installed = await this.readMarketplaceInstall(pluginKey)
+ const installed = await this.readMarketplaceInstall(pluginKey, lock)
const listing = installed
? await this.marketplace.findPlugin(installed.sourceId, pluginKey)
: null
diff --git a/src/main/project-runtime-git-router.ts b/src/main/project-runtime-git-router.ts
index b2c851b7bfc..bb7d4f44390 100644
--- a/src/main/project-runtime-git-router.ts
+++ b/src/main/project-runtime-git-router.ts
@@ -183,7 +183,15 @@ function readRealpath(folder: string): string | null {
}
function buildRoutes(store: ProjectRuntimeGitRouterStore): Route[] {
- const projects = store.getProjects()
+ const ownerByRepoId = new Map<string, Project>()
+ for (const project of store.getProjects()) {
+ for (const repoId of project.sourceRepoIds) {
+ // First owner wins.
+ if (!ownerByRepoId.has(repoId)) {
+ ownerByRepoId.set(repoId, project)
+ }
+ }
+ }
const globalDefault = store.getSettings().localWindowsRuntimeDefault
const localRepos = new Map(
store
@@ -192,7 +200,10 @@ function buildRoutes(store: ProjectRuntimeGitRouterStore): Route[] {
.map((repo) => [repo.id, repo])
)
const distroByRepo = new Map(
- [...localRepos.values()].map((repo) => [repo.id, wslGitDistro(repo, projects, globalDefault)])
+ [...localRepos.values()].map((repo) => [
+ repo.id,
+ wslGitDistro(repo, ownerByRepoId, globalDefault)
+ ])
)
// Host-Git routes stay too, so a project nested in a WSL one keeps its own Git.
const routes: Route[] = [...localRepos.values()].map((repo) => ({
@@ -219,13 +230,13 @@ function buildRoutes(store: ProjectRuntimeGitRouterStore): Route[] {
*/
function wslGitDistro(
repo: Repo,
- projects: readonly Project[],
+ ownerByRepoId: ReadonlyMap<string, Project>,
globalWindowsRuntimeDefault: unknown
): string | undefined {
if (isFolderRepo(repo)) {
return undefined
}
- const project = projects.find((entry) => entry.sourceRepoIds.includes(repo.id))
+ const project = ownerByRepoId.get(repo.id)
const resolution = resolveProjectExecutionRuntime({
appPlatform: 'win32',
projectId: project?.id ?? repo.id,
diff --git a/src/main/wsl/wsl-drive-unc-conversion-run.test.ts b/src/main/wsl/wsl-drive-unc-conversion-run.test.ts
index 1e1bfabc142..73d961a6bd3 100644
--- a/src/main/wsl/wsl-drive-unc-conversion-run.test.ts
+++ b/src/main/wsl/wsl-drive-unc-conversion-run.test.ts
@@ -93,6 +93,50 @@ describe('startWslDriveUncConversion', () => {
expect(run.restart).toHaveBeenCalledOnce()
})
+ const savedMeta = {
+ instanceId: 'saved',
+ displayName: 'feature',
+ comment: '',
+ linkedIssue: null,
+ linkedPR: null,
+ linkedLinearIssue: null,
+ isArchived: false,
+ isUnread: false,
+ isPinned: false,
+ sortOrder: 0,
+ lastActivityAt: 0,
+ hostId: 'local' as const
+ }
+ const ubuntu = String.raw`\\wsl.localhost\Ubuntu\mnt\c`
+ it.each([
+ { shape: 'inside its folder', parent: UNC, nested: `${UNC}\\nested`, savedWorktree: null },
+ { shape: 'at a drive root', parent: ubuntu, nested: `${ubuntu}\\src`, savedWorktree: null },
+ {
+ shape: 'inside its saved worktree',
+ parent: UNC,
+ nested: `${ubuntu}\\feature\\nested`,
+ savedWorktree: `${ubuntu}\\feature`
+ }
+ ])(
+ 'converts a project nested $shape with its parent',
+ async ({ parent, nested, savedWorktree }) => {
+ const value = state()
+ value.repos[0].path = parent
+ value.repos.push({ id: 'repo-b', path: nested, displayName: 'b', badgeColor: '', addedAt: 0 })
+ value.projects.push({ ...value.projects[0], id: 'repo-b', sourceRepoIds: ['repo-b'] })
+ if (savedWorktree) {
+ value.worktreeMeta = { [`repo-a::${savedWorktree}`]: savedMeta }
+ }
+ const run = deps({ readProfileState: async () => value })
+ expect(await startWslDriveUncConversion(run, REQUEST)).toMatchObject({
+ outcome: 'restarting'
+ })
+ expect(listWslDriveUncConversions(root)).toEqual([
+ expect.objectContaining({ repoIds: ['repo-a', 'repo-b'] })
+ ])
+ }
+ )
+
it('refuses, pausing nothing, when the distro does not show /mnt/c as drive C:', async () => {
for (const mounts of [null, [{ mountPoint: '/mnt/c', windowsRoot: null }]]) {
const run = deps({ readDriveMounts: async () => mounts })
diff --git a/src/main/wsl/wsl-drive-unc-conversion-run.ts b/src/main/wsl/wsl-drive-unc-conversion-run.ts
index 27755af8148..dd7e515f88c 100644
--- a/src/main/wsl/wsl-drive-unc-conversion-run.ts
+++ b/src/main/wsl/wsl-drive-unc-conversion-run.ts
@@ -24,8 +24,12 @@ import {
type WslDriveProjectDeps
} from './wsl-drive-project-windows-git'
import { WslDriveUncKeyCollisionError } from './wsl-drive-unc-identity-rewrite'
-import { collectWslDriveUncScope, wslUncDrivePathToWindows } from './wsl-drive-unc-project-scope'
-import { rewriteWslDriveUncState } from './wsl-drive-unc-state-rewrite'
+import {
+ collectWslDriveUncScope,
+ withNestedWslDriveUncProjects,
+ wslUncDrivePathToWindows
+} from './wsl-drive-unc-project-scope'
+import { rewriteWslDriveUncState, wslDriveUncRewriteRoots } from './wsl-drive-unc-state-rewrite'
import type { WindowsDriveMount } from '../runtime/wsl-guest-drive-mountinfo'
export type WslDriveUncConversionRunDeps = Pick<
@@ -138,7 +142,15 @@ function checkScope(
if (repoIds.length + folderWorkspaceIds.length === 0 && blockers.length === 0) {
blockers.push({ kind: 'not-convertible', id: '', reason: 'not-in-scope' })
}
- return blockers.length > 0 ? { blockers } : { repoIds, folderWorkspaceIds }
+ // Bare paths are re-keyed by folder, so a nested project's rows would move without its ids.
+ return blockers.length > 0
+ ? { blockers }
+ : withNestedWslDriveUncProjects(
+ scope,
+ request.distro,
+ { repoIds, folderWorkspaceIds },
+ (project) => wslDriveUncRewriteRoots(state, { distro: request.distro, ...project })
+ )
}
/** Windows Git runs in the drive path, which is the same folder the distro shows. */
diff --git a/src/main/wsl/wsl-drive-unc-project-scope.ts b/src/main/wsl/wsl-drive-unc-project-scope.ts
index 3173e33d86a..d2a5567e295 100644
--- a/src/main/wsl/wsl-drive-unc-project-scope.ts
+++ b/src/main/wsl/wsl-drive-unc-project-scope.ts
@@ -127,14 +127,8 @@ function refuseOverlaps(scope: WslDriveUncScope, repos: readonly Repo[], distro:
.filter((entry) => entry.reason !== 'duplicate-windows-project')
.map((entry) => entry.id)
)
- const comparable = (repo: Repo): string[] =>
- wslMoveRepoPaths(repo).flatMap((path) => {
- const drive = wslUncDrivePathToWindows(path, distro)
- return drive ? [normalizeRuntimePathForComparison(drive)] : []
- })
+ const comparable = (repo: Repo): string[] => driveRoots(wslMoveRepoPaths(repo), distro)
const refusedRoots = repos.filter((repo) => refusedIds.has(repo.id)).flatMap(comparable)
- const nests = (left: string, right: string): boolean =>
- left === right || left.startsWith(`${right}/`) || right.startsWith(`${left}/`)
const overlapping = new Set(
repos
.filter((repo) => scope.repoIds.includes(repo.id))
@@ -149,6 +143,62 @@ function refuseOverlaps(scope: WslDriveUncScope, repos: readonly Repo[], distro:
}
}
+/** The picked projects and every convertible one nesting with them, which must convert together. */
+export function withNestedWslDriveUncProjects(
+ scope: WslDriveUncScope,
+ distro: string,
+ picked: { repoIds: readonly string[]; folderWorkspaceIds: readonly string[] },
+ /** The folders a conversion of just this project rewrites, its saved worktrees included. */
+ rewriteRoots: (project: { repoIds: string[]; folderWorkspaceIds: string[] }) => string[]
+): { repoIds: string[]; folderWorkspaceIds: string[] } {
+ const repoIds = new Set(picked.repoIds)
+ const folderWorkspaceIds = new Set(picked.folderWorkspaceIds)
+ const candidates = [
+ ...scope.repoIds.map((id) => ({
+ ids: repoIds,
+ id,
+ roots: driveRoots(rewriteRoots({ repoIds: [id], folderWorkspaceIds: [] }), distro)
+ })),
+ ...scope.folderWorkspaceIds.map((id) => ({
+ ids: folderWorkspaceIds,
+ id,
+ roots: driveRoots(rewriteRoots({ repoIds: [], folderWorkspaceIds: [id] }), distro)
+ }))
+ ]
+ for (let added = true; added;) {
+ added = false
+ const roots = candidates
+ .filter((entry) => entry.ids.has(entry.id))
+ .flatMap((entry) => entry.roots)
+ for (const entry of candidates) {
+ if (
+ !entry.ids.has(entry.id) &&
+ entry.roots.some((root) => roots.some((other) => nests(root, other)))
+ ) {
+ entry.ids.add(entry.id)
+ added = true
+ }
+ }
+ }
+ return { repoIds: [...repoIds], folderWorkspaceIds: [...folderWorkspaceIds] }
+}
+
+function driveRoots(paths: readonly string[], distro: string): string[] {
+ return paths.flatMap((path) => {
+ const drive = wslUncDrivePathToWindows(path, distro)
+ return drive ? [normalizeRuntimePathForComparison(drive)] : []
+ })
+}
+
+function nests(left: string, right: string): boolean {
+ return left === right || isInside(left, right) || isInside(right, left)
+}
+
+// Why: a drive root normalizes to `c:/`, which already ends in the separator.
+function isInside(path: string, folder: string): boolean {
+ return path.startsWith(folder.endsWith('/') ? folder : `${folder}/`)
+}
+
/** The worktree id a converted project's worktree gets: same repo id, drive path. */
export function wslDriveUncWorktreeId(worktreeId: string, distro: string): string {
return rewriteWorktreeIdPath(worktreeId, (path) => wslUncDrivePathToWindows(path, distro) ?? path)
diff --git a/src/main/wsl/wsl-drive-unc-state-rewrite.ts b/src/main/wsl/wsl-drive-unc-state-rewrite.ts
index 496556b0c87..9f6f23d2721 100644
--- a/src/main/wsl/wsl-drive-unc-state-rewrite.ts
+++ b/src/main/wsl/wsl-drive-unc-state-rewrite.ts
@@ -45,26 +45,13 @@ export function rewriteWslDriveUncState(
): WslDriveUncStateRewrite {
const repoIds = new Set(scope.repoIds)
const folderWorkspaceIds = new Set(scope.folderWorkspaceIds)
- const roots = [
- ...saved.repos.filter((repo) => repoIds.has(repo.id)).flatMap(wslMoveRepoPaths),
- ...saved.folderWorkspaces
- .filter((folder) => folderWorkspaceIds.has(folder.id))
- .map((folder) => folder.folderPath)
- ]
- const ids = createWslDriveUncRewriter({
- distro: scope.distro,
- repoIds,
- folderWorkspaceIds,
- roots
- })
- const worktreeIds = collectRewrittenWorktreeIds(saved, ids)
+ const { roots, worktreeIds } = collectRewriteRoots(saved, scope)
const state = withoutDiscoveryShadows(saved, worktreeIds)
- // A worktree outside the repo's own folders is still the project's.
const rewriter = createWslDriveUncRewriter({
distro: scope.distro,
repoIds,
folderWorkspaceIds,
- roots: [...roots, ...[...worktreeIds.keys()].flatMap(worktreePathOf)]
+ roots
})
const next: PersistedState = { ...state }
for (const [field, disposition] of Object.entries(WSL_DRIVE_UNC_STATE_DISPOSITIONS)) {
@@ -103,6 +90,37 @@ function isStateField(field: string): field is keyof PersistedState {
}
/** Every converted worktree id the rewritten fields name, old to new. */
+/** The folders whose bare paths a conversion of this scope rewrites. */
+export function wslDriveUncRewriteRoots(
+ saved: PersistedState,
+ scope: WslDriveUncStateScope
+): string[] {
+ return collectRewriteRoots(saved, scope).roots
+}
+
+function collectRewriteRoots(
+ saved: PersistedState,
+ scope: WslDriveUncStateScope
+): { roots: string[]; worktreeIds: Map<string, string> } {
+ const repoIds = new Set(scope.repoIds)
+ const folderWorkspaceIds = new Set(scope.folderWorkspaceIds)
+ const roots = [
+ ...saved.repos.filter((repo) => repoIds.has(repo.id)).flatMap(wslMoveRepoPaths),
+ ...saved.folderWorkspaces
+ .filter((folder) => folderWorkspaceIds.has(folder.id))
+ .map((folder) => folder.folderPath)
+ ]
+ const ids = createWslDriveUncRewriter({
+ distro: scope.distro,
+ repoIds,
+ folderWorkspaceIds,
+ roots
+ })
+ const worktreeIds = collectRewrittenWorktreeIds(saved, ids)
+ // A worktree outside the repo's own folders is still the project's.
+ return { roots: [...roots, ...[...worktreeIds.keys()].flatMap(worktreePathOf)], worktreeIds }
+}
+
function collectRewrittenWorktreeIds(
state: PersistedState,
rewriter: WslDriveUncRewriter
diff --git a/src/renderer/src/components/editor/editor-bytes-documents.test.ts b/src/renderer/src/components/editor/editor-bytes-documents.test.ts
index 4a27e5d5bc4..4c6dc954b85 100644
--- a/src/renderer/src/components/editor/editor-bytes-documents.test.ts
+++ b/src/renderer/src/components/editor/editor-bytes-documents.test.ts
@@ -152,6 +152,20 @@ describe('binary custom editor reloads', () => {
})
describe('binary custom editor tabs', () => {
+ it('skips the tab sweep on store writes that leave the tabs and bytes alone', () => {
+ storeListener.current?.(state, { ...state, openFiles: [...state.openFiles] })
+ const find = vi.spyOn(state.openFiles, 'find')
+ for (let i = 0; i < 3; i++) {
+ storeListener.current?.(state, { ...state })
+ }
+ expect(find).not.toHaveBeenCalled()
+ setEditorBytesDraft('book', edited)
+ find.mockClear()
+ storeListener.current?.(state, { ...state })
+ expect(find).toHaveBeenCalled()
+ find.mockRestore()
+ })
+
it('ignores a read that started before an edit and save it does not include', async () => {
const editsAtRead = editorBytesEdits('book')
setEditorBytesDraft('book', edited)
diff --git a/src/renderer/src/components/editor/editor-bytes-documents.ts b/src/renderer/src/components/editor/editor-bytes-documents.ts
index 851cd979be3..49736bdbb44 100644
--- a/src/renderer/src/components/editor/editor-bytes-documents.ts
+++ b/src/renderer/src/components/editor/editor-bytes-documents.ts
@@ -18,15 +18,31 @@ import { bytesDocumentBoxes } from './editor-bytes-document-boxes'
const listeners = new Set<() => void>()
let unsubscribeStore: (() => void) | null = null
+// Why: boxes change outside the store, so a store write that leaves the tabs alone may still need a sweep.
+let boxesChangedSinceSweep = false
-function notify(): void {
+function notifyListeners(): void {
for (const listener of listeners) {
listener()
}
}
+function notify(): void {
+ boxesChangedSinceSweep = true
+ notifyListeners()
+}
+
/** Drops a draft once its tab is clean (saved, reverted, discarded) and the entry once it closes. */
function dropSettledDrafts(state: AppState, previous: AppState): void {
+ if (
+ !boxesChangedSinceSweep &&
+ state.openFiles === previous.openFiles &&
+ state.editorBufferIdOf === previous.editorBufferIdOf &&
+ state.editorBufferViews === previous.editorBufferViews
+ ) {
+ return
+ }
+ boxesChangedSinceSweep = false
let changed = false
const isOpen = (id: string): boolean => state.openFiles.some((file) => file.id === id)
for (const [fileId, box] of bytesDocumentBoxes) {
@@ -51,7 +67,7 @@ function dropSettledDrafts(state: AppState, previous: AppState): void {
unsubscribeStore = null
}
if (changed) {
- notify()
+ notifyListeners()
}
}
diff --git a/src/renderer/src/components/native-chat/native-chat-file-link.ts b/src/renderer/src/components/native-chat/native-chat-file-link.ts
index 56101563f42..bfdfb57f1cc 100644
--- a/src/renderer/src/components/native-chat/native-chat-file-link.ts
+++ b/src/renderer/src/components/native-chat/native-chat-file-link.ts
@@ -94,7 +94,7 @@ export function resolveNativeChatFileLinkContext(
type FileLinkContextInputState = WorktreeRuntimeOwnerState & NativeChatTabDirectoryState
// Every field the directory and owner resolvers read.
-const FILE_LINK_CONTEXT_INPUT_KEYS = [
+export const FILE_LINK_CONTEXT_INPUT_KEYS = [
'repos',
'settings',
'worktreesByRepo',
diff --git a/src/renderer/src/components/native-chat/native-chat-github-repo.test.ts b/src/renderer/src/components/native-chat/native-chat-github-repo.test.ts
new file mode 100644
index 00000000000..ff6230435f8
--- /dev/null
+++ b/src/renderer/src/components/native-chat/native-chat-github-repo.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest'
+import { getDefaultSettings } from '../../../../shared/constants'
+import { createNativeChatRepoSelector } from './native-chat-github-repo'
+import { repoFixture, worktreeFixture } from './native-chat-workspace-test-fixtures'
+
+describe('createNativeChatRepoSelector', () => {
+ it('skips the repo scan on unrelated writes and re-resolves when a route input changes', () => {
+ const repo = repoFixture({ kind: 'git' })
+ let scans = 0
+ const repos = [repo]
+ const filter = repos.filter.bind(repos)
+ Object.defineProperty(repos, 'filter', {
+ value: (predicate: Parameters<typeof filter>[0]) => {
+ scans++
+ return filter(predicate)
+ }
+ })
+ const base = {
+ repos,
+ worktreesByRepo: { repo: [worktreeFixture('wt-1', '/repo/worktree')] },
+ detectedWorktreesByRepo: {},
+ folderWorkspaces: [],
+ floatingWorkspacePath: null,
+ settings: { ...getDefaultSettings('/home/me'), activeRuntimeEnvironmentId: null }
+ }
+ const select = createNativeChatRepoSelector('wt-1')
+
+ expect(select(base)).toBe(repo)
+ expect(select({ ...base })).toBe(repo)
+ expect(scans).toBe(1)
+
+ expect(select({ ...base, worktreesByRepo: {} })).toBeNull()
+ })
+})
diff --git a/src/renderer/src/components/native-chat/native-chat-github-repo.ts b/src/renderer/src/components/native-chat/native-chat-github-repo.ts
index 75d6f246d0e..5ff1f4ccabc 100644
--- a/src/renderer/src/components/native-chat/native-chat-github-repo.ts
+++ b/src/renderer/src/components/native-chat/native-chat-github-repo.ts
@@ -9,6 +9,9 @@ import {
repoUpstreamIdentityKey
} from '@/lib/repo-slug-cache'
import { getKnownExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner'
+import type { AppState } from '@/store/types'
+import type { WorktreeRuntimeOwnerState } from '@/lib/worktree-runtime-owner-state'
+import { FILE_LINK_CONTEXT_INPUT_KEYS } from './native-chat-file-link'
import type { Repo } from '../../../../shared/repo-types'
import { getRepoExecutionHostId, isUnresolvedOwnerHostId } from '../../../../shared/execution-host'
import {
@@ -38,27 +41,55 @@ function ownerRepoFromKey(key: string): { owner: string; repo: string } | null {
return owner && repo ? { owner, repo } : null
}
+type NativeChatRepoState = Pick<
+ AppState,
+ | 'repos'
+ | 'worktreesByRepo'
+ | 'detectedWorktreesByRepo'
+ | 'folderWorkspaces'
+ | 'floatingWorkspacePath'
+> &
+ WorktreeRuntimeOwnerState
+
+function resolveNativeChatRepo(
+ state: NativeChatRepoState,
+ worktreeId: string | undefined
+): Repo | null {
+ // The same owner the chat's file links route to; twins on other hosts must not answer for it.
+ const hostId = worktreeId ? getKnownExecutionHostIdForWorktree(state, worktreeId) : null
+ if (!worktreeId || !hostId || isUnresolvedOwnerHostId(hostId)) {
+ return null
+ }
+ const worktree = findKnownWorktreeById(state, worktreeId, hostId)
+ if (!worktree) {
+ return null
+ }
+ const owners = state.repos.filter(
+ (candidate) => candidate.id === worktree.repoId && getRepoExecutionHostId(candidate) === hostId
+ )
+ const found = owners.length === 1 ? owners[0] : null
+ return found && (!found.kind || found.kind === 'git') ? found : null
+}
+
+export function createNativeChatRepoSelector(worktreeId: string | undefined) {
+ let inputs: unknown[] | null = null
+ let repo: Repo | null = null
+ // Retained chats all subscribe; unrelated store writes must not re-resolve the owner or scan repos.
+ return (state: NativeChatRepoState): Repo | null => {
+ if (!inputs || FILE_LINK_CONTEXT_INPUT_KEYS.some((key, i) => state[key] !== inputs?.[i])) {
+ inputs = FILE_LINK_CONTEXT_INPUT_KEYS.map((key) => state[key])
+ repo = resolveNativeChatRepo(state, worktreeId)
+ }
+ return repo
+ }
+}
+
/** The git repo behind the chat's workspace, with its GitHub remotes once resolved. */
export function useNativeChatGitHubRepo(
worktreeId: string | undefined
): NativeChatGitHubRepo | null {
- const repo = useAppStore((state) => {
- // The same owner the chat's file links route to; twins on other hosts must not answer for it.
- const hostId = worktreeId ? getKnownExecutionHostIdForWorktree(state, worktreeId) : null
- if (!worktreeId || !hostId || isUnresolvedOwnerHostId(hostId)) {
- return null
- }
- const worktree = findKnownWorktreeById(state, worktreeId, hostId)
- if (!worktree) {
- return null
- }
- const owners = state.repos.filter(
- (candidate) =>
- candidate.id === worktree.repoId && getRepoExecutionHostId(candidate) === hostId
- )
- const found = owners.length === 1 ? owners[0] : null
- return found && (!found.kind || found.kind === 'git') ? found : null
- })
+ const selectRepo = useMemo(() => createNativeChatRepoSelector(worktreeId), [worktreeId])
+ const repo = useAppStore(selectRepo)
const [resolved, setResolved] = useState(() => ({
repo,
originKey: readCachedOriginKey(repo),