mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 09:46:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9946c2598d |
@@ -146,6 +146,22 @@ quietly relying on:
|
||||
|
||||
The fix for transforms is Gotcha 3. The fix for context is Gotcha 7.
|
||||
|
||||
### The portal patch
|
||||
|
||||
`patches/@gorhom+portal+1.0.14.patch` moves portal state out of the provider's
|
||||
context value and into a store each `PortalHost` subscribes to. Upstream keeps
|
||||
every host's portals in one context value at the app root, so each portal mount,
|
||||
update and unmount changed that value and React searched every mounted fiber
|
||||
for consumers. That cost grows with the retained panels: a hover card took
|
||||
about 3 ms of it in a fresh window and 16 ms after a few hours. With the store,
|
||||
a portal change renders only its own host.
|
||||
|
||||
Do not put per-overlay state in a context that wraps the app for the same
|
||||
reason. Give the consumers a store to subscribe to.
|
||||
|
||||
The patch also keys each portal in its host (upstream PR #62). Without the key,
|
||||
closing one overlay remounted every later overlay in the same host.
|
||||
|
||||
## Gotcha 3 — Keyboard layout and portal anchors
|
||||
|
||||
`composer/dock` owns the stationary viewport, bottom-anchored surface, composer
|
||||
|
||||
+10
-1
@@ -86,7 +86,7 @@ mounts—never at module evaluation time.
|
||||
|
||||
## Dynamic Pixel Styles On Web
|
||||
|
||||
Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and appends a CSS rule to `#unistyles-web`; those rules are not reclaimed during the page lifetime, so pointer-driven positioning can turn into steady stylesheet growth.
|
||||
Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and inserts a CSS rule into `#unistyles-web` for it, then deletes the rule when the last element using it unmounts. Pointer-driven positioning turns into a rule insert and delete per move.
|
||||
|
||||
Use the inline style escape hatch below for high-churn values. Do not split a component into plain/web/native variants just to keep one measured value out of the CSS registry. Raw DOM wrappers are reserved for real DOM infrastructure, such as terminal hosts, virtualized web rows, or third-party drag wrappers.
|
||||
|
||||
@@ -224,6 +224,7 @@ Quick confirmation in DevTools console:
|
||||
```js
|
||||
[...document.styleSheets]
|
||||
.flatMap((s) => [...(s.cssRules || [])])
|
||||
.flatMap((r) => (r.cssRules ? [...r.cssRules] : [r]))
|
||||
.map((r) => r.cssText)
|
||||
.filter((t) => t.includes("unistyles") && t.includes("> *"));
|
||||
```
|
||||
@@ -366,6 +367,14 @@ colors. Keep this patch until upstream reads the scheme through separate lists.
|
||||
The desktop browser E2E checks both transition directions in an isolated Electron
|
||||
process, because Playwright's focus emulation prevents real hidden-page behavior.
|
||||
|
||||
The stylesheet patch backports upstream PR #1354 (3.8.0). Unistyles 3.2.4 rewrote
|
||||
the whole text of `#unistyles-web` whenever a class was added or removed, and
|
||||
the browser then restyled the entire document: about 5 ms each time, several
|
||||
times for one hover card. The backport changes one CSSOM rule per class instead.
|
||||
The tag therefore has no text; read its rules through `sheet.cssRules`. Classes
|
||||
without a media query sit inside an `@media all` group. Assert on the stylesheet
|
||||
in E2E with `packages/app/e2e/support/helpers/shared-stylesheet.ts`.
|
||||
|
||||
Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in
|
||||
`patches/` is inert unless that script knows which installed package activates
|
||||
it.
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
|
||||
interface DragMeasurement {
|
||||
observer: MutationObserver;
|
||||
stylesheetMutations: number;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__PASEO_EXPLORER_DRAG_MEASUREMENT__?: DragMeasurement;
|
||||
}
|
||||
}
|
||||
import {
|
||||
readSharedStylesheetChanges,
|
||||
rememberSharedStylesheet,
|
||||
} from "../support/helpers/shared-stylesheet";
|
||||
|
||||
async function waitForResizePaint(page: Page): Promise<void> {
|
||||
await page.evaluate(
|
||||
@@ -23,23 +16,8 @@ async function waitForResizePaint(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
async function beginResizeMeasurement(page: Page): Promise<void> {
|
||||
await page.evaluate(() => {
|
||||
const stylesheet = document.getElementById("unistyles-web");
|
||||
if (!stylesheet) throw new Error("Shared stylesheet is missing");
|
||||
globalThis.__PASEO_RESET_RENDER_PROFILE__!();
|
||||
const measurement: DragMeasurement = {
|
||||
stylesheetMutations: 0,
|
||||
observer: new MutationObserver((records) => {
|
||||
measurement.stylesheetMutations += records.length;
|
||||
}),
|
||||
};
|
||||
measurement.observer.observe(stylesheet, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
characterData: true,
|
||||
});
|
||||
window.__PASEO_EXPLORER_DRAG_MEASUREMENT__ = measurement;
|
||||
});
|
||||
await page.evaluate(() => globalThis.__PASEO_RESET_RENDER_PROFILE__!());
|
||||
await rememberSharedStylesheet(page);
|
||||
}
|
||||
|
||||
async function previewExplorerResize(page: Page, distance: number) {
|
||||
@@ -61,16 +39,14 @@ async function previewExplorerResize(page: Page, distance: number) {
|
||||
await waitForResizePaint(page);
|
||||
}
|
||||
const during = (await explorer.boundingBox())!.width;
|
||||
const measurement = await page.evaluate(() => {
|
||||
const state = window.__PASEO_EXPLORER_DRAG_MEASUREMENT__!;
|
||||
state.observer.disconnect();
|
||||
return {
|
||||
stylesheetMutations: state.stylesheetMutations,
|
||||
paneRenders: Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {})
|
||||
const measurement = {
|
||||
stylesheetChanges: await readSharedStylesheetChanges(page),
|
||||
paneRenders: await page.evaluate(() =>
|
||||
Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {})
|
||||
.filter(([id]) => id.startsWith("SplitPaneView:"))
|
||||
.reduce((sum, [, reasons]) => sum + (reasons.render ?? 0), 0),
|
||||
};
|
||||
});
|
||||
),
|
||||
};
|
||||
await page.mouse.up();
|
||||
await waitForResizePaint(page);
|
||||
const after = (await explorer.boundingBox())!.width;
|
||||
@@ -92,7 +68,7 @@ async function expectExplorerWidthSurvivesReload(page: Page, width: number): Pro
|
||||
await expect.poll(async () => (await explorer.boundingBox())?.width).toBeCloseTo(width, 0);
|
||||
}
|
||||
|
||||
test("Explorer drag previews without rerendering panes or rewriting the shared stylesheet", async ({
|
||||
test("Explorer drag previews without rerendering panes or changing the shared stylesheet", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
@@ -117,9 +93,9 @@ test("Explorer drag previews without rerendering panes or rewriting the shared s
|
||||
).toBe(true);
|
||||
const grown = await previewExplorerResize(page, -100);
|
||||
const shrunk = await previewExplorerResize(page, 50);
|
||||
expect(grown.stylesheetMutations).toBe(0);
|
||||
expect(grown.stylesheetChanges).toEqual({ added: 0, removed: 0, rebuilt: 0 });
|
||||
expect(grown.paneRenders).toBe(0);
|
||||
expect(shrunk.stylesheetMutations).toBe(0);
|
||||
expect(shrunk.stylesheetChanges).toEqual({ added: 0, removed: 0, rebuilt: 0 });
|
||||
expect(shrunk.paneRenders).toBe(0);
|
||||
await expectExplorerWidthSurvivesReload(page, shrunk.width);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
expectNewWorkspaceControlsEnabled,
|
||||
expectNewWorkspaceProjectSelected,
|
||||
@@ -177,33 +176,6 @@ test.describe("New workspace entry points", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
|
||||
page,
|
||||
}) => {
|
||||
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
|
||||
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
|
||||
await page.getByTestId("new-workspace-project-picker-trigger").click();
|
||||
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
|
||||
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
|
||||
await expect(composer).toBeFocused();
|
||||
|
||||
await page.keyboard.press("Control+N");
|
||||
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
|
||||
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
|
||||
await expect(composer).toBeFocused();
|
||||
} finally {
|
||||
await projectA.cleanup();
|
||||
await projectB.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
expectNewWorkspaceDraft,
|
||||
fillNewWorkspaceDraft,
|
||||
openNewWorkspaceComposer,
|
||||
@@ -110,27 +109,6 @@ test.describe("New workspace: launching a terminal", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openNewWorkspaceComposer(page, {
|
||||
projectKey: workspace.projectKey,
|
||||
projectDisplayName: workspace.projectDisplayName,
|
||||
});
|
||||
await selectLaunchOption(page, BARE_PROFILE.id);
|
||||
await expect(terminalPromptInput(page)).toHaveCount(0);
|
||||
|
||||
// The read-only command preview has nothing to type into, so the picker
|
||||
// hands focus back to the field that opened it.
|
||||
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
|
||||
await projectTrigger.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
|
||||
await expect(projectTrigger).toBeFocused();
|
||||
});
|
||||
|
||||
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -25,6 +25,10 @@ import { projectEquivalenceViewKey } from "../support/helpers/project-view-key";
|
||||
import { escapeRegex } from "../support/helpers/regex";
|
||||
import { openFilesPanel } from "../support/helpers/workspace-tabs";
|
||||
import { seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import {
|
||||
readSharedStylesheetChanges,
|
||||
rememberSharedStylesheet,
|
||||
} from "../support/helpers/shared-stylesheet";
|
||||
|
||||
const GITHUB_REMOTE_URL = "https://github.com/test-owner/test-repo.git";
|
||||
|
||||
@@ -429,6 +433,32 @@ test.describe("Sidebar workspace list", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("workspace hover card opens and closes without rebuilding the shared stylesheet", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-stylesheet-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarProject(page, path.basename(workspace.repoPath));
|
||||
await movePointerAwayFromWorkspaceHoverCard(page);
|
||||
await rememberSharedStylesheet(page);
|
||||
|
||||
await openWorkspaceHoverCard(page, workspace.workspaceId);
|
||||
const opened = await readSharedStylesheetChanges(page);
|
||||
// The card brings styles nothing else on screen uses, so the stylesheet has to grow.
|
||||
expect(opened.added).toBeGreaterThan(0);
|
||||
expect(opened.rebuilt).toBe(0);
|
||||
|
||||
await rememberSharedStylesheet(page);
|
||||
await movePointerAwayFromWorkspaceHoverCard(page);
|
||||
await expectWorkspaceHoverCardClosed(page);
|
||||
expect((await readSharedStylesheetChanges(page)).rebuilt).toBe(0);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("workspace hover card closes when the pointer leaves a clicked row", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-click-leave-" });
|
||||
|
||||
|
||||
@@ -243,14 +243,6 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
|
||||
await expect(searchInput).toBeFocused();
|
||||
}
|
||||
|
||||
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
|
||||
const searchInput = page.getByPlaceholder("Search projects");
|
||||
await expect(searchInput).toBeFocused({ timeout: 30_000 });
|
||||
await page.keyboard.type(projectName);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(searchInput).toBeHidden({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
export async function expectNewWorkspaceProjectSelected(
|
||||
page: Page,
|
||||
projectDisplayName: string,
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* The shared stylesheet is `#unistyles-web`: one rule per generated style class, for the whole app.
|
||||
* Replacing a rule that is still in use makes the browser restyle the entire document, so a spec
|
||||
* remembers the rules, performs an interaction, and reads back what happened to them.
|
||||
*/
|
||||
export interface SharedStylesheetChanges {
|
||||
/** Rules for classes the interaction introduced. */
|
||||
added: number;
|
||||
/** Rules for classes nothing uses any more. */
|
||||
removed: number;
|
||||
/** Rules still in use that were thrown away and created again. */
|
||||
rebuilt: number;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__PASEO_SHARED_STYLESHEET_RULES__?: Map<string, CSSRule>;
|
||||
}
|
||||
}
|
||||
|
||||
function readSharedStylesheetRules(): Map<string, CSSRule> {
|
||||
const tag = document.getElementById("unistyles-web");
|
||||
if (!(tag instanceof HTMLStyleElement) || !tag.sheet) {
|
||||
throw new Error("Shared stylesheet is missing");
|
||||
}
|
||||
const rules = new Map<string, CSSRule>();
|
||||
const collect = (list: CSSRuleList, group: string) => {
|
||||
for (const rule of list) {
|
||||
if (rule instanceof CSSStyleRule) rules.set(`${group}${rule.selectorText}`, rule);
|
||||
else if (rule instanceof CSSMediaRule) collect(rule.cssRules, `${rule.conditionText} `);
|
||||
}
|
||||
};
|
||||
collect(tag.sheet.cssRules, "");
|
||||
return rules;
|
||||
}
|
||||
|
||||
export async function rememberSharedStylesheet(page: Page): Promise<void> {
|
||||
await page.evaluate(
|
||||
`window.__PASEO_SHARED_STYLESHEET_RULES__ = (${readSharedStylesheetRules.toString()})()`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function readSharedStylesheetChanges(page: Page): Promise<SharedStylesheetChanges> {
|
||||
return page.evaluate(`(() => {
|
||||
const before = window.__PASEO_SHARED_STYLESHEET_RULES__;
|
||||
if (!before) throw new Error("Shared stylesheet was not remembered");
|
||||
const after = (${readSharedStylesheetRules.toString()})();
|
||||
const changes = { added: 0, removed: 0, rebuilt: 0 };
|
||||
for (const [selector, rule] of after) {
|
||||
if (!before.has(selector)) changes.added += 1;
|
||||
else if (before.get(selector) !== rule) changes.rebuilt += 1;
|
||||
}
|
||||
for (const selector of before.keys()) {
|
||||
if (!after.has(selector)) changes.removed += 1;
|
||||
}
|
||||
return changes;
|
||||
})()`);
|
||||
}
|
||||
@@ -162,7 +162,6 @@ export interface HostPickerProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
anchorRef: React.RefObject<View | null>;
|
||||
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
|
||||
includeAllHost?: boolean;
|
||||
includeAddHost?: boolean;
|
||||
onAddHost?: () => void;
|
||||
@@ -186,7 +185,6 @@ export function HostPicker({
|
||||
open,
|
||||
onOpenChange,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
includeAllHost,
|
||||
includeAddHost,
|
||||
onAddHost,
|
||||
@@ -308,7 +306,6 @@ export function HostPicker({
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
desktopMinWidth={desktopMinWidth}
|
||||
/>
|
||||
|
||||
@@ -138,8 +138,6 @@ export interface ComboboxProps {
|
||||
/** When true, selecting an option does not close the picker (multi-select mode). */
|
||||
keepOpenOnSelect?: boolean;
|
||||
anchorRef: React.RefObject<View | null>;
|
||||
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
|
||||
restoreFocusRef?: React.RefObject<unknown>;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
@@ -1404,7 +1402,6 @@ export function Combobox({
|
||||
footer,
|
||||
keepOpenOnSelect = false,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
children,
|
||||
}: ComboboxProps): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
@@ -1670,7 +1667,6 @@ export function Combobox({
|
||||
layer: floatingLayer,
|
||||
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
|
||||
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
|
||||
restoreFocusRef,
|
||||
});
|
||||
|
||||
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
import React, { act } from "react";
|
||||
import React, { act, Profiler, useEffect, useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { Portal, PortalProvider } from "@gorhom/portal";
|
||||
import { Portal, PortalHost, PortalProvider } from "@gorhom/portal";
|
||||
import { FloatingPanelPortalHost, measureFloatingPanelPortalHost } from "./floating-panel-portal";
|
||||
|
||||
async function mount(element: React.ReactElement) {
|
||||
const container = document.createElement("div");
|
||||
container.style.cssText = "position:relative;width:800px;height:600px";
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
await act(async () => root.render(element));
|
||||
return {
|
||||
container,
|
||||
render: (next: React.ReactElement) => act(async () => root.render(next)),
|
||||
unmount: async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("Floating panel host lifetime", () => {
|
||||
test("removing the newest host preserves the surviving host measurement", async () => {
|
||||
const container = document.createElement("div");
|
||||
container.style.cssText = "position:relative;width:800px;height:600px";
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
function Content({ overlap }: { overlap: boolean }) {
|
||||
return (
|
||||
<PortalProvider shouldAddRootHost={false}>
|
||||
@@ -21,20 +33,106 @@ describe("Floating panel host lifetime", () => {
|
||||
</PortalProvider>
|
||||
);
|
||||
}
|
||||
const view = await mount(<Content overlap={true} />);
|
||||
try {
|
||||
await act(async () => root.render(<Content overlap={true} />));
|
||||
expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({
|
||||
width: 800,
|
||||
height: 600,
|
||||
});
|
||||
await act(async () => root.render(<Content overlap={false} />));
|
||||
await view.render(<Content overlap={false} />);
|
||||
expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({
|
||||
width: 800,
|
||||
height: 600,
|
||||
});
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
await view.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const rendered: string[] = [];
|
||||
|
||||
function record(id: string) {
|
||||
rendered.push(id);
|
||||
}
|
||||
|
||||
describe("Portal hosts", () => {
|
||||
test("opening a portal renders its own host and no other", async () => {
|
||||
let setCardOpen: (open: boolean) => void = () => {};
|
||||
function Card() {
|
||||
const [open, setOpen] = useState(false);
|
||||
setCardOpen = setOpen;
|
||||
if (!open) return null;
|
||||
return (
|
||||
<Portal hostName="sidebar" name="card">
|
||||
<div data-testid="card">Workspace</div>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
const view = await mount(
|
||||
<PortalProvider shouldAddRootHost={false}>
|
||||
<Profiler id="sidebar" onRender={record}>
|
||||
<PortalHost name="sidebar" />
|
||||
</Profiler>
|
||||
<Profiler id="workspace" onRender={record}>
|
||||
<PortalHost name="workspace" />
|
||||
</Profiler>
|
||||
<Card />
|
||||
</PortalProvider>,
|
||||
);
|
||||
try {
|
||||
rendered.length = 0;
|
||||
await act(async () => setCardOpen(true));
|
||||
|
||||
expect(view.container.querySelector('[data-testid="card"]')?.textContent).toBe("Workspace");
|
||||
expect(rendered).toContain("sidebar");
|
||||
expect(rendered).not.toContain("workspace");
|
||||
|
||||
rendered.length = 0;
|
||||
await act(async () => setCardOpen(false));
|
||||
|
||||
expect(view.container.querySelector('[data-testid="card"]')).toBeNull();
|
||||
expect(rendered).not.toContain("workspace");
|
||||
} finally {
|
||||
await view.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
test("closing an earlier portal keeps a later portal mounted", async () => {
|
||||
let menuMounts = 0;
|
||||
function Menu() {
|
||||
useEffect(() => {
|
||||
menuMounts += 1;
|
||||
}, []);
|
||||
return <div data-testid="menu">Menu</div>;
|
||||
}
|
||||
function Content({ tooltip }: { tooltip: boolean }) {
|
||||
return (
|
||||
<PortalProvider shouldAddRootHost={false}>
|
||||
<PortalHost name="workspace" />
|
||||
{tooltip && (
|
||||
<Portal hostName="workspace" name="tooltip">
|
||||
<span data-testid="tooltip">Tooltip</span>
|
||||
</Portal>
|
||||
)}
|
||||
<Portal hostName="workspace" name="menu">
|
||||
<Menu />
|
||||
</Portal>
|
||||
</PortalProvider>
|
||||
);
|
||||
}
|
||||
const view = await mount(<Content tooltip={true} />);
|
||||
try {
|
||||
expect(view.container.querySelector('[data-testid="tooltip"]')).not.toBeNull();
|
||||
expect(menuMounts).toBe(1);
|
||||
|
||||
await view.render(<Content tooltip={false} />);
|
||||
|
||||
expect(view.container.querySelector('[data-testid="tooltip"]')).toBeNull();
|
||||
expect(view.container.querySelector('[data-testid="menu"]')).not.toBeNull();
|
||||
expect(menuMounts).toBe(1);
|
||||
} finally {
|
||||
await view.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,10 +9,6 @@ export interface OverlayRegistration {
|
||||
*/
|
||||
keys: readonly string[];
|
||||
onKeyDown(event: KeyboardInputEvent): boolean;
|
||||
/**
|
||||
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
|
||||
* to whatever had focus when the overlay opened.
|
||||
*/
|
||||
restoreFocusRef?: RefObject<unknown>;
|
||||
manageFocus?: boolean;
|
||||
}
|
||||
|
||||
@@ -3,29 +3,12 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
|
||||
import type { OverlayRegistration } from "./overlay-contract";
|
||||
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
|
||||
|
||||
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
|
||||
interface FocusTarget {
|
||||
focus(): void;
|
||||
}
|
||||
|
||||
function isFocusTarget(value: unknown): value is FocusTarget {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
typeof (value as Partial<FocusTarget>).focus === "function"
|
||||
);
|
||||
}
|
||||
|
||||
function canRestoreFocusTo(target: FocusTarget): boolean {
|
||||
return !(target instanceof HTMLElement) || document.contains(target);
|
||||
}
|
||||
|
||||
interface WebOverlayEntry {
|
||||
getLayer: () => number;
|
||||
getKeys: () => readonly string[];
|
||||
getScope: () => HTMLElement | null;
|
||||
getKeyHandler: () => WebOverlayKeyHandler;
|
||||
restoreFocus: FocusTarget | null;
|
||||
restoreFocus: HTMLElement | null;
|
||||
manageFocus: boolean;
|
||||
}
|
||||
|
||||
@@ -173,7 +156,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
|
||||
entry.manageFocus &&
|
||||
options?.restoreFocus !== false &&
|
||||
entry.restoreFocus &&
|
||||
canRestoreFocusTo(entry.restoreFocus)
|
||||
document.contains(entry.restoreFocus)
|
||||
) {
|
||||
entry.restoreFocus.focus();
|
||||
}
|
||||
@@ -198,7 +181,7 @@ export function useOverlayRegistration({
|
||||
keysRef.current = keys;
|
||||
const layerRef = useRef(layer);
|
||||
const keyHandlerRef = useRef(onKeyDown);
|
||||
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
|
||||
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
|
||||
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const registeredRef = useRef(false);
|
||||
@@ -210,7 +193,7 @@ export function useOverlayRegistration({
|
||||
keyHandlerRef.current = onKeyDown;
|
||||
if (active && !wasActiveRef.current && typeof document !== "undefined") {
|
||||
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
|
||||
if (isFocusTarget(requestedRestoreTarget)) {
|
||||
if (requestedRestoreTarget instanceof HTMLElement) {
|
||||
capturedRestoreFocusRef.current = requestedRestoreTarget;
|
||||
} else {
|
||||
capturedRestoreFocusRef.current =
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import React, { act, useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
let setLabel: (label: string) => void = () => {};
|
||||
|
||||
function Row({ label }: { label: string }) {
|
||||
return <div>{label}</div>;
|
||||
}
|
||||
|
||||
function List() {
|
||||
const [label, setState] = useState("first");
|
||||
setLabel = setState;
|
||||
return <Row label={label} />;
|
||||
}
|
||||
|
||||
function reactMeasures(): PerformanceEntry[] {
|
||||
return performance
|
||||
.getEntriesByType("measure")
|
||||
.filter((entry) => JSON.stringify((entry as PerformanceMeasure).detail ?? "").includes("⚛"));
|
||||
}
|
||||
|
||||
// React's development build reports renders to the browser's performance timeline. The browser
|
||||
// keeps every measure for the life of the page, so a long session held millions of them.
|
||||
test("React's development render timings do not pile up in the performance timeline", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(<List />));
|
||||
for (const label of ["second", "third", "fourth"]) {
|
||||
await act(async () => setLabel(label));
|
||||
}
|
||||
|
||||
expect(container.textContent).toBe("fourth");
|
||||
expect(reactMeasures()).toHaveLength(0);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
@@ -1578,18 +1578,9 @@ export function NewWorkspaceScreen({
|
||||
? t("newWorkspace.refPicker.searching")
|
||||
: t("newWorkspace.refPicker.noMatchingRefs");
|
||||
|
||||
// The prompt is where the user types; when a field's picker closes, focus returns there rather
|
||||
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
|
||||
// shows a read-only command preview, so its pickers keep returning focus to their field.
|
||||
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
|
||||
const handleComposerFocusInput = useCallback((focus: () => void) => {
|
||||
composerFocusRef.current = { focus };
|
||||
}, []);
|
||||
|
||||
const formStack = useNewWorkspaceForm({
|
||||
isCompact,
|
||||
isPending,
|
||||
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
|
||||
pluginItems: (
|
||||
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
|
||||
),
|
||||
@@ -1691,7 +1682,6 @@ export function NewWorkspaceScreen({
|
||||
clearDraft={noopClearDraft}
|
||||
autoFocus={terminalTakesPrompt}
|
||||
autoFocusKey={launchFocusKey}
|
||||
onFocusInput={handleComposerFocusInput}
|
||||
error={errorMessage}
|
||||
/>
|
||||
) : (
|
||||
@@ -1722,7 +1712,6 @@ export function NewWorkspaceScreen({
|
||||
clearDraft={handleClearDraft}
|
||||
autoFocus
|
||||
autoFocusKey={launchFocusKey}
|
||||
onFocusInput={handleComposerFocusInput}
|
||||
commandDraft={composerState?.commandDraft}
|
||||
agentControls={agentControlsWithDisabled}
|
||||
error={errorMessage}
|
||||
|
||||
@@ -67,11 +67,6 @@ export interface NewWorkspaceFormProps {
|
||||
isPending: boolean;
|
||||
/** Plugin fields, drawn after the base ref. */
|
||||
pluginItems: ReactNode;
|
||||
/**
|
||||
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
|
||||
* one, focus returns to the field that opened the picker.
|
||||
*/
|
||||
restoreFocusRef?: RefObject<unknown>;
|
||||
project: PickerControl & {
|
||||
options: ComboboxOption[];
|
||||
projectByOptionId: Map<string, HostProjectListItem>;
|
||||
@@ -378,17 +373,7 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
|
||||
*/
|
||||
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
isCompact,
|
||||
isPending,
|
||||
pluginItems,
|
||||
restoreFocusRef,
|
||||
project,
|
||||
host,
|
||||
isolation,
|
||||
base,
|
||||
launch,
|
||||
} = props;
|
||||
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
|
||||
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
|
||||
const projectPicker = useProjectPicker(project, isPending);
|
||||
const isolationPicker = useIsolationPicker({
|
||||
@@ -447,7 +432,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
open={host.openState}
|
||||
onOpenChange={host.onOpenChange}
|
||||
anchorRef={host.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
includeAddHost
|
||||
onAddHost={host.onAddHost}
|
||||
addHostTestID="new-workspace-host-picker-add-host"
|
||||
@@ -541,7 +525,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={360}
|
||||
anchorRef={project.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText="No projects available."
|
||||
renderOption={projectPicker.renderOption}
|
||||
footer={projectPicker.footer}
|
||||
@@ -556,7 +539,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
searchable={false}
|
||||
desktopPlacement="bottom-start"
|
||||
anchorRef={isolation.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
desktopMinWidth={280}
|
||||
renderOption={isolationPicker.renderOption}
|
||||
/>
|
||||
@@ -573,7 +555,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={440}
|
||||
anchorRef={base.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText={base.emptyText}
|
||||
toolbar={refPicker.toolbar}
|
||||
renderOption={refPicker.renderOption}
|
||||
@@ -590,7 +571,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={360}
|
||||
anchorRef={worktreePicker.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText={t("newWorkspace.worktreePicker.empty")}
|
||||
renderOption={worktreePicker.renderOption}
|
||||
/>
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { createTestLogger } from "../../../../test-utils/test-logger.js";
|
||||
import { ClaudeAgentClient } from "./agent.js";
|
||||
|
||||
const hostedEnvironments = [
|
||||
{ transport: "Bedrock", env: { CLAUDE_CODE_USE_BEDROCK: "1" } },
|
||||
{ transport: "Vertex", env: { CLAUDE_CODE_USE_VERTEX: "true" } },
|
||||
];
|
||||
|
||||
test.each(hostedEnvironments)(
|
||||
"offers Auto mode on $transport while preserving its default mode",
|
||||
async ({ env }) => {
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtimeSettings: { env },
|
||||
resolveVersion: async () => "2.1.263",
|
||||
discoverModels: async () => [],
|
||||
});
|
||||
|
||||
const catalog = await client.fetchCatalog({ cwd: process.cwd() });
|
||||
|
||||
expect(catalog.modes?.map((mode) => mode.id)).toContain("auto");
|
||||
expect(catalog.defaultModeId).toBe("default");
|
||||
},
|
||||
);
|
||||
|
||||
test.each(hostedEnvironments)(
|
||||
"passes an explicit Auto selection on $transport to Claude Code",
|
||||
async ({ env }) => {
|
||||
const sdkError = new Error("Claude Code rejected this request");
|
||||
let requestedMode: string | undefined;
|
||||
let requestedEnv: NodeJS.ProcessEnv | undefined;
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtimeSettings: { env },
|
||||
resolveBinary: async () => "/test/claude",
|
||||
queryFactory: ({ options }) => {
|
||||
requestedMode = options.permissionMode;
|
||||
requestedEnv = options.env;
|
||||
throw sdkError;
|
||||
},
|
||||
});
|
||||
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
|
||||
|
||||
try {
|
||||
await expect(session.setMode("auto")).rejects.toBe(sdkError);
|
||||
expect(requestedMode).toBe("auto");
|
||||
expect(requestedEnv).toMatchObject(env);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -201,6 +201,23 @@ test("exposes and applies auto permission mode", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects auto mode when Claude Code uses Bedrock", async () => {
|
||||
const previousBedrock = process.env.CLAUDE_CODE_USE_BEDROCK;
|
||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||
|
||||
const session = await createSession();
|
||||
|
||||
try {
|
||||
await expect(session.setMode("auto")).rejects.toThrow(
|
||||
"Claude Auto mode requires the Anthropic API and is not supported when Claude Code uses Bedrock",
|
||||
);
|
||||
expect(sdkQueryFactory).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
restoreEnvValue("CLAUDE_CODE_USE_BEDROCK", previousBedrock);
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ env: {}, expected: "auto" },
|
||||
{ env: { CLAUDE_CODE_USE_BEDROCK: "1" }, expected: "default" },
|
||||
@@ -276,6 +293,40 @@ test("allows launch env to disable inherited Bedrock transport for auto mode", a
|
||||
}
|
||||
});
|
||||
|
||||
test("fails an auto mode turn when Claude Code uses Vertex", async () => {
|
||||
const previousVertex = process.env.CLAUDE_CODE_USE_VERTEX;
|
||||
process.env.CLAUDE_CODE_USE_VERTEX = "true";
|
||||
sdkQueryFactory.mockImplementation(() => {
|
||||
throw new Error("query should not start");
|
||||
});
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory: sdkQueryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
modeId: "auto",
|
||||
});
|
||||
|
||||
try {
|
||||
const events = await collectUntilTerminal(streamSession(session, "hello"));
|
||||
const failure = events.find(
|
||||
(event): event is Extract<AgentStreamEvent, { type: "turn_failed" }> =>
|
||||
event.type === "turn_failed",
|
||||
);
|
||||
|
||||
expect(failure?.error).toContain(
|
||||
"Claude Auto mode requires the Anthropic API and is not supported when Claude Code uses Vertex",
|
||||
);
|
||||
expect(sdkQueryFactory).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
restoreEnvValue("CLAUDE_CODE_USE_VERTEX", previousVertex);
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("switches an auto mode session to another mode when Claude Code uses Bedrock", async () => {
|
||||
const previousBedrock = process.env.CLAUDE_CODE_USE_BEDROCK;
|
||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||
|
||||
@@ -1056,11 +1056,37 @@ function isTruthyEnvValue(value: string | undefined): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function claudeDefaultMode(env: NodeJS.ProcessEnv): PermissionMode {
|
||||
return isTruthyEnvValue(env.CLAUDE_CODE_USE_BEDROCK) ||
|
||||
isTruthyEnvValue(env.CLAUDE_CODE_USE_VERTEX)
|
||||
? "default"
|
||||
: "auto";
|
||||
function claudeAutoModeUnavailableOn(env: NodeJS.ProcessEnv): "Bedrock" | "Vertex" | null {
|
||||
if (isTruthyEnvValue(env.CLAUDE_CODE_USE_BEDROCK)) {
|
||||
return "Bedrock";
|
||||
}
|
||||
if (isTruthyEnvValue(env.CLAUDE_CODE_USE_VERTEX)) {
|
||||
return "Vertex";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function assertClaudeModeCanRun(mode: PermissionMode, env: NodeJS.ProcessEnv): void {
|
||||
if (mode !== "auto") {
|
||||
return;
|
||||
}
|
||||
const transport = claudeAutoModeUnavailableOn(env);
|
||||
if (transport === null) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Claude Auto mode requires the Anthropic API and is not supported when Claude Code uses ${transport}. Select another permission mode or unset the ${transport === "Bedrock" ? "CLAUDE_CODE_USE_BEDROCK" : "CLAUDE_CODE_USE_VERTEX"} environment variable.`,
|
||||
);
|
||||
}
|
||||
|
||||
function claudeModeCatalog(env: NodeJS.ProcessEnv): {
|
||||
modes: AgentMode[];
|
||||
defaultModeId: PermissionMode;
|
||||
} {
|
||||
if (claudeAutoModeUnavailableOn(env)) {
|
||||
return { modes: DEFAULT_MODES.filter((mode) => mode.id !== "auto"), defaultModeId: "default" };
|
||||
}
|
||||
return { modes: DEFAULT_MODES, defaultModeId: "auto" };
|
||||
}
|
||||
|
||||
function coerceSessionMetadata(metadata: AgentMetadata | undefined): Partial<AgentSessionConfig> {
|
||||
@@ -1787,10 +1813,10 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
discoveredModelIds,
|
||||
),
|
||||
);
|
||||
const modeCatalog = claudeModeCatalog(env);
|
||||
return {
|
||||
models,
|
||||
modes: DEFAULT_MODES,
|
||||
defaultModeId: claudeDefaultMode(env),
|
||||
...modeCatalog,
|
||||
...(incomplete ? { incomplete } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1800,7 +1826,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
}
|
||||
|
||||
async resolveDefaultModeId({ env: launchEnv }: ResolveAgentDefaultModeInput): Promise<string> {
|
||||
return claudeDefaultMode(this.buildProviderEnv(launchEnv));
|
||||
return claudeModeCatalog(this.buildProviderEnv(launchEnv)).defaultModeId;
|
||||
}
|
||||
|
||||
private buildProviderEnv(launchEnv?: Record<string, string>): NodeJS.ProcessEnv {
|
||||
@@ -2925,6 +2951,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
const normalized = isPermissionMode(modeId) ? modeId : "default";
|
||||
assertClaudeModeCanRun(normalized, this.harnessEnvironment);
|
||||
const previousMode = this.currentMode;
|
||||
const previousQuery = this.query;
|
||||
const activeQuery = await this.ensureQuery(normalized);
|
||||
@@ -3984,6 +4011,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
const providerOptions = applyClaudeToolPolicy(sdkProviderOptions, this.config.toolPolicy);
|
||||
const settingsOptions = await this.buildSettingsOptions(providerOptions);
|
||||
const sdkEnv = this.harnessEnvironment;
|
||||
assertClaudeModeCanRun(permissionMode, sdkEnv);
|
||||
|
||||
const claudeBinary = await this.resolveBinary();
|
||||
this.logger.debug(
|
||||
|
||||
@@ -185,39 +185,29 @@ test("repeated content is reused without rewriting the attachment", async () =>
|
||||
test("64 MiB materialization leaves the event loop responsive and preserves bytes", async () => {
|
||||
const bytes = Buffer.alloc(64 * 1024 * 1024, 37);
|
||||
const data = bytes.toString("base64");
|
||||
const materializing = new AsyncLocalStorage<boolean>();
|
||||
let loopAdvanced = false;
|
||||
let yieldedBeforeFilesystem: boolean | undefined;
|
||||
const hook = createHook({
|
||||
init(_id, type) {
|
||||
// The first filesystem request follows hashing. A later turn could
|
||||
// come from filesystem I/O even if hashing blocked the event loop.
|
||||
if (
|
||||
type === "FSREQPROMISE" &&
|
||||
materializing.getStore() &&
|
||||
yieldedBeforeFilesystem === undefined
|
||||
) {
|
||||
yieldedBeforeFilesystem = loopAdvanced;
|
||||
}
|
||||
},
|
||||
});
|
||||
const probe = setImmediate(() => {
|
||||
loopAdvanced = true;
|
||||
});
|
||||
hook.enable();
|
||||
// Main-thread CPU time between ticks bounds the decode and hash work done on the loop;
|
||||
// wall-clock gaps on shared CI runners also count preemption and timer granularity.
|
||||
// File writes stay on fs/promises, so they never block the loop.
|
||||
const threadCpuMs = () => {
|
||||
const { user, system } = process.threadCpuUsage();
|
||||
return (user + system) / 1000;
|
||||
};
|
||||
let previous = threadCpuMs();
|
||||
let longest = 0;
|
||||
const probe = setInterval(() => {
|
||||
const now = threadCpuMs();
|
||||
longest = Math.max(longest, now - previous);
|
||||
previous = now;
|
||||
}, 1);
|
||||
try {
|
||||
const result = await materializing.run(true, () =>
|
||||
materializeProviderImage({ data, mimeType: "image/png" }),
|
||||
);
|
||||
try {
|
||||
expect(yieldedBeforeFilesystem).toBe(true);
|
||||
expect(readFileSync(result.path).equals(bytes)).toBe(true);
|
||||
} finally {
|
||||
rmSync(result.path, { force: true });
|
||||
}
|
||||
const result = await materializeProviderImage({ data, mimeType: "image/png" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
console.log(`64 MiB attachment longest blocking stretch: ${longest.toFixed(2)} ms CPU`);
|
||||
expect(longest).toBeLessThan(50);
|
||||
expect(readFileSync(result.path).equals(bytes)).toBe(true);
|
||||
rmSync(result.path, { force: true });
|
||||
} finally {
|
||||
hook.disable();
|
||||
clearImmediate(probe);
|
||||
clearInterval(probe);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -778,40 +778,3 @@ test.each([
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("an uninitialized submodule below a bare repository layout does not fail the comparison", async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), "diff-uninitialized-submodule-"));
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
|
||||
const { mkdir } = await import("node:fs/promises");
|
||||
try {
|
||||
git("init", "-b", "main");
|
||||
git("config", "user.name", "Test");
|
||||
git("config", "user.email", "test@example.com");
|
||||
await writeFile(join(cwd, "README.md"), "base\n");
|
||||
git("add", ".");
|
||||
git("-c", "commit.gpgsign=false", "commit", "-m", "base");
|
||||
const base = git("rev-parse", "HEAD");
|
||||
git("update-index", "--add", "--cacheinfo", `160000,${base},vendor/sub`);
|
||||
git("-c", "commit.gpgsign=false", "commit", "-m", "record submodule");
|
||||
// `vendor/` holds files shaped like a bare repository; git discovery from the
|
||||
// uninitialized `vendor/sub` would stop there before reaching the superproject.
|
||||
git("init", "--bare", "-q", "vendor");
|
||||
await mkdir(join(cwd, "vendor", "sub"));
|
||||
const comparison = await listComparison({
|
||||
cwd,
|
||||
base: { kind: "rev", rev: base },
|
||||
head: { kind: "worktree" },
|
||||
highlight: false,
|
||||
});
|
||||
try {
|
||||
expect(comparison.files.map((file) => [file.entry.path, file.entry.change])).toContainEqual([
|
||||
"vendor/sub",
|
||||
"added",
|
||||
]);
|
||||
} finally {
|
||||
await comparison.close();
|
||||
}
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
type CheckoutDiffCompare,
|
||||
} from "../../utils/checkout-git.js";
|
||||
import { lstat, readFile, readlink } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { resolve } from "node:path";
|
||||
import type { DiffEndpoint, DiffSubscribeRequest } from "@getpaseo/protocol/messages";
|
||||
import type { DiffEntry, DiffBody } from "@getpaseo/protocol/binary-frames/index";
|
||||
import { runGitCommand, type GitCommandOptions } from "../../utils/run-git-command.js";
|
||||
@@ -444,36 +444,15 @@ async function readWorktreeContent({
|
||||
if (value.isSymbolicLink())
|
||||
return { hashed: false, literal: `symlink:${await readlink(absolutePath)}` };
|
||||
if (value.isDirectory() && (header[0] === ":160000" || header[1] === "160000")) {
|
||||
return { hashed: false, literal: await readSubmoduleIdentity(path, absolutePath, options) };
|
||||
const submodule = await runGitCommand(
|
||||
["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],
|
||||
{ cwd: absolutePath, envOverlay: { GIT_OPTIONAL_LOCKS: "0" } },
|
||||
);
|
||||
return { hashed: false, literal: `submodule:${submodule.stdout}` };
|
||||
}
|
||||
return { hashed: value.isFile() && text, literal: null };
|
||||
}
|
||||
|
||||
// An uninitialized submodule has no `.git`; running git there would discover
|
||||
// whichever repository sits above it. Its content is the commit the index
|
||||
// records. Pinning GIT_DIR keeps an initialized submodule's status on its own `.git`.
|
||||
async function readSubmoduleIdentity(
|
||||
path: string,
|
||||
submodulePath: string,
|
||||
options: GitCommandOptions,
|
||||
): Promise<string> {
|
||||
try {
|
||||
await lstat(join(submodulePath, ".git"));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
const recorded = await runGitCommand(["rev-parse", "--verify", "--quiet", `:0:${path}`], {
|
||||
...options,
|
||||
acceptExitCodes: [0, 1],
|
||||
});
|
||||
return `submodule-uninitialized:${recorded.stdout.trim()}`;
|
||||
}
|
||||
const status = await runGitCommand(
|
||||
["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],
|
||||
{ cwd: submodulePath, envOverlay: { GIT_DIR: ".git", GIT_OPTIONAL_LOCKS: "0" } },
|
||||
);
|
||||
return `submodule:${status.stdout}`;
|
||||
}
|
||||
|
||||
function diffArguments(compare: Compare, baseSha: string, headSha: string): string[] {
|
||||
const revisions: string[] = [];
|
||||
if (compare.base.kind !== "index") revisions.push(baseSha);
|
||||
|
||||
@@ -534,61 +534,6 @@ test("submodule commits invalidate cached worktree gitlink bodies", async () =>
|
||||
}
|
||||
});
|
||||
|
||||
// Windows paths cannot contain `:`.
|
||||
const uninitializedSubmodulePaths = process.platform === "win32" ? ["sub"] : ["sub", "0:sub"];
|
||||
|
||||
test.each(uninitializedSubmodulePaths)(
|
||||
"staged commits invalidate cached bodies for an uninitialized submodule at %s",
|
||||
async (submodule) => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), "diff-uninitialized-gitlink-cache-"));
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
|
||||
const streams = new DiffSubscriptions({
|
||||
async requestWorkingTreeWatch(root) {
|
||||
return { repoRoot: root, unsubscribe: async () => {} };
|
||||
},
|
||||
});
|
||||
const frames: DiffFrame[] = [];
|
||||
const commit = (message: string) => {
|
||||
git("-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", message);
|
||||
return git("rev-parse", "HEAD");
|
||||
};
|
||||
try {
|
||||
git("init", "-b", "main");
|
||||
git("config", "user.name", "Test");
|
||||
git("config", "user.email", "test@example.com");
|
||||
const [a, b, c] = [commit("A"), commit("B"), commit("C")];
|
||||
git("update-index", "--add", "--cacheinfo", `160000,${a},${submodule}`);
|
||||
git("-c", "commit.gpgsign=false", "commit", "-m", "record A");
|
||||
await mkdir(join(cwd, submodule));
|
||||
git("update-index", "--cacheinfo", `160000,${b},${submodule}`);
|
||||
const subscription = await streams.subscribe(
|
||||
{ cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } },
|
||||
async (frame) => {
|
||||
frames.push(frame);
|
||||
},
|
||||
);
|
||||
await subscription.start();
|
||||
expect(frames.at(-1)).toMatchObject({ opcode: DiffOpcode.End, error: null });
|
||||
frames.length = 0;
|
||||
git("update-index", "--cacheinfo", `160000,${c},${submodule}`);
|
||||
await streams.invalidateForCwd(cwd);
|
||||
await expect
|
||||
.poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 })
|
||||
.toBe(true);
|
||||
const bodies = frames.flatMap((frame) =>
|
||||
frame.opcode === DiffOpcode.Bodies ? frame.files : [],
|
||||
);
|
||||
expect(bodies.flatMap((file) => file.hunks.flatMap((hunk) => hunk.lines))).toContainEqual(
|
||||
expect.objectContaining({ type: "add", content: `Subproject commit ${c}` }),
|
||||
);
|
||||
await subscription.release();
|
||||
} finally {
|
||||
await streams.close();
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("stat-only changes reuse cached bodies and send no body frames", async () => {
|
||||
const { utimes } = await import("node:fs/promises");
|
||||
const cwd = await mkdtemp(join(tmpdir(), "diff-stat-only-"));
|
||||
|
||||
+2
-34
@@ -296,23 +296,8 @@ function createGitRepository(): { tempDir: string; repoDir: string } {
|
||||
return { tempDir, repoDir };
|
||||
}
|
||||
|
||||
async function createBaseRecoveryFixture(
|
||||
baseBranch: string | null,
|
||||
options: { bareSource?: boolean } = {},
|
||||
) {
|
||||
const { tempDir, repoDir: checkoutDir } = createGitRepository();
|
||||
const repoDir = options.bareSource ? join(realpathSync(tempDir), "repo.git") : checkoutDir;
|
||||
if (options.bareSource) {
|
||||
execFileSync("git", ["clone", "--bare", "-q", checkoutDir, repoDir], { stdio: "pipe" });
|
||||
// A bare clone does not copy the checkout's local config; its linked worktrees share this one.
|
||||
for (const [key, value] of [
|
||||
["user.name", "Paseo Test"],
|
||||
["user.email", "test@example.com"],
|
||||
["core.autocrlf", "false"],
|
||||
]) {
|
||||
execFileSync("git", ["--git-dir", repoDir, "config", key, value], { stdio: "pipe" });
|
||||
}
|
||||
}
|
||||
async function createBaseRecoveryFixture(baseBranch: string | null) {
|
||||
const { tempDir, repoDir } = createGitRepository();
|
||||
const paseoHome = join(tempDir, "paseo-home");
|
||||
const created = await createWorktree({
|
||||
cwd: repoDir,
|
||||
@@ -663,23 +648,6 @@ test("restore rejects a branch checked out elsewhere without inventing another b
|
||||
).toBe("* feature");
|
||||
});
|
||||
|
||||
test("restores a workspace after the last checkout of a bare repository is archived", async () => {
|
||||
const fixture = await createBaseRecoveryFixture("main", { bareSource: true });
|
||||
await fixture.archiveAndRemove();
|
||||
|
||||
await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({
|
||||
workspaceId: fixture.workspace.workspaceId,
|
||||
action: "restore",
|
||||
});
|
||||
expect(readFileSync(join(fixture.workspace.cwd, "feature.txt"), "utf8")).toBe("feature\n");
|
||||
expect(
|
||||
execFileSync("git", ["symbolic-ref", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe("refs/heads/feature");
|
||||
});
|
||||
|
||||
test("restores a user-created worktree at its recorded path outside Paseo's root", async () => {
|
||||
const { tempDir, repoDir } = createGitRepository();
|
||||
const worktreeRoot = join(realpathSync(tempDir), "external-worktree");
|
||||
|
||||
@@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto";
|
||||
import { basename } from "node:path";
|
||||
|
||||
import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
|
||||
import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js";
|
||||
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
|
||||
import { runGitCommand } from "../../../utils/run-git-command.js";
|
||||
import {
|
||||
@@ -157,10 +156,7 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
let workspaceToUnarchive = resolved.workspace;
|
||||
let recreated: { worktreePath: string; pluginId: string | null } | null = null;
|
||||
if (resolved.kind === "restore") {
|
||||
const { workspace, sourceRepoRoot } = resolved;
|
||||
recreated = await runWithRepositoryRoot(sourceRepoRoot, () =>
|
||||
recreateArchivedWorktree(workspace, sourceRepoRoot),
|
||||
);
|
||||
recreated = await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
|
||||
if ((resolved.workspace.worktreeManagerPluginId ?? null) !== recreated.pluginId) {
|
||||
const { worktreeManagerPluginId: _previous, ...withoutManager } = resolved.workspace;
|
||||
workspaceToUnarchive = recreated.pluginId
|
||||
|
||||
@@ -190,7 +190,7 @@ async function withAuthenticatedRemote(
|
||||
{ cwd },
|
||||
);
|
||||
await run(["clone", "--bare", cwd, remote], { cwd: root });
|
||||
await run(["--git-dir", remote, "update-server-info"], { cwd: root });
|
||||
await run(["update-server-info"], { cwd: remote });
|
||||
await run(["config", "credential.helper", ""], { cwd });
|
||||
await run(["config", "core.askPass", askpassCommand], { cwd });
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
|
||||
@@ -18,9 +18,7 @@ import { createGitLabService } from "../services/gitlab-service.js";
|
||||
import {
|
||||
getCheckoutSnapshotFacts,
|
||||
getCheckoutStatus,
|
||||
getMainRepoRoot,
|
||||
pushCurrentBranch,
|
||||
resolveRepositoryDefaultBranch,
|
||||
} from "../utils/checkout-git.js";
|
||||
import {
|
||||
getPaseoWorktreeMetadataPath,
|
||||
@@ -28,7 +26,6 @@ import {
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js";
|
||||
import {
|
||||
createWorktree,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
listGitWorktrees,
|
||||
listPaseoWorktrees,
|
||||
@@ -91,13 +88,11 @@ function createGitHubServiceStub(): ForgeService {
|
||||
function createCoreDeps(options?: {
|
||||
github?: ForgeService;
|
||||
forge?: { forge: string; service: ForgeService };
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
resolveRepoRoot?: (cwd: string) => Promise<string>;
|
||||
}) {
|
||||
return {
|
||||
github: options?.github ?? createGitHubServiceStub(),
|
||||
workspaceGitService: {
|
||||
resolveRepoRoot: options?.resolveRepoRoot ?? (async (cwd: string) => cwd),
|
||||
resolveRepoRoot: async (cwd: string) => cwd,
|
||||
resolveForge: async () =>
|
||||
options?.forge
|
||||
? {
|
||||
@@ -107,7 +102,7 @@ function createCoreDeps(options?: {
|
||||
}
|
||||
: null,
|
||||
},
|
||||
resolveDefaultBranch: options?.resolveDefaultBranch ?? (async () => "main"),
|
||||
resolveDefaultBranch: async () => "main",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -450,39 +445,6 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
expect(existsSync(first.worktree.worktreePath)).toBe(true);
|
||||
});
|
||||
|
||||
test("creates a workspace from a checkout of a bare repository that only Paseo uses", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
const bareRepo = path.join(tempDir, "repo.git");
|
||||
execFileSync("git", ["clone", "--bare", "-q", repoDir, bareRepo], { stdio: "pipe" });
|
||||
const first = await createWorktree({
|
||||
cwd: bareRepo,
|
||||
paseoHome,
|
||||
worktreeSlug: "first",
|
||||
source: { kind: "branch-off", branchName: "first", baseBranch: "main" },
|
||||
});
|
||||
expect(await getMainRepoRoot(first.worktreePath, { paseoHome })).toBe(bareRepo);
|
||||
|
||||
const result = await createCoreWorktree(
|
||||
{ cwd: first.worktreePath, worktreeSlug: "second", paseoHome },
|
||||
createCoreDeps({
|
||||
resolveRepoRoot: (cwd) => getMainRepoRoot(cwd, { paseoHome }),
|
||||
resolveDefaultBranch: async (root) =>
|
||||
(await resolveRepositoryDefaultBranch(root)) ?? "unresolved",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.repoRoot).toBe(bareRepo);
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
branchName: "second",
|
||||
});
|
||||
expect(readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8")).toBe(
|
||||
"hello\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("creates branch-off worktrees from origin main without tracking origin main", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepoWithOriginMain();
|
||||
cleanupPaths.push(tempDir);
|
||||
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
} from "./resolve-worktree-creation-intent.js";
|
||||
import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/protocol/messages";
|
||||
import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import { runWithRepositoryRoot } from "../utils/git-repository-discovery.js";
|
||||
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
|
||||
|
||||
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
|
||||
@@ -79,16 +78,6 @@ async function createWorktreeCoreWithPriority(
|
||||
deps: CreateWorktreeCoreDeps,
|
||||
): Promise<CreateWorktreeCoreResult> {
|
||||
const repoRoot = await resolveWorktreeRepoRoot(input, deps.workspaceGitService);
|
||||
return runWithRepositoryRoot(repoRoot, () =>
|
||||
createWorktreeAtRepositoryRoot(input, deps, repoRoot),
|
||||
);
|
||||
}
|
||||
|
||||
async function createWorktreeAtRepositoryRoot(
|
||||
input: CreateWorktreeCoreInput,
|
||||
deps: CreateWorktreeCoreDeps,
|
||||
repoRoot: string,
|
||||
): Promise<CreateWorktreeCoreResult> {
|
||||
const requestedWorktreeSlug = input.worktreeSlug
|
||||
? normalizeWorktreeSlug(input.worktreeSlug)
|
||||
: undefined;
|
||||
|
||||
@@ -907,8 +907,6 @@ describe("ForgeService", () => {
|
||||
ttlMs: 0,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => null,
|
||||
now: () => now,
|
||||
});
|
||||
const reads = recordCurrentPullRequestStatusReads(service);
|
||||
@@ -982,8 +980,6 @@ describe("ForgeService", () => {
|
||||
ttlMs: 0,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => null,
|
||||
now: () => now,
|
||||
});
|
||||
const reads = recordCurrentPullRequestStatusReads(service);
|
||||
@@ -1030,8 +1026,6 @@ describe("ForgeService", () => {
|
||||
ttlMs: 0,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => null,
|
||||
now: () => now,
|
||||
});
|
||||
const reads = recordCurrentPullRequestStatusReads(service);
|
||||
@@ -1075,8 +1069,6 @@ describe("ForgeService", () => {
|
||||
ttlMs: 0,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => null,
|
||||
now: () => now,
|
||||
});
|
||||
|
||||
@@ -1106,8 +1098,6 @@ describe("ForgeService", () => {
|
||||
ttlMs: 0,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => null,
|
||||
now: () => now,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
parseSafeBareRepositorySupport,
|
||||
readRepositoryRootGitDir,
|
||||
resolveGitDiscovery,
|
||||
runWithRepositoryRoot,
|
||||
type GitDiscovery,
|
||||
} from "./git-repository-discovery.js";
|
||||
|
||||
const EXPLICIT = ["-c", "safe.bareRepository=explicit"];
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
function git(args: string[], cwd?: string): string {
|
||||
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim();
|
||||
}
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = realpathSync.native(mkdtempSync(path.join(tmpdir(), "paseo-git-discovery-")));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function createBareRepositoryWithLinkedWorktree(root: string): string {
|
||||
const source = path.join(root, "source");
|
||||
git(["init", "-q", "-b", "main", source]);
|
||||
git(
|
||||
[
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"commit",
|
||||
"-q",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"base",
|
||||
],
|
||||
source,
|
||||
);
|
||||
const bareRepo = path.join(root, "repo.git");
|
||||
git(["clone", "-q", "--bare", source, bareRepo]);
|
||||
git(["worktree", "add", "-q", path.join(root, "main"), "main"], bareRepo);
|
||||
return bareRepo;
|
||||
}
|
||||
|
||||
// Runs git with only the discovery environment, as a Git release that ignores
|
||||
// `safe.bareRepository` would see it.
|
||||
function gitDirWithoutConfig(cwd: string, discovery: GitDiscovery): string {
|
||||
try {
|
||||
const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
stdio: "pipe",
|
||||
env: { ...process.env, ...discovery.envOverlay },
|
||||
}).trim();
|
||||
return path.resolve(gitDir);
|
||||
} catch (error) {
|
||||
return String((error as { stderr?: string }).stderr).trim();
|
||||
}
|
||||
}
|
||||
|
||||
describe("resolveGitDiscovery before Git 2.38", () => {
|
||||
const legacy = {
|
||||
gitDirSet: false,
|
||||
repositoryRootGitDir: null,
|
||||
safeBareRepositorySupported: false,
|
||||
};
|
||||
|
||||
it("stops git at a bare repository layout in the working directory", async () => {
|
||||
const layout = path.join(makeTempDir(), "layout");
|
||||
git(["init", "--bare", "-q", layout]);
|
||||
|
||||
const discovery = await resolveGitDiscovery({ cwd: layout, ...legacy });
|
||||
|
||||
expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(layout, ".git") });
|
||||
expect(gitDirWithoutConfig(layout, discovery)).toMatch(/not a git repository/);
|
||||
});
|
||||
|
||||
it("stops git at a bare repository layout in a parent directory", async () => {
|
||||
const layout = path.join(makeTempDir(), "layout");
|
||||
git(["init", "--bare", "-q", layout]);
|
||||
const nested = path.join(layout, "a", "b");
|
||||
mkdirSync(nested, { recursive: true });
|
||||
|
||||
const discovery = await resolveGitDiscovery({ cwd: nested, ...legacy });
|
||||
|
||||
expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(nested, ".git") });
|
||||
expect(gitDirWithoutConfig(nested, discovery)).toMatch(/not a git repository/);
|
||||
});
|
||||
|
||||
it("leaves discovery alone when a checkout sits between the directory and the layout", async () => {
|
||||
const layout = path.join(makeTempDir(), "layout");
|
||||
git(["init", "--bare", "-q", layout]);
|
||||
const checkout = path.join(layout, "checkout");
|
||||
git(["init", "-q", checkout]);
|
||||
const nested = path.join(checkout, "src");
|
||||
mkdirSync(nested);
|
||||
|
||||
const discovery = await resolveGitDiscovery({ cwd: nested, ...legacy });
|
||||
|
||||
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
|
||||
expect(gitDirWithoutConfig(nested, discovery)).toBe(path.join(checkout, ".git"));
|
||||
});
|
||||
|
||||
it("leaves discovery alone inside a checkout's own .git directory", async () => {
|
||||
const checkout = path.join(makeTempDir(), "checkout");
|
||||
git(["init", "-q", checkout]);
|
||||
const gitDir = path.join(checkout, ".git");
|
||||
|
||||
const discovery = await resolveGitDiscovery({ cwd: gitDir, ...legacy });
|
||||
|
||||
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
|
||||
});
|
||||
|
||||
it("stops git at a bare repository with linked worktrees unless its root is named", async () => {
|
||||
const bareRepo = createBareRepositoryWithLinkedWorktree(makeTempDir());
|
||||
|
||||
const unnamed = await resolveGitDiscovery({ cwd: bareRepo, ...legacy });
|
||||
const named = await resolveGitDiscovery({
|
||||
cwd: bareRepo,
|
||||
...legacy,
|
||||
repositoryRootGitDir: bareRepo,
|
||||
});
|
||||
|
||||
expect(unnamed.envOverlay).toEqual({ GIT_DIR: path.join(bareRepo, ".git") });
|
||||
expect(named).toEqual({ configArgs: EXPLICIT, envOverlay: { GIT_DIR: bareRepo } });
|
||||
expect(gitDirWithoutConfig(bareRepo, named)).toBe(bareRepo);
|
||||
});
|
||||
|
||||
it("stops git below a bare repository with linked worktrees", async () => {
|
||||
const bareRepo = createBareRepositoryWithLinkedWorktree(makeTempDir());
|
||||
const refs = path.join(bareRepo, "refs");
|
||||
|
||||
const discovery = await resolveGitDiscovery({ cwd: refs, ...legacy });
|
||||
|
||||
expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(refs, ".git") });
|
||||
});
|
||||
|
||||
it("keeps a GIT_DIR the caller already chose", async () => {
|
||||
const layout = path.join(makeTempDir(), "layout");
|
||||
git(["init", "--bare", "-q", layout]);
|
||||
|
||||
const discovery = await resolveGitDiscovery({
|
||||
cwd: layout,
|
||||
gitDirSet: true,
|
||||
repositoryRootGitDir: layout,
|
||||
safeBareRepositorySupported: false,
|
||||
});
|
||||
|
||||
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveGitDiscovery on Git 2.38 and later", () => {
|
||||
it("relies on safe.bareRepository instead of walking the directory tree", async () => {
|
||||
const layout = path.join(makeTempDir(), "layout");
|
||||
git(["init", "--bare", "-q", layout]);
|
||||
|
||||
const discovery = await resolveGitDiscovery({
|
||||
cwd: layout,
|
||||
gitDirSet: false,
|
||||
repositoryRootGitDir: null,
|
||||
safeBareRepositorySupported: true,
|
||||
});
|
||||
|
||||
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
|
||||
});
|
||||
|
||||
it("names a bare repository root that the caller scoped", async () => {
|
||||
const layout = path.join(makeTempDir(), "layout");
|
||||
git(["init", "--bare", "-q", layout]);
|
||||
|
||||
const discovery = await resolveGitDiscovery({
|
||||
cwd: layout,
|
||||
gitDirSet: false,
|
||||
repositoryRootGitDir: layout,
|
||||
safeBareRepositorySupported: true,
|
||||
});
|
||||
|
||||
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: { GIT_DIR: layout } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("runWithRepositoryRoot", () => {
|
||||
it("names a bare repository root only for commands at that root", async () => {
|
||||
const bareRepo = path.join(makeTempDir(), "repo.git");
|
||||
git(["init", "--bare", "-q", bareRepo]);
|
||||
|
||||
const inside = await runWithRepositoryRoot(bareRepo, async () => ({
|
||||
root: readRepositoryRootGitDir(bareRepo),
|
||||
below: readRepositoryRootGitDir(path.join(bareRepo, "refs")),
|
||||
}));
|
||||
|
||||
expect(inside).toEqual({ root: bareRepo, below: null });
|
||||
expect(readRepositoryRootGitDir(bareRepo)).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves a checkout root to normal discovery", async () => {
|
||||
const checkout = path.join(makeTempDir(), "checkout");
|
||||
git(["init", "-q", checkout]);
|
||||
|
||||
const named = await runWithRepositoryRoot(checkout, async () =>
|
||||
readRepositoryRootGitDir(checkout),
|
||||
);
|
||||
|
||||
expect(named).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSafeBareRepositorySupport", () => {
|
||||
it.each([
|
||||
["git version 2.53.0", true],
|
||||
["git version 2.38.0", true],
|
||||
["git version 2.45.1.windows.1", true],
|
||||
["git version 3.0.0", true],
|
||||
["git version 2.37.1 (Apple Git-137)", false],
|
||||
["git version 2.34.1", false],
|
||||
["git version 1.9.5", false],
|
||||
["unexpected output", false],
|
||||
])("%s → %s", (output, supported) => {
|
||||
expect(parseSafeBareRepositorySupport(output)).toBe(supported);
|
||||
});
|
||||
});
|
||||
@@ -1,172 +0,0 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { lstat, realpath, stat } from "node:fs/promises";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import type { ProcessEnvRecord } from "../server/paseo-env.js";
|
||||
import { execCommand } from "./spawn.js";
|
||||
|
||||
const EXPLICIT_BARE_REPOSITORY = ["-c", "safe.bareRepository=explicit"];
|
||||
|
||||
/** How a git command finds its repository. */
|
||||
export interface GitDiscovery {
|
||||
configArgs: string[];
|
||||
envOverlay: ProcessEnvRecord;
|
||||
}
|
||||
|
||||
export interface GitDiscoveryInput {
|
||||
cwd: string;
|
||||
/** The command already names its repository through `GIT_DIR`. */
|
||||
gitDirSet: boolean;
|
||||
/** From `readRepositoryRootGitDir`, read when the command was submitted. */
|
||||
repositoryRootGitDir: string | null;
|
||||
safeBareRepositorySupported: boolean;
|
||||
}
|
||||
|
||||
interface RepositoryRoot {
|
||||
paths: readonly string[];
|
||||
gitDir: string;
|
||||
}
|
||||
|
||||
const repositoryRoots = new AsyncLocalStorage<readonly RepositoryRoot[]>();
|
||||
|
||||
/**
|
||||
* Runs `operation` with `root` named as the repository of every git command
|
||||
* whose cwd is exactly `root`.
|
||||
*
|
||||
* Paseo records a bare repository as a repository root when only its linked
|
||||
* checkouts use it. Git has no `.git` to find there, so those commands receive
|
||||
* the bare repository through `GIT_DIR`. A root with a `.git` keeps normal
|
||||
* discovery, and directories below `root` are not affected.
|
||||
*/
|
||||
export async function runWithRepositoryRoot<T>(
|
||||
root: string,
|
||||
operation: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
const current = repositoryRoots.getStore() ?? [];
|
||||
if (findRepositoryRoot(current, root)) return operation();
|
||||
const named = await readBareRepositoryRoot(root);
|
||||
if (!named) return operation();
|
||||
return repositoryRoots.run([...current, named], operation);
|
||||
}
|
||||
|
||||
/** The bare repository `runWithRepositoryRoot` named for `cwd` in this async context. */
|
||||
export function readRepositoryRootGitDir(cwd: string): string | null {
|
||||
return findRepositoryRoot(repositoryRoots.getStore() ?? [], cwd)?.gitDir ?? null;
|
||||
}
|
||||
|
||||
function findRepositoryRoot(
|
||||
roots: readonly RepositoryRoot[],
|
||||
cwd: string,
|
||||
): RepositoryRoot | undefined {
|
||||
const path = resolve(cwd);
|
||||
return roots.find((root) => root.paths.includes(path));
|
||||
}
|
||||
|
||||
async function readBareRepositoryRoot(root: string): Promise<RepositoryRoot | null> {
|
||||
const dotGit = await lstat(join(root, ".git")).catch(() => null);
|
||||
if (dotGit || !(await looksLikeBareRepository(root))) return null;
|
||||
const gitDir = await realpath(root).catch(() => null);
|
||||
if (!gitDir) return null;
|
||||
return { paths: [...new Set([resolve(root), gitDir])], gitDir };
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps git from adopting a directory that only looks like a bare repository
|
||||
* (`HEAD`, `objects/`, `refs/`), at `cwd` or above it.
|
||||
*
|
||||
* A caller that works on a bare repository names it with `GIT_DIR`, directly or
|
||||
* through `runWithRepositoryRoot`.
|
||||
*
|
||||
* - Git 2.38 and later: `safe.bareRepository=explicit`.
|
||||
* - Earlier releases ignore that setting. When discovery from `cwd` would reach
|
||||
* such a directory before any `.git`, `GIT_DIR` is pinned to the missing
|
||||
* `<cwd>/.git`, so git reports that no repository was found.
|
||||
*/
|
||||
export async function resolveGitDiscovery(input: GitDiscoveryInput): Promise<GitDiscovery> {
|
||||
if (!input.gitDirSet && input.repositoryRootGitDir) {
|
||||
return {
|
||||
configArgs: EXPLICIT_BARE_REPOSITORY,
|
||||
envOverlay: { GIT_DIR: input.repositoryRootGitDir },
|
||||
};
|
||||
}
|
||||
if (input.gitDirSet || input.safeBareRepositorySupported) {
|
||||
return { configArgs: EXPLICIT_BARE_REPOSITORY, envOverlay: {} };
|
||||
}
|
||||
if (!(await discoveryReachesImplicitBareRepository(input.cwd))) {
|
||||
return { configArgs: EXPLICIT_BARE_REPOSITORY, envOverlay: {} };
|
||||
}
|
||||
return {
|
||||
configArgs: EXPLICIT_BARE_REPOSITORY,
|
||||
envOverlay: { GIT_DIR: join(input.cwd, ".git") },
|
||||
};
|
||||
}
|
||||
|
||||
/** `safe.bareRepository` arrived in Git 2.38. */
|
||||
export function parseSafeBareRepositorySupport(versionOutput: string): boolean {
|
||||
const match = /git version (\d+)\.(\d+)/.exec(versionOutput);
|
||||
if (!match) return false;
|
||||
const major = Number(match[1]);
|
||||
const minor = Number(match[2]);
|
||||
return major > 2 || (major === 2 && minor >= 38);
|
||||
}
|
||||
|
||||
let safeBareRepositorySupport: Promise<boolean> | null = null;
|
||||
|
||||
/** Reads `git --version` once per process. */
|
||||
export function readSafeBareRepositorySupport(): Promise<boolean> {
|
||||
safeBareRepositorySupport ??= execCommand("git", ["--version"]).then(
|
||||
({ stdout }) => parseSafeBareRepositorySupport(stdout),
|
||||
() => false,
|
||||
);
|
||||
return safeBareRepositorySupport;
|
||||
}
|
||||
|
||||
// Follows git's discovery order: `<dir>/.git` first, then `<dir>` itself as a
|
||||
// bare repository, then the parent. Git itself accepts a bare-looking directory
|
||||
// that is a checkout's `.git`, or sits in its `worktrees/` or `modules/`.
|
||||
async function discoveryReachesImplicitBareRepository(cwd: string): Promise<boolean> {
|
||||
let dir: string;
|
||||
try {
|
||||
dir = await realpath(cwd);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
while (true) {
|
||||
const dotGit = join(dir, ".git");
|
||||
if ((await isFile(dotGit)) || (await looksLikeBareRepository(dotGit))) return false;
|
||||
if (await looksLikeBareRepository(dir)) return !isInsideDotGit(dir);
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) return false;
|
||||
dir = parent;
|
||||
}
|
||||
}
|
||||
|
||||
function isInsideDotGit(dir: string): boolean {
|
||||
const path = dir.replaceAll("\\", "/");
|
||||
return (
|
||||
basename(dir) === ".git" || path.includes("/.git/worktrees/") || path.includes("/.git/modules/")
|
||||
);
|
||||
}
|
||||
|
||||
async function looksLikeBareRepository(dir: string): Promise<boolean> {
|
||||
return (
|
||||
(await isFile(join(dir, "HEAD"))) &&
|
||||
(await isDirectory(join(dir, "objects"))) &&
|
||||
(await isDirectory(join(dir, "refs")))
|
||||
);
|
||||
}
|
||||
|
||||
async function isFile(path: string): Promise<boolean> {
|
||||
try {
|
||||
return (await stat(path)).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function isDirectory(path: string): Promise<boolean> {
|
||||
try {
|
||||
return (await stat(path)).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,8 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { runWithRepositoryRoot } from "./git-repository-discovery.js";
|
||||
import { runGitCommand } from "./run-git-command.js";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
@@ -59,112 +49,3 @@ describe("runGitCommand fsmonitor isolation", () => {
|
||||
expect(result.stdout.trim()).toBe("false");
|
||||
});
|
||||
});
|
||||
|
||||
function git(args: string[], cwd?: string): string {
|
||||
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim();
|
||||
}
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = realpathSync.native(mkdtempSync(path.join(tmpdir(), "paseo-git-discovery-")));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Files shaped like a bare repository (`HEAD`, `config`, `objects/`, `refs/`) that
|
||||
// git would adopt implicitly, with a clean filter that leaves a marker when run.
|
||||
function createBareRepositoryLayout(root: string, name: string): { dir: string; marker: string } {
|
||||
const dir = path.join(root, name);
|
||||
git(["init", "--bare", "-q", dir]);
|
||||
const marker = path.join(root, `${name}.marker`);
|
||||
writeFileSync(path.join(dir, "info", "attributes"), "* filter=probe\n");
|
||||
git(["config", "-f", path.join(dir, "config"), "filter.probe.clean", `touch '${marker}'; cat`]);
|
||||
return { dir, marker };
|
||||
}
|
||||
|
||||
function createBareRepositoryWithLinkedWorktree(root: string): {
|
||||
bareRepo: string;
|
||||
worktree: string;
|
||||
} {
|
||||
const source = path.join(root, "source");
|
||||
git(["init", "-q", "-b", "main", source]);
|
||||
git(
|
||||
[
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"commit",
|
||||
"-q",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"base",
|
||||
],
|
||||
source,
|
||||
);
|
||||
const bareRepo = path.join(root, "repo.git");
|
||||
git(["clone", "-q", "--bare", source, bareRepo]);
|
||||
const worktree = path.join(root, "main");
|
||||
git(["worktree", "add", "-q", worktree, "main"], bareRepo);
|
||||
return { bareRepo, worktree };
|
||||
}
|
||||
|
||||
function listedWorktreePaths(porcelain: string): string[] {
|
||||
return porcelain
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith("worktree "))
|
||||
.map((line) => path.resolve(line.slice("worktree ".length)));
|
||||
}
|
||||
|
||||
describe("runGitCommand repository discovery", () => {
|
||||
it("does not adopt a bare repository layout at the working directory", async () => {
|
||||
const root = makeTempDir();
|
||||
const layout = createBareRepositoryLayout(root, "layout");
|
||||
writeFileSync(path.join(layout.dir, "f.txt"), "contents\n");
|
||||
|
||||
await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: layout.dir });
|
||||
|
||||
expect(existsSync(layout.marker)).toBe(false);
|
||||
await expect(
|
||||
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: layout.dir }),
|
||||
).rejects.toThrow(/cannot use bare repository/);
|
||||
});
|
||||
|
||||
it("does not adopt a bare repository layout in a parent directory", async () => {
|
||||
const root = makeTempDir();
|
||||
const layout = createBareRepositoryLayout(root, "layout");
|
||||
const nested = path.join(layout.dir, "nested");
|
||||
mkdirSync(nested);
|
||||
writeFileSync(path.join(nested, "f.txt"), "contents\n");
|
||||
|
||||
await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: nested });
|
||||
|
||||
expect(existsSync(layout.marker)).toBe(false);
|
||||
await expect(
|
||||
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: nested }),
|
||||
).rejects.toThrow(/cannot use bare repository/);
|
||||
});
|
||||
|
||||
it("does not adopt a bare repository at the working directory even with linked worktrees", async () => {
|
||||
const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(makeTempDir());
|
||||
|
||||
await expect(
|
||||
runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo }),
|
||||
).rejects.toThrow(/cannot use bare repository/);
|
||||
const fromWorktree = await runGitCommand(["rev-parse", "--git-common-dir"], { cwd: worktree });
|
||||
expect(path.resolve(worktree, fromWorktree.stdout.trim())).toBe(bareRepo);
|
||||
});
|
||||
|
||||
it("runs at a bare repository root named with runWithRepositoryRoot", async () => {
|
||||
const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(makeTempDir());
|
||||
|
||||
const fromRoot = await runWithRepositoryRoot(bareRepo, () =>
|
||||
runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo }),
|
||||
);
|
||||
const belowRoot = await runWithRepositoryRoot(bareRepo, () =>
|
||||
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: path.join(bareRepo, "refs") }),
|
||||
).catch((error: unknown) => error);
|
||||
|
||||
expect(listedWorktreePaths(fromRoot.stdout)).toContain(worktree);
|
||||
expect(String(belowRoot)).toMatch(/cannot use bare repository/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,11 +11,6 @@ import {
|
||||
startGitCommandTrace,
|
||||
submitGitCommandTrace,
|
||||
} from "./git-command-trace.js";
|
||||
import {
|
||||
readRepositoryRootGitDir,
|
||||
readSafeBareRepositorySupport,
|
||||
resolveGitDiscovery,
|
||||
} from "./git-repository-discovery.js";
|
||||
import { spawnProcess } from "./spawn.js";
|
||||
import {
|
||||
GitProcessScheduler,
|
||||
@@ -301,15 +296,13 @@ function executeGitCommand<Output>(
|
||||
submission: GitCommandSubmission,
|
||||
): Promise<GitCommandResult<Output>> {
|
||||
const priority = submission.priority ?? gitCommandPriority.getStore() ?? "normal";
|
||||
// Read at submission: the scheduler may start the process from another async context.
|
||||
const repositoryRootGitDir = readRepositoryRootGitDir(options.cwd);
|
||||
const metricsState = submitGitCommandMetric(args, options.cwd, priority);
|
||||
const commandTrace = submitGitCommandTrace(args, options.cwd, {
|
||||
active: gitProcessScheduler.activeCount,
|
||||
pending: gitProcessScheduler.pendingCount,
|
||||
});
|
||||
const runtimeMetric = gitRuntimeMetrics.submit(getGitOperation(args), submission.provenance);
|
||||
const spawnCommand = (launch: GitLaunch) => {
|
||||
const startCommand = () => {
|
||||
let releaseProcessSlot!: () => void;
|
||||
const exited = new Promise<void>((resolve) => {
|
||||
releaseProcessSlot = resolve;
|
||||
@@ -324,10 +317,7 @@ function executeGitCommand<Output>(
|
||||
const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const acceptExitCodes = options.acceptExitCodes ?? [0];
|
||||
const command = formatGitCommand(args);
|
||||
const envOverlay = mergeEnvOverlays(
|
||||
mergeEnvOverlays(options.env, options.envOverlay),
|
||||
launch.envOverlay,
|
||||
);
|
||||
const envOverlay = mergeEnvOverlays(options.env, options.envOverlay);
|
||||
const startedAt = Date.now();
|
||||
beginGitCommandMetric(metricsState);
|
||||
const logger = typeof options.logger?.trace === "function" ? options.logger : undefined;
|
||||
@@ -417,12 +407,19 @@ function executeGitCommand<Output>(
|
||||
|
||||
let child: ReturnType<typeof spawnProcess>;
|
||||
try {
|
||||
child = spawnProcess("git", [...launch.configArgs, ...args], {
|
||||
cwd: options.cwd,
|
||||
envOverlay,
|
||||
shell: false,
|
||||
stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
||||
});
|
||||
// `core.quotepath=false` makes git emit raw UTF-8 paths instead of
|
||||
// octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`).
|
||||
// `core.fsmonitor=false` prevents repository config from launching a command.
|
||||
child = spawnProcess(
|
||||
"git",
|
||||
["-c", "core.quotepath=false", "-c", "core.fsmonitor=false", ...args],
|
||||
{
|
||||
cwd: options.cwd,
|
||||
envOverlay,
|
||||
shell: false,
|
||||
stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
spawnGitCommandTrace(commandTrace, child.pid);
|
||||
} catch (error) {
|
||||
rejectSpawnFailure(error);
|
||||
@@ -577,15 +574,6 @@ function executeGitCommand<Output>(
|
||||
});
|
||||
return { result: resultPromise, exited };
|
||||
};
|
||||
// The process slot stays held through the launch lookup because `exited`
|
||||
// settles only after the spawned process exits. `resolveGitLaunch` never rejects.
|
||||
const startCommand = () => {
|
||||
const spawned = resolveGitLaunch(options, repositoryRootGitDir).then(spawnCommand);
|
||||
return {
|
||||
result: spawned.then((scheduled) => scheduled.result),
|
||||
exited: spawned.then((scheduled) => scheduled.exited),
|
||||
};
|
||||
};
|
||||
const promise = gitProcessScheduler.run(startCommand, { priority });
|
||||
gitRuntimeMetrics.observeLimiter(
|
||||
gitProcessScheduler.activeCount,
|
||||
@@ -594,36 +582,6 @@ function executeGitCommand<Output>(
|
||||
return promise;
|
||||
}
|
||||
|
||||
interface GitLaunch {
|
||||
configArgs: string[];
|
||||
envOverlay: ProcessEnvRecord;
|
||||
}
|
||||
|
||||
// `core.quotepath=false` makes git emit raw UTF-8 paths instead of
|
||||
// octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`).
|
||||
// `core.fsmonitor=false` prevents repository config from launching a command.
|
||||
async function resolveGitLaunch(
|
||||
options: GitCommandOptions,
|
||||
repositoryRootGitDir: string | null,
|
||||
): Promise<GitLaunch> {
|
||||
const discovery = await resolveGitDiscovery({
|
||||
cwd: options.cwd,
|
||||
repositoryRootGitDir,
|
||||
gitDirSet: Boolean(options.envOverlay?.GIT_DIR ?? options.env?.GIT_DIR ?? process.env.GIT_DIR),
|
||||
safeBareRepositorySupported: await readSafeBareRepositorySupport(),
|
||||
});
|
||||
return {
|
||||
configArgs: [
|
||||
"-c",
|
||||
"core.quotepath=false",
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
...discovery.configArgs,
|
||||
],
|
||||
envOverlay: discovery.envOverlay,
|
||||
};
|
||||
}
|
||||
|
||||
export const runGitCommand: RunGitCommand = (args, options) =>
|
||||
executeGitCommand(args, options, decodeUtf8, {});
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
deletePaseoWorktree,
|
||||
readWorktreeHead,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
listPaseoWorktrees,
|
||||
mapWorkspaceCwdToWorktree,
|
||||
runWorktreeTeardownCommands,
|
||||
slugify,
|
||||
@@ -98,14 +97,6 @@ describe("paseo worktree manager", () => {
|
||||
await rm(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
|
||||
function cloneBareRepository(): string {
|
||||
const bareRepo = join(tempDir, "bare.git");
|
||||
execFileSync("git", ["clone", "--bare", "-q", repoDir, bareRepo]);
|
||||
// A bare clone does not copy the checkout's local config; its linked worktrees share this one.
|
||||
execFileSync("git", ["--git-dir", bareRepo, "config", "core.autocrlf", "false"]);
|
||||
return bareRepo;
|
||||
}
|
||||
|
||||
it.each([
|
||||
{ existing: [], preferred: "main/patch-1", expected: "main-1/patch-1" },
|
||||
{ existing: ["main-1"], preferred: "main/patch-1", expected: "main-2/patch-1" },
|
||||
@@ -312,44 +303,6 @@ describe("paseo worktree manager", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("creates and removes a worktree from a bare repository with no linked checkouts", async () => {
|
||||
const bareRepo = cloneBareRepository();
|
||||
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "from-bare",
|
||||
cwd: bareRepo,
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "from-bare",
|
||||
paseoHome,
|
||||
});
|
||||
expect(readFileSync(join(created.worktreePath, "file.txt"), "utf8")).toBe("hello\n");
|
||||
|
||||
await deletePaseoWorktree({ cwd: bareRepo, worktreePath: created.worktreePath, paseoHome });
|
||||
expect(existsSync(created.worktreePath)).toBe(false);
|
||||
expect(
|
||||
execFileSync("git", ["--git-dir", bareRepo, "worktree", "list", "--porcelain"], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
).not.toContain(created.worktreePath);
|
||||
});
|
||||
|
||||
it("lists the worktrees of a bare repository that only Paseo checkouts use", async () => {
|
||||
const bareRepo = cloneBareRepository();
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "listed",
|
||||
cwd: bareRepo,
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "listed",
|
||||
paseoHome,
|
||||
});
|
||||
|
||||
const worktrees = await listPaseoWorktrees({ cwd: bareRepo, paseoHome });
|
||||
|
||||
expect(worktrees.map((entry) => [entry.path, entry.branchName])).toEqual([
|
||||
[realpathSync.native(created.worktreePath), "listed"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("deletes a worktree whose .git admin dir has already been removed", async () => {
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "orphan-delete-branch",
|
||||
|
||||
@@ -34,7 +34,6 @@ import {
|
||||
writePaseoWorktreeMetadata,
|
||||
writePaseoWorktreeRuntimeMetadata,
|
||||
} from "./worktree-metadata.js";
|
||||
import { runWithRepositoryRoot } from "./git-repository-discovery.js";
|
||||
import { runGitCommand } from "./run-git-command.js";
|
||||
import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js";
|
||||
import { spawnProcess } from "./spawn.js";
|
||||
@@ -1218,23 +1217,15 @@ export async function listGitWorktrees({ cwd }: { cwd: string }): Promise<GitWor
|
||||
return worktrees;
|
||||
}
|
||||
|
||||
export interface ListPaseoWorktreesOptions {
|
||||
cwd: string;
|
||||
paseoHome?: string;
|
||||
worktreesRoot?: string;
|
||||
}
|
||||
|
||||
export function listPaseoWorktrees(
|
||||
options: ListPaseoWorktreesOptions,
|
||||
): Promise<PaseoWorktreeInfo[]> {
|
||||
return runWithRepositoryRoot(options.cwd, () => listPaseoWorktreesAtRepositoryRoot(options));
|
||||
}
|
||||
|
||||
async function listPaseoWorktreesAtRepositoryRoot({
|
||||
export async function listPaseoWorktrees({
|
||||
cwd,
|
||||
paseoHome,
|
||||
worktreesRoot,
|
||||
}: ListPaseoWorktreesOptions): Promise<PaseoWorktreeInfo[]> {
|
||||
}: {
|
||||
cwd: string;
|
||||
paseoHome?: string;
|
||||
worktreesRoot?: string;
|
||||
}): Promise<PaseoWorktreeInfo[]> {
|
||||
const projectWorktreesRoot = await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot);
|
||||
const { entries } = await readGitWorktreeEntries(cwd);
|
||||
|
||||
@@ -1334,12 +1325,7 @@ export async function readWorktreeHeadReference(worktreePath: string): Promise<s
|
||||
}
|
||||
}
|
||||
|
||||
export function deletePaseoWorktree(options: DeletePaseoWorktreeOptions): Promise<void> {
|
||||
const operation = () => deletePaseoWorktreeAtRepositoryRoot(options);
|
||||
return options.cwd ? runWithRepositoryRoot(options.cwd, operation) : operation();
|
||||
}
|
||||
|
||||
async function deletePaseoWorktreeAtRepositoryRoot({
|
||||
export async function deletePaseoWorktree({
|
||||
cwd,
|
||||
worktreePath,
|
||||
teardownCwds,
|
||||
@@ -1674,13 +1660,7 @@ export function createWorktree(
|
||||
export function createWorktree(
|
||||
options: CreateWorktreeOptions,
|
||||
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
|
||||
export function createWorktree(
|
||||
options: CreateWorktreeOptions,
|
||||
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }> {
|
||||
return runWithRepositoryRoot(options.cwd, () => createWorktreeAtRepositoryRoot(options));
|
||||
}
|
||||
|
||||
async function createWorktreeAtRepositoryRoot({
|
||||
export async function createWorktree({
|
||||
cwd,
|
||||
source,
|
||||
preparedBranchOff,
|
||||
@@ -1795,15 +1775,7 @@ export function runPluginWorktreeManagerCheckout(
|
||||
export function runPluginWorktreeManagerCheckout(
|
||||
options: RunPluginWorktreeManagerCheckoutOptions,
|
||||
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null>;
|
||||
export function runPluginWorktreeManagerCheckout(
|
||||
options: RunPluginWorktreeManagerCheckoutOptions,
|
||||
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null> {
|
||||
return runWithRepositoryRoot(options.cwd, () =>
|
||||
runPluginWorktreeManagerCheckoutAtRepositoryRoot(options),
|
||||
);
|
||||
}
|
||||
|
||||
async function runPluginWorktreeManagerCheckoutAtRepositoryRoot(
|
||||
export async function runPluginWorktreeManagerCheckout(
|
||||
options: RunPluginWorktreeManagerCheckoutOptions,
|
||||
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null> {
|
||||
const {
|
||||
@@ -2349,17 +2321,7 @@ async function resolveRestoredWorktreeFromBasePlan(
|
||||
};
|
||||
}
|
||||
|
||||
export function prepareWorktreeBranchOff(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "branch-off" }>,
|
||||
previous?: PreparedWorktreeBranchOff,
|
||||
): Promise<PreparedWorktreeBranchOff> {
|
||||
return runWithRepositoryRoot(cwd, () =>
|
||||
prepareWorktreeBranchOffAtRepositoryRoot(cwd, source, previous),
|
||||
);
|
||||
}
|
||||
|
||||
async function prepareWorktreeBranchOffAtRepositoryRoot(
|
||||
export async function prepareWorktreeBranchOff(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "branch-off" }>,
|
||||
previous?: PreparedWorktreeBranchOff,
|
||||
@@ -2589,19 +2551,11 @@ async function configureWorktreePushRemote(options: {
|
||||
* Fetches the first of `sources` a remote serves into the local ref `destination`, and returns
|
||||
* the name of that remote.
|
||||
*/
|
||||
export interface FetchFirstAvailableRefOptions {
|
||||
export async function fetchFirstAvailableRef(options: {
|
||||
cwd: string;
|
||||
sources: WorktreeCheckoutRef[];
|
||||
destination: string;
|
||||
}
|
||||
|
||||
export function fetchFirstAvailableRef(options: FetchFirstAvailableRefOptions): Promise<string> {
|
||||
return runWithRepositoryRoot(options.cwd, () => fetchFirstAvailableRefAtRepositoryRoot(options));
|
||||
}
|
||||
|
||||
async function fetchFirstAvailableRefAtRepositoryRoot(
|
||||
options: FetchFirstAvailableRefOptions,
|
||||
): Promise<string> {
|
||||
}): Promise<string> {
|
||||
let lastResult:
|
||||
| Awaited<ReturnType<typeof runGitCommand>>
|
||||
| { stderr: string; stdout: string; exitCode: number | null }
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
diff --git a/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js b/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js
|
||||
index 72ba2a7..e2f32a5 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js
|
||||
@@ -34,7 +34,11 @@ const PortalHostComponent = ({
|
||||
}, []); //#endregion
|
||||
//#region render
|
||||
|
||||
- return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, state.map(item => item.node)); //#endregion
|
||||
+ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a
|
||||
+ // portal shifts the ones after it and React remounts them.
|
||||
+ return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, state.map(item => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
|
||||
+ key: item.name
|
||||
+ }, item.node))); //#endregion
|
||||
};
|
||||
|
||||
const PortalHost = /*#__PURE__*/(0, _react.memo)(PortalHostComponent);
|
||||
diff --git a/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js b/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js
|
||||
index 3b2a494..af6616e 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js
|
||||
@@ -11,9 +11,7 @@ var _PortalHost = require("../portalHost/PortalHost");
|
||||
|
||||
var _portal = require("../../contexts/portal");
|
||||
|
||||
-var _constants = require("../../state/constants");
|
||||
-
|
||||
-var _reducer = require("../../state/reducer");
|
||||
+var _store = require("../../state/store");
|
||||
|
||||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
|
||||
|
||||
@@ -24,11 +22,11 @@ const PortalProviderComponent = ({
|
||||
shouldAddRootHost = true,
|
||||
children
|
||||
}) => {
|
||||
- const [state, dispatch] = (0, _react.useReducer)(_reducer.reducer, _constants.INITIAL_STATE);
|
||||
+ const [store] = (0, _react.useState)(_store.createPortalStore);
|
||||
return /*#__PURE__*/_react.default.createElement(_portal.PortalDispatchContext.Provider, {
|
||||
- value: dispatch
|
||||
+ value: store.dispatch
|
||||
}, /*#__PURE__*/_react.default.createElement(_portal.PortalStateContext.Provider, {
|
||||
- value: state
|
||||
+ value: store
|
||||
}, children, shouldAddRootHost && /*#__PURE__*/_react.default.createElement(_PortalHost.PortalHost, {
|
||||
name: rootHostName
|
||||
})));
|
||||
diff --git a/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js b/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js
|
||||
index 7a18089..77a8e24 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js
|
||||
@@ -10,13 +10,15 @@ var _react = require("react");
|
||||
var _portal = require("../contexts/portal");
|
||||
|
||||
const usePortalState = hostName => {
|
||||
- const state = (0, _react.useContext)(_portal.PortalStateContext);
|
||||
+ const store = (0, _react.useContext)(_portal.PortalStateContext);
|
||||
|
||||
- if (state === null) {
|
||||
+ if (store === null) {
|
||||
throw new Error("'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component.");
|
||||
}
|
||||
|
||||
- return state[hostName] || [];
|
||||
+ const getPortals = () => store.getPortals(hostName);
|
||||
+
|
||||
+ return (0, _react.useSyncExternalStore)(store.subscribe, getPortals, getPortals);
|
||||
};
|
||||
|
||||
exports.usePortalState = usePortalState;
|
||||
diff --git a/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js b/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js
|
||||
index 158e729..cd50661 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js
|
||||
@@ -31,17 +31,15 @@ const addUpdatePortal = (state, hostName, portalName, node) => {
|
||||
*/
|
||||
|
||||
|
||||
- const index = state[hostName].findIndex(item => item.name === portalName);
|
||||
-
|
||||
- if (index !== -1) {
|
||||
- state[hostName][index].node = node;
|
||||
- } else {
|
||||
- state[hostName].push({
|
||||
- name: portalName,
|
||||
- node
|
||||
- });
|
||||
- }
|
||||
-
|
||||
+ // Paseo patch: a changed host gets a new array, so the store can hand each host its own
|
||||
+ // snapshot and only the host whose portals changed renders.
|
||||
+ const portals = state[hostName];
|
||||
+ const index = portals.findIndex(item => item.name === portalName);
|
||||
+ const portal = {
|
||||
+ name: portalName,
|
||||
+ node
|
||||
+ };
|
||||
+ state[hostName] = index !== -1 ? portals.map(item => item.name === portalName ? portal : item) : [...portals, portal];
|
||||
return state;
|
||||
};
|
||||
|
||||
@@ -56,7 +54,11 @@ const removePortal = (state, hostName, portalName) => {
|
||||
}
|
||||
|
||||
const index = state[hostName].findIndex(item => item.name === portalName);
|
||||
- if (index !== -1) state[hostName].splice(index, 1);
|
||||
+
|
||||
+ if (index !== -1) {
|
||||
+ state[hostName] = state[hostName].filter(item => item.name !== portalName);
|
||||
+ }
|
||||
+
|
||||
return state;
|
||||
};
|
||||
|
||||
diff --git a/node_modules/@gorhom/portal/lib/commonjs/state/store.js b/node_modules/@gorhom/portal/lib/commonjs/state/store.js
|
||||
new file mode 100644
|
||||
index 0000000..0da9a5c
|
||||
--- /dev/null
|
||||
+++ b/node_modules/@gorhom/portal/lib/commonjs/state/store.js
|
||||
@@ -0,0 +1,34 @@
|
||||
+"use strict";
|
||||
+
|
||||
+Object.defineProperty(exports, "__esModule", {
|
||||
+ value: true
|
||||
+});
|
||||
+exports.createPortalStore = void 0;
|
||||
+
|
||||
+var _constants = require("./constants");
|
||||
+
|
||||
+var _reducer = require("./reducer");
|
||||
+
|
||||
+const NO_PORTALS = [];
|
||||
+// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context
|
||||
+// value it changed on every portal add, update and remove, and React then walked every fiber under
|
||||
+// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead.
|
||||
+const createPortalStore = () => {
|
||||
+ let state = _constants.INITIAL_STATE;
|
||||
+ const listeners = new Set();
|
||||
+ return {
|
||||
+ getPortals: hostName => state[hostName] || NO_PORTALS,
|
||||
+ dispatch: action => {
|
||||
+ state = (0, _reducer.reducer)(state, action);
|
||||
+ listeners.forEach(listener => listener());
|
||||
+ },
|
||||
+ subscribe: listener => {
|
||||
+ listeners.add(listener);
|
||||
+ return () => {
|
||||
+ listeners.delete(listener);
|
||||
+ };
|
||||
+ }
|
||||
+ };
|
||||
+};
|
||||
+
|
||||
+exports.createPortalStore = createPortalStore;
|
||||
diff --git a/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js b/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js
|
||||
index d22cc16..e492b4b 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js
|
||||
@@ -21,7 +21,11 @@ const PortalHostComponent = ({
|
||||
}, []); //#endregion
|
||||
//#region render
|
||||
|
||||
- return /*#__PURE__*/React.createElement(React.Fragment, null, state.map(item => item.node)); //#endregion
|
||||
+ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a
|
||||
+ // portal shifts the ones after it and React remounts them.
|
||||
+ return /*#__PURE__*/React.createElement(React.Fragment, null, state.map(item => /*#__PURE__*/React.createElement(React.Fragment, {
|
||||
+ key: item.name
|
||||
+ }, item.node))); //#endregion
|
||||
};
|
||||
|
||||
export const PortalHost = /*#__PURE__*/memo(PortalHostComponent);
|
||||
diff --git a/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js b/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js
|
||||
index 522a08a..d2e07b6 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js
|
||||
@@ -1,19 +1,18 @@
|
||||
-import React, { memo, useReducer } from 'react';
|
||||
+import React, { memo, useState } from 'react';
|
||||
import { PortalHost } from '../portalHost/PortalHost';
|
||||
import { PortalDispatchContext, PortalStateContext } from '../../contexts/portal';
|
||||
-import { INITIAL_STATE } from '../../state/constants';
|
||||
-import { reducer } from '../../state/reducer';
|
||||
+import { createPortalStore } from '../../state/store';
|
||||
|
||||
const PortalProviderComponent = ({
|
||||
rootHostName = 'root',
|
||||
shouldAddRootHost = true,
|
||||
children
|
||||
}) => {
|
||||
- const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
|
||||
+ const [store] = useState(createPortalStore);
|
||||
return /*#__PURE__*/React.createElement(PortalDispatchContext.Provider, {
|
||||
- value: dispatch
|
||||
+ value: store.dispatch
|
||||
}, /*#__PURE__*/React.createElement(PortalStateContext.Provider, {
|
||||
- value: state
|
||||
+ value: store
|
||||
}, children, shouldAddRootHost && /*#__PURE__*/React.createElement(PortalHost, {
|
||||
name: rootHostName
|
||||
})));
|
||||
diff --git a/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js b/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js
|
||||
index c82cc71..daee3ac 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js
|
||||
@@ -1,12 +1,14 @@
|
||||
-import { useContext } from 'react';
|
||||
+import { useContext, useSyncExternalStore } from 'react';
|
||||
import { PortalStateContext } from '../contexts/portal';
|
||||
export const usePortalState = hostName => {
|
||||
- const state = useContext(PortalStateContext);
|
||||
+ const store = useContext(PortalStateContext);
|
||||
|
||||
- if (state === null) {
|
||||
+ if (store === null) {
|
||||
throw new Error("'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component.");
|
||||
}
|
||||
|
||||
- return state[hostName] || [];
|
||||
+ const getPortals = () => store.getPortals(hostName);
|
||||
+
|
||||
+ return useSyncExternalStore(store.subscribe, getPortals, getPortals);
|
||||
};
|
||||
//# sourceMappingURL=usePortalState.js.map
|
||||
\ No newline at end of file
|
||||
diff --git a/node_modules/@gorhom/portal/lib/module/state/reducer.js b/node_modules/@gorhom/portal/lib/module/state/reducer.js
|
||||
index cad5f28..51f7124 100644
|
||||
--- a/node_modules/@gorhom/portal/lib/module/state/reducer.js
|
||||
+++ b/node_modules/@gorhom/portal/lib/module/state/reducer.js
|
||||
@@ -23,17 +23,15 @@ const addUpdatePortal = (state, hostName, portalName, node) => {
|
||||
*/
|
||||
|
||||
|
||||
- const index = state[hostName].findIndex(item => item.name === portalName);
|
||||
-
|
||||
- if (index !== -1) {
|
||||
- state[hostName][index].node = node;
|
||||
- } else {
|
||||
- state[hostName].push({
|
||||
- name: portalName,
|
||||
- node
|
||||
- });
|
||||
- }
|
||||
-
|
||||
+ // Paseo patch: a changed host gets a new array, so the store can hand each host its own
|
||||
+ // snapshot and only the host whose portals changed renders.
|
||||
+ const portals = state[hostName];
|
||||
+ const index = portals.findIndex(item => item.name === portalName);
|
||||
+ const portal = {
|
||||
+ name: portalName,
|
||||
+ node
|
||||
+ };
|
||||
+ state[hostName] = index !== -1 ? portals.map(item => item.name === portalName ? portal : item) : [...portals, portal];
|
||||
return state;
|
||||
};
|
||||
|
||||
@@ -48,7 +46,11 @@ const removePortal = (state, hostName, portalName) => {
|
||||
}
|
||||
|
||||
const index = state[hostName].findIndex(item => item.name === portalName);
|
||||
- if (index !== -1) state[hostName].splice(index, 1);
|
||||
+
|
||||
+ if (index !== -1) {
|
||||
+ state[hostName] = state[hostName].filter(item => item.name !== portalName);
|
||||
+ }
|
||||
+
|
||||
return state;
|
||||
};
|
||||
|
||||
diff --git a/node_modules/@gorhom/portal/lib/module/state/store.js b/node_modules/@gorhom/portal/lib/module/state/store.js
|
||||
new file mode 100644
|
||||
index 0000000..2c94075
|
||||
--- /dev/null
|
||||
+++ b/node_modules/@gorhom/portal/lib/module/state/store.js
|
||||
@@ -0,0 +1,23 @@
|
||||
+import { INITIAL_STATE } from './constants';
|
||||
+import { reducer } from './reducer';
|
||||
+const NO_PORTALS = [];
|
||||
+// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context
|
||||
+// value it changed on every portal add, update and remove, and React then walked every fiber under
|
||||
+// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead.
|
||||
+export const createPortalStore = () => {
|
||||
+ let state = INITIAL_STATE;
|
||||
+ const listeners = new Set();
|
||||
+ return {
|
||||
+ getPortals: hostName => state[hostName] || NO_PORTALS,
|
||||
+ dispatch: action => {
|
||||
+ state = reducer(state, action);
|
||||
+ listeners.forEach(listener => listener());
|
||||
+ },
|
||||
+ subscribe: listener => {
|
||||
+ listeners.add(listener);
|
||||
+ return () => {
|
||||
+ listeners.delete(listener);
|
||||
+ };
|
||||
+ }
|
||||
+ };
|
||||
+};
|
||||
diff --git a/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx b/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx
|
||||
index 62a2103..699765e 100644
|
||||
--- a/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx
|
||||
+++ b/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx
|
||||
@@ -20,7 +20,15 @@ const PortalHostComponent = ({ name }: PortalHostProps) => {
|
||||
//#endregion
|
||||
|
||||
//#region render
|
||||
- return <>{state.map(item => item.node)}</>;
|
||||
+ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a
|
||||
+ // portal shifts the ones after it and React remounts them.
|
||||
+ return (
|
||||
+ <>
|
||||
+ {state.map(item => (
|
||||
+ <React.Fragment key={item.name}>{item.node}</React.Fragment>
|
||||
+ ))}
|
||||
+ </>
|
||||
+ );
|
||||
//#endregion
|
||||
};
|
||||
|
||||
diff --git a/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx b/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx
|
||||
index 8350171..f91273a 100644
|
||||
--- a/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx
|
||||
+++ b/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx
|
||||
@@ -1,11 +1,10 @@
|
||||
-import React, { memo, useReducer } from 'react';
|
||||
+import React, { memo, useState } from 'react';
|
||||
import { PortalHost } from '../portalHost/PortalHost';
|
||||
import {
|
||||
PortalDispatchContext,
|
||||
PortalStateContext,
|
||||
} from '../../contexts/portal';
|
||||
-import { INITIAL_STATE } from '../../state/constants';
|
||||
-import { reducer } from '../../state/reducer';
|
||||
+import { createPortalStore } from '../../state/store';
|
||||
import type { PortalProviderProps } from './types';
|
||||
|
||||
const PortalProviderComponent = ({
|
||||
@@ -13,10 +12,10 @@ const PortalProviderComponent = ({
|
||||
shouldAddRootHost = true,
|
||||
children,
|
||||
}: PortalProviderProps) => {
|
||||
- const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
|
||||
+ const [store] = useState(createPortalStore);
|
||||
return (
|
||||
- <PortalDispatchContext.Provider value={dispatch}>
|
||||
- <PortalStateContext.Provider value={state}>
|
||||
+ <PortalDispatchContext.Provider value={store.dispatch}>
|
||||
+ <PortalStateContext.Provider value={store}>
|
||||
{children}
|
||||
{shouldAddRootHost && <PortalHost name={rootHostName} />}
|
||||
</PortalStateContext.Provider>
|
||||
diff --git a/node_modules/@gorhom/portal/src/contexts/portal.ts b/node_modules/@gorhom/portal/src/contexts/portal.ts
|
||||
index 2e3a46f..85ff020 100644
|
||||
--- a/node_modules/@gorhom/portal/src/contexts/portal.ts
|
||||
+++ b/node_modules/@gorhom/portal/src/contexts/portal.ts
|
||||
@@ -1,10 +1,7 @@
|
||||
import { createContext } from 'react';
|
||||
+import type { PortalStore } from '../state/store';
|
||||
import type { ActionTypes } from '../state/types';
|
||||
-import type { PortalType } from '../types';
|
||||
|
||||
-export const PortalStateContext = createContext<Record<
|
||||
- string,
|
||||
- Array<PortalType>
|
||||
-> | null>(null);
|
||||
+export const PortalStateContext = createContext<PortalStore | null>(null);
|
||||
export const PortalDispatchContext =
|
||||
createContext<React.Dispatch<ActionTypes> | null>(null);
|
||||
diff --git a/node_modules/@gorhom/portal/src/hooks/usePortalState.ts b/node_modules/@gorhom/portal/src/hooks/usePortalState.ts
|
||||
index 64bb180..d9877c3 100644
|
||||
--- a/node_modules/@gorhom/portal/src/hooks/usePortalState.ts
|
||||
+++ b/node_modules/@gorhom/portal/src/hooks/usePortalState.ts
|
||||
@@ -1,14 +1,16 @@
|
||||
-import { useContext } from 'react';
|
||||
+import { useContext, useSyncExternalStore } from 'react';
|
||||
import { PortalStateContext } from '../contexts/portal';
|
||||
|
||||
export const usePortalState = (hostName: string) => {
|
||||
- const state = useContext(PortalStateContext);
|
||||
+ const store = useContext(PortalStateContext);
|
||||
|
||||
- if (state === null) {
|
||||
+ if (store === null) {
|
||||
throw new Error(
|
||||
"'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component."
|
||||
);
|
||||
}
|
||||
|
||||
- return state[hostName] || [];
|
||||
+ const getPortals = () => store.getPortals(hostName);
|
||||
+
|
||||
+ return useSyncExternalStore(store.subscribe, getPortals, getPortals);
|
||||
};
|
||||
diff --git a/node_modules/@gorhom/portal/src/state/reducer.ts b/node_modules/@gorhom/portal/src/state/reducer.ts
|
||||
index 37f2414..1370244 100644
|
||||
--- a/node_modules/@gorhom/portal/src/state/reducer.ts
|
||||
+++ b/node_modules/@gorhom/portal/src/state/reducer.ts
|
||||
@@ -38,15 +38,15 @@ const addUpdatePortal = (
|
||||
/**
|
||||
* updated portal, if it was already added.
|
||||
*/
|
||||
- const index = state[hostName].findIndex(item => item.name === portalName);
|
||||
- if (index !== -1) {
|
||||
- state[hostName][index].node = node;
|
||||
- } else {
|
||||
- state[hostName].push({
|
||||
- name: portalName,
|
||||
- node,
|
||||
- });
|
||||
- }
|
||||
+ // Paseo patch: a changed host gets a new array, so the store can hand each host its own
|
||||
+ // snapshot and only the host whose portals changed renders.
|
||||
+ const portals = state[hostName];
|
||||
+ const index = portals.findIndex(item => item.name === portalName);
|
||||
+ const portal = { name: portalName, node };
|
||||
+ state[hostName] =
|
||||
+ index !== -1
|
||||
+ ? portals.map(item => (item.name === portalName ? portal : item))
|
||||
+ : [...portals, portal];
|
||||
return state;
|
||||
};
|
||||
|
||||
@@ -65,7 +65,9 @@ const removePortal = (
|
||||
}
|
||||
|
||||
const index = state[hostName].findIndex(item => item.name === portalName);
|
||||
- if (index !== -1) state[hostName].splice(index, 1);
|
||||
+ if (index !== -1) {
|
||||
+ state[hostName] = state[hostName].filter(item => item.name !== portalName);
|
||||
+ }
|
||||
return state;
|
||||
};
|
||||
|
||||
diff --git a/node_modules/@gorhom/portal/src/state/store.ts b/node_modules/@gorhom/portal/src/state/store.ts
|
||||
new file mode 100644
|
||||
index 0000000..4acf035
|
||||
--- /dev/null
|
||||
+++ b/node_modules/@gorhom/portal/src/state/store.ts
|
||||
@@ -0,0 +1,30 @@
|
||||
+import { INITIAL_STATE } from './constants';
|
||||
+import { reducer } from './reducer';
|
||||
+import type { PortalType } from '../types';
|
||||
+import type { ActionTypes } from './types';
|
||||
+
|
||||
+const NO_PORTALS: Array<PortalType> = [];
|
||||
+
|
||||
+// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context
|
||||
+// value it changed on every portal add, update and remove, and React then walked every fiber under
|
||||
+// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead.
|
||||
+export const createPortalStore = () => {
|
||||
+ let state: Record<string, Array<PortalType>> = INITIAL_STATE;
|
||||
+ const listeners = new Set<() => void>();
|
||||
+
|
||||
+ return {
|
||||
+ getPortals: (hostName: string) => state[hostName] || NO_PORTALS,
|
||||
+ dispatch: (action: ActionTypes) => {
|
||||
+ state = reducer(state, action);
|
||||
+ listeners.forEach(listener => listener());
|
||||
+ },
|
||||
+ subscribe: (listener: () => void) => {
|
||||
+ listeners.add(listener);
|
||||
+ return () => {
|
||||
+ listeners.delete(listener);
|
||||
+ };
|
||||
+ },
|
||||
+ };
|
||||
+};
|
||||
+
|
||||
+export type PortalStore = ReturnType<typeof createPortalStore>;
|
||||
@@ -0,0 +1,170 @@
|
||||
diff --git a/node_modules/react-dom/cjs/react-dom-client.development.js b/node_modules/react-dom/cjs/react-dom-client.development.js
|
||||
index 771ecad..3d9bf72 100644
|
||||
--- a/node_modules/react-dom/cjs/react-dom-client.development.js
|
||||
+++ b/node_modules/react-dom/cjs/react-dom-client.development.js
|
||||
@@ -4073,6 +4073,8 @@
|
||||
? "Idle"
|
||||
: "Other";
|
||||
}
|
||||
+ // Paseo backport of React 19.3.0: clear each measure once it is reported. The browser keeps
|
||||
+ // every measure for the life of the page, so a long development session held millions.
|
||||
function logComponentTrigger(fiber, startTime, endTime, trigger) {
|
||||
supportsUserTiming &&
|
||||
((reusableComponentOptions.start = startTime),
|
||||
@@ -4088,7 +4090,7 @@
|
||||
reusableComponentOptions
|
||||
)
|
||||
)
|
||||
- : performance.measure(trigger, reusableComponentOptions));
|
||||
+ : performance.measure(trigger, reusableComponentOptions), performance.clearMeasures(trigger));
|
||||
}
|
||||
function logComponentReappeared(fiber, startTime, endTime) {
|
||||
logComponentTrigger(fiber, startTime, endTime, "Reconnect");
|
||||
@@ -4159,7 +4161,7 @@
|
||||
: performance.measure(
|
||||
"\u200b" + name,
|
||||
reusableComponentOptions
|
||||
- )))
|
||||
+ ), performance.clearMeasures("\u200b" + name)))
|
||||
: null != selfTime
|
||||
? selfTime.run(
|
||||
console.timeStamp.bind(
|
||||
@@ -4229,7 +4231,7 @@
|
||||
? debugTask.run(
|
||||
performance.measure.bind(performance, "\u200b" + name, fiber)
|
||||
)
|
||||
- : performance.measure("\u200b" + name, fiber);
|
||||
+ : performance.measure("\u200b" + name, fiber), performance.clearMeasures("\u200b" + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4274,7 +4276,7 @@
|
||||
startTime
|
||||
)
|
||||
)
|
||||
- : performance.measure("\u200b" + name, startTime);
|
||||
+ : performance.measure("\u200b" + name, startTime), performance.clearMeasures("\u200b" + name);
|
||||
}
|
||||
}
|
||||
} else
|
||||
@@ -4434,7 +4436,7 @@
|
||||
? debugTask.run(
|
||||
performance.measure.bind(performance, "Recovered", startTime)
|
||||
)
|
||||
- : performance.measure("Recovered", startTime);
|
||||
+ : performance.measure("Recovered", startTime), performance.clearMeasures("Recovered");
|
||||
}
|
||||
}
|
||||
function logErroredRenderPhase(startTime, endTime, lanes, debugTask) {
|
||||
@@ -4517,7 +4519,7 @@
|
||||
? debugTask.run(
|
||||
performance.measure.bind(performance, "Errored", startTime)
|
||||
)
|
||||
- : performance.measure("Errored", startTime);
|
||||
+ : performance.measure("Errored", startTime), performance.clearMeasures("Errored");
|
||||
}
|
||||
}
|
||||
function logAnimatingPhase(startTime, endTime, debugTask) {
|
||||
@@ -17111,7 +17113,7 @@
|
||||
previousRenderStartTime
|
||||
)
|
||||
)
|
||||
- : performance.measure(isSpawnedUpdate, previousRenderStartTime));
|
||||
+ : performance.measure(isSpawnedUpdate, previousRenderStartTime), performance.clearMeasures(isSpawnedUpdate));
|
||||
}
|
||||
blockingUpdateTime = -1.1;
|
||||
blockingUpdateType = 0;
|
||||
@@ -17248,7 +17250,7 @@
|
||||
previousRenderStartTime
|
||||
)
|
||||
)
|
||||
- : performance.measure(debugTask, previousRenderStartTime))),
|
||||
+ : performance.measure(debugTask, previousRenderStartTime), performance.clearMeasures(debugTask))),
|
||||
(transitionUpdateTime = transitionStartTime = -1.1),
|
||||
(transitionUpdateType = 0),
|
||||
(transitionSuspendedTime = -1.1),
|
||||
diff --git a/node_modules/react-dom/cjs/react-dom-profiling.development.js b/node_modules/react-dom/cjs/react-dom-profiling.development.js
|
||||
index c8b583c..7fd2231 100644
|
||||
--- a/node_modules/react-dom/cjs/react-dom-profiling.development.js
|
||||
+++ b/node_modules/react-dom/cjs/react-dom-profiling.development.js
|
||||
@@ -4081,6 +4081,8 @@
|
||||
? "Idle"
|
||||
: "Other";
|
||||
}
|
||||
+ // Paseo backport of React 19.3.0: clear each measure once it is reported. The browser keeps
|
||||
+ // every measure for the life of the page, so a long development session held millions.
|
||||
function logComponentTrigger(fiber, startTime, endTime, trigger) {
|
||||
supportsUserTiming &&
|
||||
((reusableComponentOptions.start = startTime),
|
||||
@@ -4096,7 +4098,7 @@
|
||||
reusableComponentOptions
|
||||
)
|
||||
)
|
||||
- : performance.measure(trigger, reusableComponentOptions));
|
||||
+ : performance.measure(trigger, reusableComponentOptions), performance.clearMeasures(trigger));
|
||||
}
|
||||
function logComponentReappeared(fiber, startTime, endTime) {
|
||||
logComponentTrigger(fiber, startTime, endTime, "Reconnect");
|
||||
@@ -4167,7 +4169,7 @@
|
||||
: performance.measure(
|
||||
"\u200b" + name,
|
||||
reusableComponentOptions
|
||||
- )))
|
||||
+ ), performance.clearMeasures("\u200b" + name)))
|
||||
: null != selfTime
|
||||
? selfTime.run(
|
||||
console.timeStamp.bind(
|
||||
@@ -4237,7 +4239,7 @@
|
||||
? debugTask.run(
|
||||
performance.measure.bind(performance, "\u200b" + name, fiber)
|
||||
)
|
||||
- : performance.measure("\u200b" + name, fiber);
|
||||
+ : performance.measure("\u200b" + name, fiber), performance.clearMeasures("\u200b" + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4282,7 +4284,7 @@
|
||||
startTime
|
||||
)
|
||||
)
|
||||
- : performance.measure("\u200b" + name, startTime);
|
||||
+ : performance.measure("\u200b" + name, startTime), performance.clearMeasures("\u200b" + name);
|
||||
}
|
||||
}
|
||||
} else
|
||||
@@ -4442,7 +4444,7 @@
|
||||
? debugTask.run(
|
||||
performance.measure.bind(performance, "Recovered", startTime)
|
||||
)
|
||||
- : performance.measure("Recovered", startTime);
|
||||
+ : performance.measure("Recovered", startTime), performance.clearMeasures("Recovered");
|
||||
}
|
||||
}
|
||||
function logErroredRenderPhase(startTime, endTime, lanes, debugTask) {
|
||||
@@ -4525,7 +4527,7 @@
|
||||
? debugTask.run(
|
||||
performance.measure.bind(performance, "Errored", startTime)
|
||||
)
|
||||
- : performance.measure("Errored", startTime);
|
||||
+ : performance.measure("Errored", startTime), performance.clearMeasures("Errored");
|
||||
}
|
||||
}
|
||||
function logAnimatingPhase(startTime, endTime, debugTask) {
|
||||
@@ -17119,7 +17121,7 @@
|
||||
previousRenderStartTime
|
||||
)
|
||||
)
|
||||
- : performance.measure(isSpawnedUpdate, previousRenderStartTime));
|
||||
+ : performance.measure(isSpawnedUpdate, previousRenderStartTime), performance.clearMeasures(isSpawnedUpdate));
|
||||
}
|
||||
blockingUpdateTime = -1.1;
|
||||
blockingUpdateType = 0;
|
||||
@@ -17256,7 +17258,7 @@
|
||||
previousRenderStartTime
|
||||
)
|
||||
)
|
||||
- : performance.measure(debugTask, previousRenderStartTime))),
|
||||
+ : performance.measure(debugTask, previousRenderStartTime), performance.clearMeasures(debugTask))),
|
||||
(transitionUpdateTime = transitionStartTime = -1.1),
|
||||
(transitionUpdateType = 0),
|
||||
(transitionSuspendedTime = -1.1),
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,79 +0,0 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
interface Database {
|
||||
prepare(sql: string): { all(...args: string[]): unknown[] };
|
||||
close(): void;
|
||||
}
|
||||
interface Sqlite {
|
||||
DatabaseSync: new (path: string, options: { readOnly: boolean }) => Database;
|
||||
}
|
||||
interface DatabaseLogin {
|
||||
key: string | null;
|
||||
}
|
||||
export interface StorePaths {
|
||||
file: string;
|
||||
database: string;
|
||||
}
|
||||
|
||||
const fileSchema = z.object({
|
||||
"opencode-go": z.object({ type: z.literal("api"), key: z.string().min(1) }).optional(),
|
||||
});
|
||||
const rowSchema = z.object({ value: z.string() });
|
||||
const keySchema = z.object({ type: z.literal("key"), key: z.string().min(1) });
|
||||
|
||||
export function defaultStorePaths(env: NodeJS.ProcessEnv = process.env): StorePaths {
|
||||
const dataHome = env.XDG_DATA_HOME || join(env.HOME || homedir(), ".local", "share");
|
||||
const directory = join(dataHome, "opencode");
|
||||
const database = resolve(directory, env.OPENCODE_DB || "opencode.db");
|
||||
return { file: join(directory, "auth.json"), database };
|
||||
}
|
||||
|
||||
export async function readFileKey(path: string): Promise<string | null> {
|
||||
try {
|
||||
const auth = fileSchema.parse(JSON.parse(await readFile(path, "utf8")));
|
||||
return auth["opencode-go"]?.key ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function readDatabaseLogin(path: string): DatabaseLogin | null {
|
||||
// Keep the legacy source loadable on Node versions without node:sqlite.
|
||||
const sqlite = z
|
||||
.object({
|
||||
DatabaseSync: z.custom<Sqlite["DatabaseSync"]>((value) => typeof value === "function"),
|
||||
})
|
||||
.safeParse(process.getBuiltinModule?.("node:sqlite"));
|
||||
if (!sqlite.success || !existsSync(path)) return null;
|
||||
const db = new sqlite.data.DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
// V1 also has opencode.db, but only v2 has the credential table.
|
||||
const tables = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'credential'")
|
||||
.all();
|
||||
if (!tables.length) return null;
|
||||
const [value] = db
|
||||
.prepare(
|
||||
// OpenCode also selects migrated rows with no active flag, ordered by creation time.
|
||||
"SELECT value FROM credential WHERE integration_id = ? ORDER BY active DESC, time_created DESC, id DESC LIMIT 1",
|
||||
)
|
||||
.all("opencode-go");
|
||||
const row = rowSchema.safeParse(value);
|
||||
if (!row.success) return { key: null };
|
||||
let credential: unknown;
|
||||
try {
|
||||
credential = JSON.parse(row.data.value);
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError) return { key: null };
|
||||
throw error;
|
||||
}
|
||||
const parsed = keySchema.safeParse(credential);
|
||||
return { key: parsed.success ? parsed.data.key : null };
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,13 @@
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import { discover, fetchUsage } from "./usage.js";
|
||||
import { defaultStorePaths } from "./stores.js";
|
||||
|
||||
import { inputSchema } from "../shared/input.js";
|
||||
|
||||
let fixtureDirectory: string;
|
||||
let fixturePath: string;
|
||||
function stores(path: string) {
|
||||
return { file: path, database: join(dirname(path), "opencode.db") };
|
||||
}
|
||||
async function database() {
|
||||
const { DatabaseSync } = await import("node:sqlite");
|
||||
const db = new DatabaseSync(join(fixtureDirectory, "opencode.db"));
|
||||
db.exec(
|
||||
"CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, value TEXT, active INTEGER, time_updated INTEGER, time_created INTEGER DEFAULT 0)",
|
||||
);
|
||||
return db;
|
||||
}
|
||||
beforeEach(async () => {
|
||||
fixtureDirectory = await mkdtemp(join(tmpdir(), "go-default-"));
|
||||
fixturePath = join(fixtureDirectory, "auth.json");
|
||||
@@ -34,9 +22,6 @@ afterEach(async () => {
|
||||
|
||||
test("discovery input rejects an explicit API key", () => {
|
||||
expect(inputSchema.safeParse({ apiKey: "unused" }).success).toBe(false);
|
||||
expect(
|
||||
inputSchema.safeParse({ store: "database", path: "opencode.db", apiKey: "unused" }).success,
|
||||
).toBe(false);
|
||||
expect(() => inputSchema.parse({})).toThrow();
|
||||
});
|
||||
|
||||
@@ -48,216 +33,14 @@ const upstreamResponse = {
|
||||
},
|
||||
};
|
||||
|
||||
test("uses the active v2 Go key instead of a stale legacy key without writing either store", async () => {
|
||||
const databasePath = join(fixtureDirectory, "opencode.db");
|
||||
const db = await database();
|
||||
const insert = db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
);
|
||||
insert.run("inactive", "opencode-go", JSON.stringify({ type: "key", key: "inactive-key" }), 0, 3);
|
||||
insert.run("active", "opencode-go", JSON.stringify({ type: "key", key: "active-key" }), 1, 1);
|
||||
insert.run("zen", "opencode", JSON.stringify({ type: "key", key: "zen-key" }), 1, 4);
|
||||
db.close();
|
||||
const beforeDatabase = await readFile(databasePath);
|
||||
const beforeFile = await readFile(fixturePath);
|
||||
const accounts = await discover(stores(fixturePath));
|
||||
expect(accounts).toEqual([
|
||||
{
|
||||
key: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
input: { store: "database", path: databasePath },
|
||||
},
|
||||
]);
|
||||
const input = inputSchema.parse(accounts[0]!.input);
|
||||
const report = await fetchUsage(input, async (_url, init) => {
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer active-key");
|
||||
return Response.json(upstreamResponse);
|
||||
});
|
||||
expect(report.status).toBe("available");
|
||||
expect(report.windows.map((window) => window.usedPct)).toEqual([21, 42, 100]);
|
||||
expect(await readFile(databasePath)).toEqual(beforeDatabase);
|
||||
expect(await readFile(fixturePath)).toEqual(beforeFile);
|
||||
});
|
||||
|
||||
test("discovers v2 Go usage without a legacy auth.json", async () => {
|
||||
const db = await database();
|
||||
db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
).run("go", "opencode-go", JSON.stringify({ type: "key", key: "database-key" }), 1, 1);
|
||||
db.close();
|
||||
await rm(fixturePath);
|
||||
const accounts = await discover(stores(fixturePath));
|
||||
expect(accounts).toEqual([
|
||||
{
|
||||
key: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
input: { store: "database", path: join(fixtureDirectory, "opencode.db") },
|
||||
},
|
||||
]);
|
||||
expect(JSON.stringify(accounts)).not.toContain("database-key");
|
||||
});
|
||||
|
||||
test("refresh follows the active Go account and re-reads its rotated key", async () => {
|
||||
const db = await database();
|
||||
const insert = db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
);
|
||||
insert.run("first", "opencode-go", JSON.stringify({ type: "key", key: "first-key" }), 1, 1);
|
||||
insert.run("second", "opencode-go", JSON.stringify({ type: "key", key: "second-key" }), 0, 2);
|
||||
db.close();
|
||||
const paths = stores(fixturePath);
|
||||
const accounts = await discover(paths);
|
||||
const input = inputSchema.parse(accounts[0]!.input);
|
||||
const { DatabaseSync } = await import("node:sqlite");
|
||||
const writer = new DatabaseSync(paths.database);
|
||||
writer.exec("UPDATE credential SET active = CASE id WHEN 'second' THEN 1 ELSE 0 END");
|
||||
writer
|
||||
.prepare("UPDATE credential SET value = ? WHERE id = 'second'")
|
||||
.run(JSON.stringify({ type: "key", key: "rotated-key" }));
|
||||
writer.close();
|
||||
expect(await discover(paths)).toEqual(accounts);
|
||||
const before = await readFile(paths.database);
|
||||
const report = await fetchUsage(input, async (_url, init) => {
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer rotated-key");
|
||||
return Response.json(upstreamResponse);
|
||||
});
|
||||
expect(report.status).toBe("available");
|
||||
expect(JSON.stringify(report)).not.toContain("rotated-key");
|
||||
expect(await readFile(paths.database)).toEqual(before);
|
||||
});
|
||||
|
||||
test.each([
|
||||
[null, false],
|
||||
[null, true],
|
||||
[0, false],
|
||||
[0, true],
|
||||
])("discovers a selected Go key with active=%s and legacy file=%s", async (active, legacy) => {
|
||||
const db = await database();
|
||||
db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
).run("migrated", "opencode-go", JSON.stringify({ type: "key", key: "migrated-key" }), active, 1);
|
||||
db.close();
|
||||
if (!legacy) await rm(fixturePath);
|
||||
const accounts = await discover(stores(fixturePath));
|
||||
expect(accounts).toEqual([
|
||||
{
|
||||
key: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
input: { store: "database", path: join(fixtureDirectory, "opencode.db") },
|
||||
},
|
||||
]);
|
||||
const report = await fetchUsage(inputSchema.parse(accounts[0]!.input), async (_url, init) => {
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer migrated-key");
|
||||
return Response.json(upstreamResponse);
|
||||
});
|
||||
expect(report.status).toBe("available");
|
||||
});
|
||||
|
||||
test("selects the newest created Go key when no explicit active key exists", async () => {
|
||||
const db = await database();
|
||||
const insert = db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_created, time_updated) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
);
|
||||
insert.run("older", "opencode-go", JSON.stringify({ type: "key", key: "older-key" }), null, 1, 9);
|
||||
insert.run("newer-a", "opencode-go", JSON.stringify({ type: "key", key: "tie-key" }), null, 2, 8);
|
||||
insert.run(
|
||||
"newer-b",
|
||||
"opencode-go",
|
||||
JSON.stringify({ type: "key", key: "selected-key" }),
|
||||
null,
|
||||
2,
|
||||
1,
|
||||
);
|
||||
db.close();
|
||||
const accounts = await discover(stores(fixturePath));
|
||||
expect(accounts).toHaveLength(1);
|
||||
await fetchUsage(inputSchema.parse(accounts[0]!.input), async (_url, init) => {
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer selected-key");
|
||||
return Response.json(upstreamResponse);
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
["other provider", "opencode", 1, JSON.stringify({ type: "key", key: "zen-key" })],
|
||||
["Console OAuth", "opencode-go", 1, JSON.stringify({ type: "oauth", access: "oauth-token" })],
|
||||
["malformed credential", "opencode-go", 1, "invalid JSON"],
|
||||
["empty key", "opencode-go", 1, JSON.stringify({ type: "key", key: "" })],
|
||||
])(
|
||||
"does not revive a legacy key for a v2 store with %s",
|
||||
async (_name, provider, active, value) => {
|
||||
const db = await database();
|
||||
db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
).run("credential", provider, value, active, 1);
|
||||
db.close();
|
||||
expect(await discover(stores(fixturePath))).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
test("keeps legacy discovery when the v1 session database has no credential table", async () => {
|
||||
const { DatabaseSync } = await import("node:sqlite");
|
||||
const db = new DatabaseSync(join(fixtureDirectory, "opencode.db"));
|
||||
db.exec("CREATE TABLE session (id TEXT PRIMARY KEY)");
|
||||
db.close();
|
||||
expect(await discover(stores(fixturePath))).toEqual([
|
||||
{
|
||||
key: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
input: { store: "file", path: fixturePath },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("fails before fetching when the selected database disappears", async () => {
|
||||
await expect(
|
||||
fetchUsage({ store: "database", path: join(fixtureDirectory, "missing.db") }, async () => {
|
||||
throw new Error("must not fetch");
|
||||
}),
|
||||
).rejects.toThrow("login store no longer exists");
|
||||
});
|
||||
|
||||
test("resolves default and overridden OpenCode store paths", () => {
|
||||
expect(defaultStorePaths({ HOME: fixtureDirectory })).toEqual({
|
||||
file: join(fixtureDirectory, ".local", "share", "opencode", "auth.json"),
|
||||
database: join(fixtureDirectory, ".local", "share", "opencode", "opencode.db"),
|
||||
});
|
||||
const customDatabase = join(fixtureDirectory, "custom.db");
|
||||
expect(
|
||||
defaultStorePaths({ XDG_DATA_HOME: fixtureDirectory, OPENCODE_DB: customDatabase }),
|
||||
).toEqual({
|
||||
file: join(fixtureDirectory, "opencode", "auth.json"),
|
||||
database: customDatabase,
|
||||
});
|
||||
});
|
||||
|
||||
test("discovers a relative OPENCODE_DB under the OpenCode data directory", async () => {
|
||||
const paths = defaultStorePaths({
|
||||
XDG_DATA_HOME: fixtureDirectory,
|
||||
OPENCODE_DB: "go.db",
|
||||
});
|
||||
const databasePath = join(fixtureDirectory, "opencode", "go.db");
|
||||
await mkdir(dirname(databasePath));
|
||||
const { DatabaseSync } = await import("node:sqlite");
|
||||
const db = new DatabaseSync(databasePath);
|
||||
db.exec(
|
||||
"CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, value TEXT, active INTEGER, time_updated INTEGER, time_created INTEGER DEFAULT 0)",
|
||||
);
|
||||
db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
).run("go", "opencode-go", JSON.stringify({ type: "key", key: "relative-key" }), 1, 1);
|
||||
db.close();
|
||||
expect(await discover(paths)).toEqual([
|
||||
{
|
||||
key: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
input: { store: "database", path: databasePath },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("discovers and fetches the default key from read-only auth.json", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "paseo-go-usage-"));
|
||||
const path = join(directory, "auth.json");
|
||||
const content = JSON.stringify({ "opencode-go": { type: "api", key: "fixture-key" } });
|
||||
try {
|
||||
await writeFile(path, content);
|
||||
expect(await discover(stores(path))).toEqual([
|
||||
{ key: expect.stringMatching(/^[a-f0-9]{64}$/), input: { store: "file", path } },
|
||||
expect(await discover(path)).toEqual([
|
||||
{ key: expect.stringMatching(/^[a-f0-9]{64}$/), input: { path } },
|
||||
]);
|
||||
const requests: Array<{ url: string; authorization: string | null }> = [];
|
||||
const fetchApi = async (url: string | URL | Request, init?: RequestInit) => {
|
||||
@@ -267,7 +50,7 @@ test("discovers and fetches the default key from read-only auth.json", async ()
|
||||
});
|
||||
return Response.json(upstreamResponse);
|
||||
};
|
||||
const report = await fetchUsage({ store: "file", path }, fetchApi);
|
||||
const report = await fetchUsage({ path }, fetchApi as typeof fetch);
|
||||
expect(requests).toEqual([
|
||||
{ url: "https://opencode.ai/zen/go/v1/usage", authorization: "Bearer fixture-key" },
|
||||
]);
|
||||
@@ -292,9 +75,9 @@ test("omits default discovery when auth.json lacks an OpenCode Go API key", asyn
|
||||
const path = join(directory, "auth.json");
|
||||
try {
|
||||
await writeFile(path, JSON.stringify({ openai: { type: "oauth", access: "other-token" } }));
|
||||
expect(await discover(stores(path))).toEqual([]);
|
||||
expect(await discover(path)).toEqual([]);
|
||||
await expect(
|
||||
fetchUsage({ store: "file", path }, async () => {
|
||||
fetchUsage({ path }, async () => {
|
||||
throw new Error("must not fetch");
|
||||
}),
|
||||
).rejects.toThrow("login store no longer exists");
|
||||
@@ -305,7 +88,7 @@ test("omits default discovery when auth.json lacks an OpenCode Go API key", asyn
|
||||
|
||||
test.each([401, 403])("maps HTTP %i to unavailable", async (status) => {
|
||||
const report = await fetchUsage(
|
||||
{ store: "file", path: fixturePath },
|
||||
{ path: fixturePath },
|
||||
async () => new Response(null, { status }),
|
||||
);
|
||||
expect(report).toEqual({
|
||||
@@ -317,19 +100,5 @@ test.each([401, 403])("maps HTTP %i to unavailable", async (status) => {
|
||||
test.each(["missing file", "unrelated file"])("discovers no accounts for %s", async (scenario) => {
|
||||
const path = join(fixtureDirectory, "missing.json");
|
||||
if (scenario === "unrelated file") await writeFile(path, "{}");
|
||||
expect(await discover(stores(path))).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps the account identity when OpenCode v2 imports the legacy Go login", async () => {
|
||||
const paths = stores(fixturePath);
|
||||
const [legacy] = await discover(paths);
|
||||
const db = await database();
|
||||
db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
).run("imported", "opencode-go", JSON.stringify({ type: "key", key: "fixture-secret" }), null, 1);
|
||||
db.close();
|
||||
const [migrated] = await discover(paths);
|
||||
expect(migrated!.input).toEqual({ store: "database", path: paths.database });
|
||||
// Usage settings are saved per account, so the card keeps its visibility and position.
|
||||
expect(migrated!.key).toBe(legacy!.key);
|
||||
expect(await discover(path)).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
hashAccountKey,
|
||||
@@ -8,7 +11,15 @@ import {
|
||||
type UsageReport,
|
||||
} from "@getpaseo/plugin/server/usage";
|
||||
import type { Input } from "../shared/input.js";
|
||||
import { defaultStorePaths, readDatabaseLogin, readFileKey } from "./stores.js";
|
||||
|
||||
const authSchema = z
|
||||
.object({
|
||||
"opencode-go": z
|
||||
.object({ type: z.literal("api"), key: z.string().min(1) })
|
||||
.passthrough()
|
||||
.optional(),
|
||||
})
|
||||
.passthrough();
|
||||
const windowSchema = z.object({
|
||||
status: z.enum(["ok", "rate-limited"]),
|
||||
percent: z.number().finite(),
|
||||
@@ -18,32 +29,32 @@ const responseSchema = z.object({
|
||||
usage: z.object({ rolling: windowSchema, weekly: windowSchema, monthly: windowSchema }),
|
||||
});
|
||||
|
||||
export async function discover(paths = defaultStorePaths()): Promise<UsageAccount[]> {
|
||||
// One OpenCode data directory holds one Go login, whichever store it lives in. Usage settings
|
||||
// are saved per account, so a login OpenCode v2 imports keeps the identity it had in auth.json.
|
||||
const key = hashAccountKey(paths.file);
|
||||
const login = readDatabaseLogin(paths.database);
|
||||
if (login) {
|
||||
return login.key
|
||||
? [
|
||||
{
|
||||
key,
|
||||
input: { store: "database", path: paths.database },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
function authPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
return join(
|
||||
env.XDG_DATA_HOME || join(env.HOME || homedir(), ".local", "share"),
|
||||
"opencode",
|
||||
"auth.json",
|
||||
);
|
||||
}
|
||||
|
||||
export async function readDefaultKey(path = authPath()): Promise<string | null> {
|
||||
try {
|
||||
const auth = authSchema.parse(JSON.parse(await readFile(path, "utf8")));
|
||||
return auth["opencode-go"]?.key ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return (await readFileKey(paths.file))
|
||||
? [{ key, input: { store: "file", path: paths.file } }]
|
||||
: [];
|
||||
}
|
||||
|
||||
export async function discover(path = authPath()): Promise<UsageAccount[]> {
|
||||
return (await readDefaultKey(path)) ? [{ key: hashAccountKey(path), input: { path } }] : [];
|
||||
}
|
||||
|
||||
export async function fetchUsage(
|
||||
input: Input,
|
||||
fetchApi: typeof fetch = fetch,
|
||||
): Promise<UsageReport> {
|
||||
const apiKey =
|
||||
input.store === "database" ? readDatabaseLogin(input.path)?.key : await readFileKey(input.path);
|
||||
const apiKey = await readDefaultKey(input.path);
|
||||
if (!apiKey) throw new Error("OpenCode Go login store no longer exists");
|
||||
const response = await fetchApi("https://opencode.ai/zen/go/v1/usage", {
|
||||
headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { z } from "zod";
|
||||
export const inputSchema = z
|
||||
.object({ store: z.enum(["file", "database"]), path: z.string().min(1) })
|
||||
.strict();
|
||||
export const inputSchema = z.object({ path: z.string().min(1) }).strict();
|
||||
export type Input = z.infer<typeof inputSchema>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
@@ -54,19 +54,6 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("copyWorktreeIncludes", () => {
|
||||
it("does not run a command the source repository configures as its fsmonitor", async () => {
|
||||
const marker = join(root, "fsmonitor.marker");
|
||||
const hook = join(root, "fsmonitor-hook.sh");
|
||||
await writeFile(hook, `#!/bin/sh\n: > '${marker}'\nprintf '1\\n'\n`);
|
||||
await chmod(hook, 0o755);
|
||||
await writeSource({ ".gitignore": ".env\n", ".worktreeinclude": ".env\n", ".env": "A=1" });
|
||||
execFileSync("git", ["add", ".gitignore", ".worktreeinclude"], { cwd: source });
|
||||
execFileSync("git", ["config", "core.fsmonitor", hook], { cwd: source });
|
||||
|
||||
expect(await copied()).toEqual([".env"]);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not search inside an ignored directory that no pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n.env\n",
|
||||
|
||||
@@ -14,13 +14,8 @@ export type CopyResult =
|
||||
| { kind: "no-include-file" }
|
||||
| { kind: "copied"; copied: string[]; skipped: string[] };
|
||||
|
||||
// `core.fsmonitor=false` prevents repository config from launching a command.
|
||||
// `safe.bareRepository=explicit` stops git from adopting a directory that only
|
||||
// looks like a bare repository.
|
||||
const GIT_CONFIG_ARGS = ["-c", "core.fsmonitor=false", "-c", "safe.bareRepository=explicit"];
|
||||
|
||||
async function git(cwd: string, args: string[], input?: string): Promise<string> {
|
||||
const child = exec("git", [...GIT_CONFIG_ARGS, ...args], { cwd, maxBuffer: 64 * 1024 * 1024 });
|
||||
const child = exec("git", args, { cwd, maxBuffer: 64 * 1024 * 1024 });
|
||||
if (input !== undefined) {
|
||||
child.child.stdin?.end(input);
|
||||
}
|
||||
|
||||
@@ -23,10 +23,29 @@ const patchedPackages = [
|
||||
// Layout constraints: backport of https://github.com/jpudysz/react-native-unistyles/pull/1357
|
||||
// (commit from the root the commit hands us, so a concurrent window-size commit is kept).
|
||||
// Remove the ShadowTreeManager hunk when the installed release includes that PR.
|
||||
// Web stylesheet: backport of https://github.com/jpudysz/react-native-unistyles/pull/1354
|
||||
// (3.8.0). Classes are added and removed as CSSOM rules, not by rewriting the style tag, which
|
||||
// made the browser restyle the whole document. Remove the web/css hunks at >= 3.8.0.
|
||||
{
|
||||
nodeModulesPath: "node_modules/react-native-unistyles",
|
||||
patchPrefix: "react-native-unistyles+",
|
||||
},
|
||||
// Portal state lives in a store that each host subscribes to. As the provider's context value it
|
||||
// changed on every portal add, update and remove, and React searched every fiber under the
|
||||
// provider (the whole app) for consumers. No upstream fix; keep while the app uses this package.
|
||||
// Keyed hosts: backport of https://github.com/gorhom/react-native-portal/pull/62, unreleased
|
||||
// after 1.0.14. Remove the PortalHost hunks when an installed release includes it.
|
||||
{
|
||||
nodeModulesPath: "node_modules/@gorhom/portal",
|
||||
patchPrefix: "@gorhom+portal+",
|
||||
},
|
||||
// Backport of React 19.3.0 to the development builds: clear each render timing after reporting
|
||||
// it. The browser keeps every performance measure for the life of the page, so a development
|
||||
// session held millions of them and gigabytes of memory. Remove when react-dom is >= 19.3.0.
|
||||
{
|
||||
nodeModulesPath: "node_modules/react-dom",
|
||||
patchPrefix: "react-dom+",
|
||||
},
|
||||
// Backport of https://github.com/software-mansion/react-native-reanimated/pull/10435
|
||||
// (Reanimated 4.7.1): skip synchronous Android prop updates for unmounted view tags
|
||||
// instead of throwing and printing a full stack trace on the UI thread per tag per event.
|
||||
|
||||
Reference in New Issue
Block a user