Refactor mobile remote search and review state
- Move composer path search and source-control discovery into shared managed state - Persist review async/loading state in atoms and add coverage - Update mobile/web composers and review highlighter initialization
This commit is contained in:
1 parent
ab95f11360
commit
e793c07a21
37 files changed
+1366
-545
No files matched your search
@@ -9,6 +9,8 @@
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/mobile/android/**",
|
||||
"apps/mobile/ios/**",
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts",
|
||||
"apps/mobile/uniwind-types.d.ts",
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/mobile/android/**",
|
||||
"apps/mobile/ios/**",
|
||||
"apps/mobile/uniwind-types.d.ts"
|
||||
],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
|
||||
@@ -1,101 +1,15 @@
|
||||
import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";
|
||||
import { createContext, type ReactNode, useContext, useMemo } from "react";
|
||||
|
||||
import {
|
||||
getActiveReviewHighlighterEngine,
|
||||
prepareReviewHighlighter,
|
||||
prepareReviewHighlighterLanguages,
|
||||
type ReviewHighlighterEngine,
|
||||
} from "./shikiReviewHighlighter";
|
||||
import { type ReviewHighlighterState, useReviewHighlighterState } from "./reviewHighlighterState";
|
||||
|
||||
type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
|
||||
|
||||
interface ReviewHighlighterContextValue {
|
||||
readonly engine: ReviewHighlighterEngine | null;
|
||||
readonly error: string | null;
|
||||
readonly status: ReviewHighlighterStatus;
|
||||
}
|
||||
|
||||
const ReviewHighlighterContext = createContext<ReviewHighlighterContextValue>({
|
||||
const ReviewHighlighterContext = createContext<ReviewHighlighterState>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
const REVIEW_INITIAL_LANGUAGES = [
|
||||
"typescript",
|
||||
"tsx",
|
||||
"javascript",
|
||||
"jsx",
|
||||
"json",
|
||||
"yaml",
|
||||
"bash",
|
||||
] as const;
|
||||
|
||||
function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
function logReviewHighlighterProviderDiagnostic(
|
||||
message: string,
|
||||
details?: Record<string, unknown>,
|
||||
): void {
|
||||
if (!isReviewHighlighterProviderDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (details) {
|
||||
console.log(`[review-highlighter-provider] ${message}`, details);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[review-highlighter-provider] ${message}`);
|
||||
}
|
||||
|
||||
export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {
|
||||
const [value, setValue] = useState<ReviewHighlighterContextValue>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
setValue({ engine: null, error: null, status: "initializing" });
|
||||
|
||||
void (async () => {
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
await prepareReviewHighlighter();
|
||||
await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);
|
||||
const engine = await getActiveReviewHighlighterEngine();
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
setValue({ engine, error: null, status: "ready" });
|
||||
} catch (error) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
|
||||
setValue({ engine: null, error: message, status: "error" });
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const value = useReviewHighlighterState();
|
||||
const contextValue = useMemo(() => value, [value]);
|
||||
|
||||
return (
|
||||
@@ -105,6 +19,6 @@ export function ReviewHighlighterProvider(props: { readonly children: ReactNode
|
||||
);
|
||||
}
|
||||
|
||||
export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {
|
||||
export function useReviewHighlighterStatus(): ReviewHighlighterState {
|
||||
return useContext(ReviewHighlighterContext);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { assert, beforeEach, it } from "vitest";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
createReviewHighlighterManager,
|
||||
IDLE_REVIEW_HIGHLIGHTER_STATE,
|
||||
} from "./reviewHighlighterState";
|
||||
|
||||
let registry = AtomRegistry.make();
|
||||
|
||||
beforeEach(() => {
|
||||
registry.dispose();
|
||||
registry = AtomRegistry.make();
|
||||
});
|
||||
|
||||
function flushAsyncWork(): Promise<void> {
|
||||
return Promise.resolve().then(() => undefined);
|
||||
}
|
||||
|
||||
it("initializes review highlighter state once", async () => {
|
||||
let prepareCalls = 0;
|
||||
let languageCalls = 0;
|
||||
let engineCalls = 0;
|
||||
const manager = createReviewHighlighterManager({
|
||||
getRegistry: () => registry,
|
||||
loader: {
|
||||
prepare: async () => {
|
||||
prepareCalls += 1;
|
||||
},
|
||||
prepareLanguages: async () => {
|
||||
languageCalls += 1;
|
||||
},
|
||||
getEngine: async () => {
|
||||
engineCalls += 1;
|
||||
return "javascript";
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(manager.getSnapshot(), IDLE_REVIEW_HIGHLIGHTER_STATE);
|
||||
|
||||
await Promise.all([manager.initialize(), manager.initialize()]);
|
||||
await manager.initialize();
|
||||
|
||||
assert.strictEqual(prepareCalls, 1);
|
||||
assert.strictEqual(languageCalls, 1);
|
||||
assert.strictEqual(engineCalls, 1);
|
||||
assert.deepStrictEqual(manager.getSnapshot(), {
|
||||
engine: "javascript",
|
||||
error: null,
|
||||
status: "ready",
|
||||
});
|
||||
});
|
||||
|
||||
it("stores initialization failures in atom state", async () => {
|
||||
const manager = createReviewHighlighterManager({
|
||||
getRegistry: () => registry,
|
||||
loader: {
|
||||
prepare: async () => {
|
||||
throw new Error("load failed");
|
||||
},
|
||||
prepareLanguages: async () => undefined,
|
||||
getEngine: async () => "javascript",
|
||||
},
|
||||
});
|
||||
|
||||
void manager.initialize();
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.deepStrictEqual(manager.getSnapshot(), {
|
||||
engine: null,
|
||||
error: "load failed",
|
||||
status: "error",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import {
|
||||
getActiveReviewHighlighterEngine,
|
||||
prepareReviewHighlighter,
|
||||
prepareReviewHighlighterLanguages,
|
||||
type ReviewHighlighterEngine,
|
||||
} from "./shikiReviewHighlighter";
|
||||
|
||||
export type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
|
||||
|
||||
export interface ReviewHighlighterState {
|
||||
readonly engine: ReviewHighlighterEngine | null;
|
||||
readonly error: string | null;
|
||||
readonly status: ReviewHighlighterStatus;
|
||||
}
|
||||
|
||||
export interface ReviewHighlighterLoader {
|
||||
readonly prepare: () => Promise<void>;
|
||||
readonly prepareLanguages: (languages: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly getEngine: () => Promise<ReviewHighlighterEngine>;
|
||||
}
|
||||
|
||||
const REVIEW_INITIAL_LANGUAGES = [
|
||||
"typescript",
|
||||
"tsx",
|
||||
"javascript",
|
||||
"jsx",
|
||||
"json",
|
||||
"yaml",
|
||||
"bash",
|
||||
] as const;
|
||||
|
||||
export const IDLE_REVIEW_HIGHLIGHTER_STATE = Object.freeze<ReviewHighlighterState>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
const INITIALIZING_REVIEW_HIGHLIGHTER_STATE = Object.freeze<ReviewHighlighterState>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "initializing",
|
||||
});
|
||||
|
||||
export const reviewHighlighterStateAtom = Atom.make(IDLE_REVIEW_HIGHLIGHTER_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:review-highlighter"),
|
||||
);
|
||||
|
||||
function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
function logReviewHighlighterProviderDiagnostic(
|
||||
message: string,
|
||||
details?: Record<string, unknown>,
|
||||
): void {
|
||||
if (!isReviewHighlighterProviderDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (details) {
|
||||
console.log(`[review-highlighter-provider] ${message}`, details);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[review-highlighter-provider] ${message}`);
|
||||
}
|
||||
|
||||
export function createReviewHighlighterManager(config: {
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
readonly loader: ReviewHighlighterLoader;
|
||||
readonly languages?: ReadonlyArray<string>;
|
||||
}) {
|
||||
let started = false;
|
||||
let inFlight: Promise<void> | null = null;
|
||||
|
||||
function getSnapshot(): ReviewHighlighterState {
|
||||
return config.getRegistry().get(reviewHighlighterStateAtom);
|
||||
}
|
||||
|
||||
function setState(state: ReviewHighlighterState): void {
|
||||
config.getRegistry().set(reviewHighlighterStateAtom, state);
|
||||
}
|
||||
|
||||
function initialize(): Promise<void> {
|
||||
if (inFlight) {
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
if (started && getSnapshot().status === "ready") {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
started = true;
|
||||
setState(INITIALIZING_REVIEW_HIGHLIGHTER_STATE);
|
||||
|
||||
inFlight = (async () => {
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
await config.loader.prepare();
|
||||
await config.loader.prepareLanguages(config.languages ?? REVIEW_INITIAL_LANGUAGES);
|
||||
const engine = await config.loader.getEngine();
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
setState({ engine, error: null, status: "ready" });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
|
||||
setState({ engine: null, error: message, status: "error" });
|
||||
} finally {
|
||||
inFlight = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
started = false;
|
||||
inFlight = null;
|
||||
setState(IDLE_REVIEW_HIGHLIGHTER_STATE);
|
||||
}
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
initialize,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
|
||||
const reviewHighlighterManager = createReviewHighlighterManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
loader: {
|
||||
prepare: prepareReviewHighlighter,
|
||||
prepareLanguages: prepareReviewHighlighterLanguages,
|
||||
getEngine: getActiveReviewHighlighterEngine,
|
||||
},
|
||||
});
|
||||
|
||||
export function useReviewHighlighterState(): ReviewHighlighterState {
|
||||
useEffect(() => {
|
||||
void reviewHighlighterManager.initialize();
|
||||
}, []);
|
||||
|
||||
return useAtomValue(reviewHighlighterStateAtom);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { parsePatchFiles, type ChangeTypes, type FileDiffMetadata } from "@pierre/diffs/utils";
|
||||
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
|
||||
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
|
||||
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { assert, it } from "vitest";
|
||||
|
||||
import {
|
||||
getReviewAsyncStateSnapshot,
|
||||
setReviewAsyncError,
|
||||
setReviewGitDiffsLoading,
|
||||
setReviewTurnDiffLoading,
|
||||
} from "./reviewState";
|
||||
|
||||
it("stores review async loading and error state in atoms", () => {
|
||||
const threadKey = `env-local:thread-review-state-${Date.now()}`;
|
||||
|
||||
setReviewGitDiffsLoading(threadKey, true);
|
||||
setReviewTurnDiffLoading(threadKey, "turn-1", true);
|
||||
setReviewAsyncError(threadKey, "load failed");
|
||||
|
||||
assert.deepStrictEqual(getReviewAsyncStateSnapshot(threadKey), {
|
||||
loadingGitDiffs: true,
|
||||
loadingTurnIds: { "turn-1": true },
|
||||
error: "load failed",
|
||||
});
|
||||
|
||||
setReviewGitDiffsLoading(threadKey, false);
|
||||
setReviewTurnDiffLoading(threadKey, "turn-1", false);
|
||||
setReviewAsyncError(threadKey, null);
|
||||
|
||||
assert.deepStrictEqual(getReviewAsyncStateSnapshot(threadKey), {
|
||||
loadingGitDiffs: false,
|
||||
loadingTurnIds: {},
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,12 @@ import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
|
||||
|
||||
const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
|
||||
const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});
|
||||
const EMPTY_REVIEW_LOADING_TURN_IDS = Object.freeze<Readonly<Record<string, boolean>>>({});
|
||||
const EMPTY_REVIEW_ASYNC_STATE = Object.freeze<ReviewAsyncState>({
|
||||
loadingGitDiffs: false,
|
||||
loadingTurnIds: EMPTY_REVIEW_LOADING_TURN_IDS,
|
||||
error: null,
|
||||
});
|
||||
const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze<
|
||||
Readonly<Record<string, ReadonlyArray<string> | undefined>>
|
||||
>({});
|
||||
@@ -24,6 +30,10 @@ const EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM = Atom.make<string | null>(null).pip
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:review:selected-section-id:null"),
|
||||
);
|
||||
const EMPTY_REVIEW_ASYNC_STATE_ATOM = Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:review:async-state:null"),
|
||||
);
|
||||
const EMPTY_REVIEW_SECTION_FILE_IDS_ATOM = Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:review:section-file-ids:null"),
|
||||
@@ -50,6 +60,13 @@ const reviewSelectedSectionIdByThreadKeyAtom = Atom.family((threadKey: string) =
|
||||
),
|
||||
);
|
||||
|
||||
const reviewAsyncStateByThreadKeyAtom = Atom.family((threadKey: string) =>
|
||||
Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`mobile:review:async-state:${threadKey}`),
|
||||
),
|
||||
);
|
||||
|
||||
const reviewExpandedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
|
||||
Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
|
||||
Atom.keepAlive,
|
||||
@@ -83,6 +100,7 @@ export interface ReviewCacheForThread {
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string>>;
|
||||
readonly selectedSectionId: string | null;
|
||||
readonly asyncState: ReviewAsyncState;
|
||||
readonly expandedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
|
||||
readonly revealedLargeFileIdsBySection: Readonly<
|
||||
Record<string, ReadonlyArray<string> | undefined>
|
||||
@@ -90,6 +108,12 @@ export interface ReviewCacheForThread {
|
||||
readonly viewedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
|
||||
}
|
||||
|
||||
export interface ReviewAsyncState {
|
||||
readonly loadingGitDiffs: boolean;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean>>;
|
||||
readonly error: string | null;
|
||||
}
|
||||
|
||||
function buildThreadKey(input: {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly threadId?: ThreadId;
|
||||
@@ -119,6 +143,9 @@ export function useReviewCacheForThread(input: {
|
||||
? reviewSelectedSectionIdByThreadKeyAtom(threadKey)
|
||||
: EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM,
|
||||
);
|
||||
const asyncState = useAtomValue(
|
||||
threadKey ? reviewAsyncStateByThreadKeyAtom(threadKey) : EMPTY_REVIEW_ASYNC_STATE_ATOM,
|
||||
);
|
||||
const expandedFileIdsBySection = useAtomValue(
|
||||
threadKey
|
||||
? reviewExpandedFileIdsByThreadKeyAtom(threadKey)
|
||||
@@ -138,6 +165,7 @@ export function useReviewCacheForThread(input: {
|
||||
gitSections,
|
||||
turnDiffById,
|
||||
selectedSectionId,
|
||||
asyncState,
|
||||
expandedFileIdsBySection,
|
||||
revealedLargeFileIdsBySection,
|
||||
viewedFileIdsBySection,
|
||||
@@ -164,6 +192,51 @@ export function setReviewSelectedSectionId(threadKey: string, sectionId: string
|
||||
appAtomRegistry.set(reviewSelectedSectionIdByThreadKeyAtom(threadKey), sectionId);
|
||||
}
|
||||
|
||||
function updateReviewAsyncState(
|
||||
threadKey: string,
|
||||
update: (current: ReviewAsyncState) => ReviewAsyncState,
|
||||
): void {
|
||||
const atom = reviewAsyncStateByThreadKeyAtom(threadKey);
|
||||
appAtomRegistry.set(atom, update(appAtomRegistry.get(atom)));
|
||||
}
|
||||
|
||||
export function setReviewGitDiffsLoading(threadKey: string, loadingGitDiffs: boolean): void {
|
||||
updateReviewAsyncState(threadKey, (current) => ({
|
||||
...current,
|
||||
loadingGitDiffs,
|
||||
}));
|
||||
}
|
||||
|
||||
export function setReviewTurnDiffLoading(
|
||||
threadKey: string,
|
||||
sectionId: string,
|
||||
isLoading: boolean,
|
||||
): void {
|
||||
updateReviewAsyncState(threadKey, (current) => {
|
||||
const loadingTurnIds = { ...current.loadingTurnIds };
|
||||
if (isLoading) {
|
||||
loadingTurnIds[sectionId] = true;
|
||||
} else {
|
||||
delete loadingTurnIds[sectionId];
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
loadingTurnIds,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function setReviewAsyncError(threadKey: string, error: string | null): void {
|
||||
updateReviewAsyncState(threadKey, (current) => ({
|
||||
...current,
|
||||
error,
|
||||
}));
|
||||
}
|
||||
|
||||
export function getReviewAsyncStateSnapshot(threadKey: string): ReviewAsyncState {
|
||||
return appAtomRegistry.get(reviewAsyncStateByThreadKeyAtom(threadKey));
|
||||
}
|
||||
|
||||
export function updateReviewExpandedFileIds(
|
||||
threadKey: string,
|
||||
sectionId: string,
|
||||
|
||||
@@ -9,7 +9,7 @@ import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import githubDarkDefault from "@shikijs/themes/github-dark-default";
|
||||
import githubLightDefault from "@shikijs/themes/github-light-default";
|
||||
import { getFiletypeFromFileName } from "@pierre/diffs/utils";
|
||||
import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
|
||||
|
||||
import {
|
||||
resolveReviewHighlighterEngine,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
@@ -12,8 +12,11 @@ import {
|
||||
getReviewSectionIdForCheckpoint,
|
||||
} from "./reviewModel";
|
||||
import {
|
||||
setReviewAsyncError,
|
||||
setReviewGitDiffsLoading,
|
||||
setReviewGitSections,
|
||||
setReviewSelectedSectionId,
|
||||
setReviewTurnDiffLoading,
|
||||
setReviewTurnDiff,
|
||||
type ReviewCacheForThread,
|
||||
} from "./reviewState";
|
||||
@@ -26,9 +29,7 @@ export function useReviewSections(input: {
|
||||
const { environmentId, reviewCache, threadId } = input;
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const [loadingTurnIds, setLoadingTurnIds] = useState<Record<string, boolean>>({});
|
||||
const [loadingGitDiffs, setLoadingGitDiffs] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, loadingGitDiffs, loadingTurnIds } = reviewCache.asyncState;
|
||||
const turnDiffByIdRef = useRef(reviewCache.turnDiffById);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -84,21 +85,32 @@ export function useReviewSections(input: {
|
||||
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
setError("Remote connection is not ready.");
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewAsyncError(reviewCache.threadKey, "Remote connection is not ready.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingGitDiffs(true);
|
||||
setError(null);
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewGitDiffsLoading(reviewCache.threadKey, true);
|
||||
setReviewAsyncError(reviewCache.threadKey, null);
|
||||
}
|
||||
try {
|
||||
const result = await client.review.getDiffPreview({ cwd: selectedThreadCwd });
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewGitSections(reviewCache.threadKey, result.sources);
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Failed to load review diffs.");
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewAsyncError(
|
||||
reviewCache.threadKey,
|
||||
cause instanceof Error ? cause.message : "Failed to load review diffs.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setLoadingGitDiffs(false);
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewGitDiffsLoading(reviewCache.threadKey, false);
|
||||
}
|
||||
}
|
||||
}, [environmentId, reviewCache.threadKey, selectedThreadCwd]);
|
||||
|
||||
@@ -119,12 +131,16 @@ export function useReviewSections(input: {
|
||||
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
setError("Remote connection is not ready.");
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewAsyncError(reviewCache.threadKey, "Remote connection is not ready.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingTurnIds((current) => ({ ...current, [sectionId]: true }));
|
||||
setError(null);
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewTurnDiffLoading(reviewCache.threadKey, sectionId, true);
|
||||
setReviewAsyncError(reviewCache.threadKey, null);
|
||||
}
|
||||
try {
|
||||
const result = await client.orchestration.getTurnDiff({
|
||||
threadId,
|
||||
@@ -135,13 +151,16 @@ export function useReviewSections(input: {
|
||||
setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff);
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Failed to load turn diff.");
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewAsyncError(
|
||||
reviewCache.threadKey,
|
||||
cause instanceof Error ? cause.message : "Failed to load turn diff.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setLoadingTurnIds((current) => {
|
||||
const next = { ...current };
|
||||
delete next[sectionId];
|
||||
return next;
|
||||
});
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewTurnDiffLoading(reviewCache.threadKey, sectionId, false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[environmentId, reviewCache.threadKey, threadId],
|
||||
|
||||
@@ -42,7 +42,7 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { CLAUDE_AGENT_EFFORT_OPTIONS, type ClaudeAgentEffort } from "./claudeEffortOptions";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
|
||||
@@ -209,12 +209,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
|
||||
// ── Trigger detection ────────────────────────────────────
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const [composerTrigger, setComposerTrigger] = useState<ComposerTrigger | null>(null);
|
||||
const [pathSearchResults, setPathSearchResults] = useState<
|
||||
ReadonlyArray<{ path: string; kind: "file" | "directory" }>
|
||||
>([]);
|
||||
const [pathSearchLoading, setPathSearchLoading] = useState(false);
|
||||
const pathSearchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const handleSelectionChange = useCallback(
|
||||
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
|
||||
@@ -224,60 +218,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const trigger = detectComposerTrigger(props.draftMessage, cursorPosition);
|
||||
setComposerTrigger(trigger);
|
||||
}, [props.draftMessage, cursorPosition]);
|
||||
|
||||
// ── File search (debounced) ──────────────────────────────
|
||||
useEffect(() => {
|
||||
if (pathSearchTimerRef.current) {
|
||||
clearTimeout(pathSearchTimerRef.current);
|
||||
pathSearchTimerRef.current = null;
|
||||
}
|
||||
|
||||
if (composerTrigger?.kind !== "path" || !composerTrigger.query || !props.projectCwd) {
|
||||
setPathSearchResults([]);
|
||||
setPathSearchLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setPathSearchLoading(true);
|
||||
const query = composerTrigger.query;
|
||||
const cwd = props.projectCwd;
|
||||
const envId = props.environmentId;
|
||||
|
||||
pathSearchTimerRef.current = setTimeout(() => {
|
||||
const client = getEnvironmentClient(envId);
|
||||
if (!client) {
|
||||
setPathSearchLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
void client.projects
|
||||
.searchEntries({ cwd, query, limit: 20 })
|
||||
.then((result) => {
|
||||
setPathSearchResults(
|
||||
result.entries.map((entry) => ({
|
||||
path: entry.path,
|
||||
kind: entry.kind === "directory" ? ("directory" as const) : ("file" as const),
|
||||
})),
|
||||
);
|
||||
})
|
||||
.catch(() => {
|
||||
setPathSearchResults([]);
|
||||
})
|
||||
.finally(() => {
|
||||
setPathSearchLoading(false);
|
||||
});
|
||||
}, 200);
|
||||
|
||||
return () => {
|
||||
if (pathSearchTimerRef.current) {
|
||||
clearTimeout(pathSearchTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [composerTrigger?.kind, composerTrigger?.query, props.projectCwd, props.environmentId]);
|
||||
const composerTrigger = useMemo<ComposerTrigger | null>(
|
||||
() => detectComposerTrigger(props.draftMessage, cursorPosition),
|
||||
[cursorPosition, props.draftMessage],
|
||||
);
|
||||
const pathSearch = useComposerPathSearch({
|
||||
environmentId: props.environmentId,
|
||||
cwd: composerTrigger?.kind === "path" ? props.projectCwd : null,
|
||||
query: composerTrigger?.kind === "path" ? composerTrigger.query : null,
|
||||
});
|
||||
|
||||
// ── Build menu items ─────────────────────────────────────
|
||||
const selectedProviderStatus = useMemo(() => {
|
||||
@@ -416,7 +365,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}
|
||||
|
||||
if (composerTrigger.kind === "path") {
|
||||
return pathSearchResults.map((entry) => {
|
||||
return pathSearch.entries.map((entry) => {
|
||||
const parts = entry.path.split("/");
|
||||
return {
|
||||
id: `path:${entry.path}`,
|
||||
@@ -430,7 +379,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}
|
||||
|
||||
return [];
|
||||
}, [composerTrigger, selectedProviderStatus, pathSearchResults]);
|
||||
}, [composerTrigger, pathSearch.entries, selectedProviderStatus]);
|
||||
|
||||
// ── Handle command selection ──────────────────────────────
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
@@ -680,7 +629,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
<ComposerCommandPopover
|
||||
items={composerMenuItems}
|
||||
triggerKind={composerTrigger.kind}
|
||||
isLoading={pathSearchLoading}
|
||||
isLoading={pathSearch.isPending}
|
||||
onSelect={handleCommandSelect}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
@@ -52,10 +52,6 @@ export function GitBranchesSheet() {
|
||||
.map((branch) => branch.name),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void gitActions.refreshSelectedThreadBranches();
|
||||
}, [gitActions]);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import {
|
||||
type SourceControlDiscoveryClient,
|
||||
type SourceControlDiscoveryTarget,
|
||||
createSourceControlDiscoveryManager,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId, SourceControlDiscoveryResult } from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
|
||||
export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager<EnvironmentId>({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
getClient: (environmentId) => getEnvironmentClient(environmentId)?.server ?? null,
|
||||
});
|
||||
|
||||
export function sourceControlDiscoveryTargetForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
): SourceControlDiscoveryTarget<EnvironmentId> {
|
||||
return { key: environmentId ?? null };
|
||||
}
|
||||
|
||||
export function refreshSourceControlDiscoveryForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
client?: SourceControlDiscoveryClient | null,
|
||||
): Promise<SourceControlDiscoveryResult | null> {
|
||||
return sourceControlDiscoveryManager.refresh(
|
||||
sourceControlDiscoveryTargetForEnvironment(environmentId),
|
||||
client ?? undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function invalidateSourceControlDiscoveryForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
): void {
|
||||
sourceControlDiscoveryManager.invalidate(
|
||||
sourceControlDiscoveryTargetForEnvironment(environmentId),
|
||||
);
|
||||
}
|
||||
|
||||
export function resetSourceControlDiscoveryState(): void {
|
||||
sourceControlDiscoveryManager.reset();
|
||||
}
|
||||
|
||||
export function resetSourceControlDiscoveryStateForTests(): void {
|
||||
resetSourceControlDiscoveryState();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type ComposerPathSearchState,
|
||||
type ComposerPathSearchTarget,
|
||||
EMPTY_COMPOSER_PATH_SEARCH_ATOM,
|
||||
EMPTY_COMPOSER_PATH_SEARCH_STATE,
|
||||
composerPathSearchStateAtom,
|
||||
createComposerPathSearchManager,
|
||||
getComposerPathSearchTargetKey,
|
||||
normalizeComposerPathSearchQuery,
|
||||
} from "@t3tools/client-runtime";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
subscribeEnvironmentConnections,
|
||||
} from "./environment-session-registry";
|
||||
|
||||
const composerPathSearchManager = createComposerPathSearchManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
getClient: (environmentId) => getEnvironmentClient(environmentId)?.projects ?? null,
|
||||
subscribeClientChanges: subscribeEnvironmentConnections,
|
||||
});
|
||||
|
||||
export function useComposerPathSearch(target: ComposerPathSearchTarget): ComposerPathSearchState {
|
||||
const stableTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: target.environmentId,
|
||||
cwd: target.cwd,
|
||||
query: normalizeComposerPathSearchQuery(target.query),
|
||||
}),
|
||||
[target.cwd, target.environmentId, target.query],
|
||||
);
|
||||
const targetKey = getComposerPathSearchTargetKey(stableTarget);
|
||||
|
||||
useEffect(() => composerPathSearchManager.watch(stableTarget), [stableTarget]);
|
||||
|
||||
const state = useAtomValue(
|
||||
targetKey !== null ? composerPathSearchStateAtom(targetKey) : EMPTY_COMPOSER_PATH_SEARCH_ATOM,
|
||||
);
|
||||
return targetKey === null ? EMPTY_COMPOSER_PATH_SEARCH_STATE : state;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import {
|
||||
type GitBranchState,
|
||||
type GitBranchTarget,
|
||||
@@ -10,7 +11,10 @@ import {
|
||||
} from "@t3tools/client-runtime";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
subscribeEnvironmentConnections,
|
||||
} from "./environment-session-registry";
|
||||
|
||||
export const gitBranchManager = createGitBranchManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
@@ -18,10 +22,21 @@ export const gitBranchManager = createGitBranchManager({
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
return client ? client.git : null;
|
||||
},
|
||||
subscribeClientChanges: subscribeEnvironmentConnections,
|
||||
watchLimit: 100,
|
||||
});
|
||||
|
||||
export function useGitBranches(target: GitBranchTarget): GitBranchState {
|
||||
const targetKey = getGitBranchTargetKey(target);
|
||||
const stableTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: target.environmentId,
|
||||
cwd: target.cwd,
|
||||
query: target.query ?? null,
|
||||
}),
|
||||
[target.cwd, target.environmentId, target.query],
|
||||
);
|
||||
const targetKey = getGitBranchTargetKey(stableTarget);
|
||||
useEffect(() => gitBranchManager.watch(stableTarget), [stableTarget]);
|
||||
const state = useAtomValue(
|
||||
targetKey !== null ? gitBranchStateAtom(targetKey) : EMPTY_GIT_BRANCH_ATOM,
|
||||
);
|
||||
|
||||
@@ -31,7 +31,7 @@ import { type ConnectedEnvironmentSummary } from "./remote-runtime-types";
|
||||
import {
|
||||
invalidateSourceControlDiscoveryForEnvironment,
|
||||
resetSourceControlDiscoveryState,
|
||||
} from "./source-control-discovery-manager";
|
||||
} from "./use-source-control-discovery";
|
||||
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
|
||||
import { shellSnapshotManager } from "./use-shell-snapshot";
|
||||
import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session";
|
||||
|
||||
@@ -2,44 +2,72 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM,
|
||||
EMPTY_SOURCE_CONTROL_DISCOVERY_STATE,
|
||||
type SourceControlDiscoveryClient,
|
||||
type SourceControlDiscoveryState,
|
||||
type SourceControlDiscoveryTarget,
|
||||
createSourceControlDiscoveryManager,
|
||||
getSourceControlDiscoveryTargetKey,
|
||||
sourceControlDiscoveryStateAtom,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useEffect } from "react";
|
||||
import type { EnvironmentId, SourceControlDiscoveryResult } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
subscribeEnvironmentConnections,
|
||||
} from "./environment-session-registry";
|
||||
import {
|
||||
refreshSourceControlDiscoveryForEnvironment,
|
||||
sourceControlDiscoveryTargetForEnvironment,
|
||||
} from "./source-control-discovery-manager";
|
||||
|
||||
const sourceControlDiscoveryManager = createSourceControlDiscoveryManager<EnvironmentId>({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
getClient: (environmentId) => getEnvironmentClient(environmentId)?.server ?? null,
|
||||
subscribeClientChanges: subscribeEnvironmentConnections,
|
||||
});
|
||||
|
||||
function sourceControlDiscoveryTargetForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
): SourceControlDiscoveryTarget<EnvironmentId> {
|
||||
return { key: environmentId ?? null };
|
||||
}
|
||||
|
||||
export function refreshSourceControlDiscoveryForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
client?: SourceControlDiscoveryClient | null,
|
||||
): Promise<SourceControlDiscoveryResult | null> {
|
||||
return sourceControlDiscoveryManager.refresh(
|
||||
sourceControlDiscoveryTargetForEnvironment(environmentId),
|
||||
client ?? undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function invalidateSourceControlDiscoveryForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
): void {
|
||||
sourceControlDiscoveryManager.invalidate(
|
||||
sourceControlDiscoveryTargetForEnvironment(environmentId),
|
||||
);
|
||||
}
|
||||
|
||||
export function resetSourceControlDiscoveryState(): void {
|
||||
sourceControlDiscoveryManager.reset();
|
||||
}
|
||||
|
||||
export function resetSourceControlDiscoveryStateForTests(): void {
|
||||
resetSourceControlDiscoveryState();
|
||||
}
|
||||
|
||||
export function useSourceControlDiscovery(
|
||||
environmentId: EnvironmentId | null,
|
||||
): SourceControlDiscoveryState {
|
||||
const target = useMemo(
|
||||
() => sourceControlDiscoveryTargetForEnvironment(environmentId),
|
||||
[environmentId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!environmentId) {
|
||||
return;
|
||||
}
|
||||
return sourceControlDiscoveryManager.watch(target);
|
||||
}, [target]);
|
||||
|
||||
const refresh = () => {
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
void refreshSourceControlDiscoveryForEnvironment(environmentId, client.server);
|
||||
};
|
||||
|
||||
refresh();
|
||||
return subscribeEnvironmentConnections(refresh);
|
||||
}, [environmentId]);
|
||||
|
||||
const target = sourceControlDiscoveryTargetForEnvironment(environmentId);
|
||||
const targetKey = getSourceControlDiscoveryTargetKey(target);
|
||||
const state = useAtomValue(
|
||||
targetKey !== null
|
||||
|
||||
@@ -39,7 +39,7 @@ function shouldKeepThreadDetailWarm(state: ThreadDetailState): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export const threadDetailManager = createThreadDetailManager({
|
||||
const threadDetailManager = createThreadDetailManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
getClient: (environmentId) => {
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
|
||||
@@ -2,7 +2,6 @@ import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
ProjectEntry,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
ResolvedKeybindingsConfig,
|
||||
@@ -29,9 +28,6 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import {
|
||||
clampCollapsedComposerCursor,
|
||||
type ComposerTrigger,
|
||||
@@ -55,6 +51,7 @@ import {
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
} from "../../lib/terminalContext";
|
||||
import { useComposerPathSearch } from "../../lib/composerPathSearchState";
|
||||
import {
|
||||
shouldUseCompactComposerPrimaryActions,
|
||||
shouldUseCompactComposerFooter,
|
||||
@@ -136,8 +133,6 @@ const runtimeModeConfig: Record<
|
||||
};
|
||||
|
||||
const runtimeModeOptions = Object.keys(runtimeModeConfig) as RuntimeMode[];
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const COMPOSER_FLOATING_LAYER_SELECTOR = [
|
||||
'[data-slot="popover-popup"]',
|
||||
'[data-slot="menu-popup"]',
|
||||
@@ -833,27 +828,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const composerTriggerKind = composerTrigger?.kind ?? null;
|
||||
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
|
||||
const isPathTrigger = composerTriggerKind === "path";
|
||||
const [debouncedPathQuery, composerPathQueryDebouncer] = useDebouncedValue(
|
||||
pathTriggerQuery,
|
||||
{ wait: COMPOSER_PATH_QUERY_DEBOUNCE_MS },
|
||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||
);
|
||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||
const workspaceEntriesQuery = useQuery(
|
||||
projectSearchEntriesQueryOptions({
|
||||
environmentId,
|
||||
cwd: gitCwd,
|
||||
query: effectivePathQuery,
|
||||
enabled: isPathTrigger,
|
||||
limit: 80,
|
||||
}),
|
||||
);
|
||||
const workspaceEntries = workspaceEntriesQuery.data?.entries ?? EMPTY_PROJECT_ENTRIES;
|
||||
const workspaceEntries = useComposerPathSearch({
|
||||
environmentId,
|
||||
cwd: isPathTrigger ? gitCwd : null,
|
||||
query: isPathTrigger ? pathTriggerQuery : null,
|
||||
});
|
||||
|
||||
const composerMenuItems = useMemo<ComposerCommandItem[]>(() => {
|
||||
if (!composerTrigger) return [];
|
||||
if (composerTrigger.kind === "path") {
|
||||
return workspaceEntries.map((entry) => ({
|
||||
return workspaceEntries.entries.map((entry) => ({
|
||||
id: `path:${entry.kind}:${entry.path}`,
|
||||
type: "path",
|
||||
path: entry.path,
|
||||
@@ -919,7 +903,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries]);
|
||||
}, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries.entries]);
|
||||
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const composerMenuSearchKey = composerTrigger
|
||||
@@ -984,10 +968,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
]);
|
||||
|
||||
const isComposerMenuLoading =
|
||||
composerTriggerKind === "path" &&
|
||||
((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) ||
|
||||
workspaceEntriesQuery.isLoading ||
|
||||
workspaceEntriesQuery.isFetching);
|
||||
composerTriggerKind === "path" && pathTriggerQuery.length > 0 && workspaceEntries.isPending;
|
||||
const composerMenuEmptyState = useMemo(() => {
|
||||
if (composerTriggerKind === "skill") {
|
||||
return "No skills found. Try / to browse provider commands.";
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type ComposerPathSearchState,
|
||||
type ComposerPathSearchTarget,
|
||||
EMPTY_COMPOSER_PATH_SEARCH_ATOM,
|
||||
EMPTY_COMPOSER_PATH_SEARCH_STATE,
|
||||
composerPathSearchStateAtom,
|
||||
createComposerPathSearchManager,
|
||||
getComposerPathSearchTargetKey,
|
||||
normalizeComposerPathSearchQuery,
|
||||
} from "@t3tools/client-runtime";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
readEnvironmentConnection,
|
||||
subscribeEnvironmentConnections,
|
||||
} from "../environments/runtime";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
|
||||
const COMPOSER_PATH_SEARCH_LIMIT = 80;
|
||||
const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 120;
|
||||
|
||||
const composerPathSearchManager = createComposerPathSearchManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
getClient: (environmentId) => readEnvironmentConnection(environmentId)?.client.projects ?? null,
|
||||
subscribeClientChanges: subscribeEnvironmentConnections,
|
||||
limit: COMPOSER_PATH_SEARCH_LIMIT,
|
||||
debounceMs: COMPOSER_PATH_SEARCH_DEBOUNCE_MS,
|
||||
});
|
||||
|
||||
export function useComposerPathSearch(target: ComposerPathSearchTarget): ComposerPathSearchState {
|
||||
const stableTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: target.environmentId,
|
||||
cwd: target.cwd,
|
||||
query: normalizeComposerPathSearchQuery(target.query),
|
||||
}),
|
||||
[target.cwd, target.environmentId, target.query],
|
||||
);
|
||||
const targetKey = getComposerPathSearchTargetKey(stableTarget);
|
||||
|
||||
useEffect(() => composerPathSearchManager.watch(stableTarget), [stableTarget]);
|
||||
|
||||
const state = useAtomValue(
|
||||
targetKey !== null ? composerPathSearchStateAtom(targetKey) : EMPTY_COMPOSER_PATH_SEARCH_ATOM,
|
||||
);
|
||||
return targetKey === null ? EMPTY_COMPOSER_PATH_SEARCH_STATE : state;
|
||||
}
|
||||
@@ -35,7 +35,7 @@ function sourceControlDiscoveryTarget(
|
||||
: { key: environmentId };
|
||||
}
|
||||
|
||||
export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({
|
||||
const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
getClient: (key) => {
|
||||
if (key === SOURCE_CONTROL_DISCOVERY_TARGET.key) {
|
||||
|
||||
@@ -339,7 +339,10 @@
|
||||
"node-pty",
|
||||
],
|
||||
"patchedDependencies": {
|
||||
"[email protected]": "patches/[email protected]",
|
||||
"[email protected]": "patches/[email protected]",
|
||||
"[email protected]": "patches/[email protected]",
|
||||
"@pierre/[email protected]": "patches/@pierre%[email protected]",
|
||||
},
|
||||
"overrides": {
|
||||
"@effect/atom-react": "catalog:",
|
||||
|
||||
+4
-1
@@ -92,7 +92,10 @@
|
||||
]
|
||||
},
|
||||
"patchedDependencies": {
|
||||
"[email protected]": "patches/[email protected]"
|
||||
"[email protected]": "patches/[email protected]",
|
||||
"[email protected]": "patches/[email protected]",
|
||||
"[email protected]": "patches/[email protected]",
|
||||
"@pierre/[email protected]": "patches/@pierre%[email protected]"
|
||||
},
|
||||
"trustedDependencies": [
|
||||
"node-pty",
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { assert, beforeEach, it } from "vitest";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
type ComposerPathSearchClient,
|
||||
createComposerPathSearchManager,
|
||||
EMPTY_COMPOSER_PATH_SEARCH_STATE,
|
||||
getComposerPathSearchTargetKey,
|
||||
} from "./composerPathSearchState.ts";
|
||||
|
||||
let registry = AtomRegistry.make();
|
||||
|
||||
const noop = () => undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
registry.dispose();
|
||||
registry = AtomRegistry.make();
|
||||
});
|
||||
|
||||
function flushAsyncWork(): Promise<void> {
|
||||
return Promise.resolve().then(() => undefined);
|
||||
}
|
||||
|
||||
const TARGET = {
|
||||
environmentId: "env-local" as EnvironmentId,
|
||||
cwd: "/repo",
|
||||
query: "src",
|
||||
};
|
||||
|
||||
it("derives null keys for inactive path searches", () => {
|
||||
assert.strictEqual(getComposerPathSearchTargetKey({ ...TARGET, query: "" }), null);
|
||||
assert.strictEqual(getComposerPathSearchTargetKey({ ...TARGET, cwd: null }), null);
|
||||
assert.strictEqual(getComposerPathSearchTargetKey({ ...TARGET, environmentId: null }), null);
|
||||
});
|
||||
|
||||
it("stores path search results in atom state", async () => {
|
||||
const manager = createComposerPathSearchManager({
|
||||
getRegistry: () => registry,
|
||||
debounceMs: 0,
|
||||
getClient: () => ({
|
||||
searchEntries: async () => ({
|
||||
entries: [
|
||||
{ path: "src/index.ts", kind: "file" },
|
||||
{ path: "src/components", kind: "directory" },
|
||||
],
|
||||
truncated: false,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
manager.search(TARGET);
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.deepStrictEqual(manager.getSnapshot(TARGET), {
|
||||
entries: [
|
||||
{ path: "src/index.ts", kind: "file" },
|
||||
{ path: "src/components", kind: "directory" },
|
||||
],
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores stale path search results after a newer request starts", async () => {
|
||||
let resolveFirst: (value: {
|
||||
entries: ReadonlyArray<{ path: string; kind: "file" | "directory" }>;
|
||||
truncated: boolean;
|
||||
}) => void = noop;
|
||||
const manager = createComposerPathSearchManager({
|
||||
getRegistry: () => registry,
|
||||
debounceMs: 0,
|
||||
getClient: () => ({
|
||||
searchEntries: (input: Parameters<ComposerPathSearchClient["searchEntries"]>[0]) => {
|
||||
if (input.query === "first") {
|
||||
return new Promise((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
entries: [{ path: "second.ts", kind: "file" }],
|
||||
truncated: false,
|
||||
});
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
manager.search({ ...TARGET, query: "first" });
|
||||
manager.search({ ...TARGET, query: "second" });
|
||||
await flushAsyncWork();
|
||||
resolveFirst({ entries: [{ path: "first.ts", kind: "file" }], truncated: false });
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.deepStrictEqual(manager.getSnapshot({ ...TARGET, query: "second" }), {
|
||||
entries: [{ path: "second.ts", kind: "file" }],
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the empty snapshot for inactive targets", () => {
|
||||
const manager = createComposerPathSearchManager({
|
||||
getRegistry: () => registry,
|
||||
getClient: () => null,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
manager.getSnapshot({ environmentId: null, cwd: null, query: null }),
|
||||
EMPTY_COMPOSER_PATH_SEARCH_STATE,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
import type { EnvironmentId, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
export interface ComposerPathSearchEntry {
|
||||
readonly path: string;
|
||||
readonly kind: "file" | "directory";
|
||||
readonly parentPath?: string;
|
||||
}
|
||||
|
||||
export interface ComposerPathSearchState {
|
||||
readonly entries: ReadonlyArray<ComposerPathSearchEntry>;
|
||||
readonly isPending: boolean;
|
||||
readonly error: string | null;
|
||||
}
|
||||
|
||||
export interface ComposerPathSearchTarget {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
readonly query: string | null;
|
||||
}
|
||||
|
||||
export interface ComposerPathSearchClient {
|
||||
readonly searchEntries: (input: {
|
||||
readonly cwd: string;
|
||||
readonly query: string;
|
||||
readonly limit: number;
|
||||
}) => Promise<ProjectSearchEntriesResult>;
|
||||
}
|
||||
|
||||
interface WatchedEntry {
|
||||
refCount: number;
|
||||
teardown: () => void;
|
||||
}
|
||||
|
||||
export const EMPTY_COMPOSER_PATH_SEARCH_STATE = Object.freeze<ComposerPathSearchState>({
|
||||
entries: [],
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const PENDING_COMPOSER_PATH_SEARCH_STATE = Object.freeze<ComposerPathSearchState>({
|
||||
entries: [],
|
||||
isPending: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const NOOP: () => void = () => undefined;
|
||||
const DEFAULT_DEBOUNCE_MS = 200;
|
||||
const DEFAULT_LIMIT = 20;
|
||||
|
||||
export const composerPathSearchStateAtom = Atom.family((key: string) =>
|
||||
Atom.make(EMPTY_COMPOSER_PATH_SEARCH_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`composer-path-search:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
export const EMPTY_COMPOSER_PATH_SEARCH_ATOM = Atom.make(EMPTY_COMPOSER_PATH_SEARCH_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("composer-path-search:null"),
|
||||
);
|
||||
|
||||
export function normalizeComposerPathSearchQuery(query: string | null): string {
|
||||
return query?.trim() ?? "";
|
||||
}
|
||||
|
||||
export function getComposerPathSearchTargetKey(target: ComposerPathSearchTarget): string | null {
|
||||
const query = normalizeComposerPathSearchQuery(target.query);
|
||||
if (target.environmentId === null || target.cwd === null || query.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `${target.environmentId}:${target.cwd}:${query}`;
|
||||
}
|
||||
|
||||
function toSearchEntries(
|
||||
entries: ProjectSearchEntriesResult["entries"],
|
||||
): ReadonlyArray<ComposerPathSearchEntry> {
|
||||
return entries.map((entry) => ({
|
||||
path: entry.path,
|
||||
kind: entry.kind === "directory" ? "directory" : "file",
|
||||
...(entry.parentPath !== undefined ? { parentPath: entry.parentPath } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function createComposerPathSearchManager(config: {
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
readonly getClient: (environmentId: EnvironmentId) => ComposerPathSearchClient | null;
|
||||
readonly subscribeClientChanges?: (listener: () => void) => () => void;
|
||||
readonly debounceMs?: number;
|
||||
readonly limit?: number;
|
||||
}) {
|
||||
const watched = new Map<string, WatchedEntry>();
|
||||
const versions = new Map<string, number>();
|
||||
const timers = new Map<string, Fiber.Fiber<void, never>>();
|
||||
const debounceMs = config.debounceMs ?? DEFAULT_DEBOUNCE_MS;
|
||||
const limit = config.limit ?? DEFAULT_LIMIT;
|
||||
|
||||
function bumpVersion(targetKey: string): number {
|
||||
const next = (versions.get(targetKey) ?? 0) + 1;
|
||||
versions.set(targetKey, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function setState(targetKey: string, state: ComposerPathSearchState): void {
|
||||
config.getRegistry().set(composerPathSearchStateAtom(targetKey), state);
|
||||
}
|
||||
|
||||
function clearTimer(targetKey: string): void {
|
||||
const fiber = timers.get(targetKey);
|
||||
if (fiber) {
|
||||
Effect.runFork(Fiber.interrupt(fiber));
|
||||
timers.delete(targetKey);
|
||||
}
|
||||
}
|
||||
|
||||
function getSnapshot(target: ComposerPathSearchTarget): ComposerPathSearchState {
|
||||
const targetKey = getComposerPathSearchTargetKey(target);
|
||||
return targetKey === null
|
||||
? EMPTY_COMPOSER_PATH_SEARCH_STATE
|
||||
: config.getRegistry().get(composerPathSearchStateAtom(targetKey));
|
||||
}
|
||||
|
||||
function runSearch(
|
||||
targetKey: string,
|
||||
target: ComposerPathSearchTarget & {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly cwd: string;
|
||||
},
|
||||
client: ComposerPathSearchClient,
|
||||
version: number,
|
||||
): void {
|
||||
void client
|
||||
.searchEntries({
|
||||
cwd: target.cwd,
|
||||
query: normalizeComposerPathSearchQuery(target.query),
|
||||
limit,
|
||||
})
|
||||
.then((result) => {
|
||||
if (versions.get(targetKey) !== version) {
|
||||
return;
|
||||
}
|
||||
setState(targetKey, {
|
||||
entries: toSearchEntries(result.entries),
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (versions.get(targetKey) !== version) {
|
||||
return;
|
||||
}
|
||||
setState(targetKey, {
|
||||
entries: [],
|
||||
isPending: false,
|
||||
error: error instanceof Error ? error.message : "Failed to search project files.",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function search(target: ComposerPathSearchTarget, client?: ComposerPathSearchClient): void {
|
||||
const targetKey = getComposerPathSearchTargetKey(target);
|
||||
if (targetKey === null || target.environmentId === null || target.cwd === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resolved = client ?? config.getClient(target.environmentId);
|
||||
if (!resolved) {
|
||||
setState(targetKey, {
|
||||
entries: [],
|
||||
isPending: false,
|
||||
error: "Remote connection is not ready.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const version = bumpVersion(targetKey);
|
||||
clearTimer(targetKey);
|
||||
setState(targetKey, PENDING_COMPOSER_PATH_SEARCH_STATE);
|
||||
|
||||
const readyTarget = {
|
||||
...target,
|
||||
environmentId: target.environmentId,
|
||||
cwd: target.cwd,
|
||||
};
|
||||
|
||||
if (debounceMs <= 0) {
|
||||
runSearch(targetKey, readyTarget, resolved, version);
|
||||
return;
|
||||
}
|
||||
|
||||
const fiber = Effect.runFork(
|
||||
Effect.sleep(Duration.millis(debounceMs)).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
timers.delete(targetKey);
|
||||
runSearch(targetKey, readyTarget, resolved, version);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
timers.set(targetKey, fiber);
|
||||
}
|
||||
|
||||
function watch(target: ComposerPathSearchTarget): () => void {
|
||||
const targetKey = getComposerPathSearchTargetKey(target);
|
||||
if (targetKey === null || target.environmentId === null || target.cwd === null) {
|
||||
return NOOP;
|
||||
}
|
||||
|
||||
const existing = watched.get(targetKey);
|
||||
if (existing) {
|
||||
existing.refCount += 1;
|
||||
return () => unwatch(targetKey);
|
||||
}
|
||||
|
||||
let currentClient: ComposerPathSearchClient | null = null;
|
||||
const sync = () => {
|
||||
const client = config.getClient(target.environmentId!);
|
||||
if (!client) {
|
||||
currentClient = null;
|
||||
setState(targetKey, {
|
||||
entries: [],
|
||||
isPending: false,
|
||||
error: "Remote connection is not ready.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentClient === client) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentClient = client;
|
||||
search(target, client);
|
||||
};
|
||||
|
||||
const unsubscribe = config.subscribeClientChanges?.(sync) ?? NOOP;
|
||||
sync();
|
||||
|
||||
watched.set(targetKey, {
|
||||
refCount: 1,
|
||||
teardown: () => {
|
||||
unsubscribe();
|
||||
clearTimer(targetKey);
|
||||
bumpVersion(targetKey);
|
||||
},
|
||||
});
|
||||
|
||||
return () => unwatch(targetKey);
|
||||
}
|
||||
|
||||
function unwatch(targetKey: string): void {
|
||||
const entry = watched.get(targetKey);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
entry.refCount -= 1;
|
||||
if (entry.refCount > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
entry.teardown();
|
||||
watched.delete(targetKey);
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
for (const entry of watched.values()) {
|
||||
entry.teardown();
|
||||
}
|
||||
watched.clear();
|
||||
versions.clear();
|
||||
for (const targetKey of timers.keys()) {
|
||||
clearTimer(targetKey);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
search,
|
||||
watch,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
@@ -16,6 +16,8 @@ function resetAtomRegistry() {
|
||||
atomRegistry = AtomRegistry.make();
|
||||
}
|
||||
|
||||
const noop = () => undefined;
|
||||
|
||||
const TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/repo" } as const;
|
||||
|
||||
const FIRST_PAGE: GitListBranchesResult = {
|
||||
@@ -158,4 +160,35 @@ describe("createGitBranchManager", () => {
|
||||
|
||||
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_BRANCH_STATE);
|
||||
});
|
||||
|
||||
it("watches branches with a ref-counted client-change subscription", async () => {
|
||||
const mock = createMockClient();
|
||||
let listener: () => void = noop;
|
||||
const unsubscribe = vi.fn();
|
||||
const manager = createGitBranchManager({
|
||||
getRegistry: () => atomRegistry,
|
||||
getClient: () => mock.client,
|
||||
subscribeClientChanges: (nextListener) => {
|
||||
listener = nextListener;
|
||||
return unsubscribe;
|
||||
},
|
||||
watchLimit: 100,
|
||||
});
|
||||
|
||||
const firstUnwatch = manager.watch(TARGET);
|
||||
const secondUnwatch = manager.watch(TARGET);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(mock.listRefs).toHaveBeenCalledTimes(1);
|
||||
expect(mock.listRefs).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 });
|
||||
|
||||
listener();
|
||||
await Promise.resolve();
|
||||
expect(mock.listRefs).toHaveBeenCalledTimes(1);
|
||||
|
||||
firstUnwatch();
|
||||
expect(unsubscribe).not.toHaveBeenCalled();
|
||||
secondUnwatch();
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -82,10 +82,22 @@ function mergeBranches(
|
||||
export interface GitBranchManagerConfig {
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
readonly getClient: (environmentId: EnvironmentId) => GitBranchClient | null;
|
||||
readonly subscribeClientChanges?: (listener: () => void) => () => void;
|
||||
readonly watchLimit?: number;
|
||||
}
|
||||
|
||||
interface WatchedEntry {
|
||||
refCount: number;
|
||||
teardown: () => void;
|
||||
}
|
||||
|
||||
const NOOP: () => void = () => undefined;
|
||||
|
||||
export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
const inFlight = new Map<string, Promise<GitListBranchesResult | null>>();
|
||||
const watched = new Map<string, WatchedEntry>();
|
||||
const watchLoadOptions =
|
||||
config.watchLimit === undefined ? undefined : { limit: config.watchLimit };
|
||||
|
||||
function getSnapshot(target: GitBranchTarget): GitBranchState {
|
||||
const targetKey = getGitBranchTargetKey(target);
|
||||
@@ -204,6 +216,70 @@ export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
});
|
||||
}
|
||||
|
||||
function watch(target: GitBranchTarget, client?: GitBranchClient): () => void {
|
||||
const targetKey = getGitBranchTargetKey(target);
|
||||
if (targetKey === null || target.environmentId === null || target.cwd === null) {
|
||||
return NOOP;
|
||||
}
|
||||
|
||||
const existing = watched.get(targetKey);
|
||||
if (existing) {
|
||||
existing.refCount += 1;
|
||||
return () => unwatch(targetKey);
|
||||
}
|
||||
|
||||
let teardown: () => void;
|
||||
|
||||
if (client) {
|
||||
void load(target, client, watchLoadOptions);
|
||||
teardown = NOOP;
|
||||
} else if (config.subscribeClientChanges) {
|
||||
let currentClient: GitBranchClient | null = null;
|
||||
const sync = () => {
|
||||
const resolved = config.getClient(target.environmentId!);
|
||||
if (!resolved) {
|
||||
currentClient = null;
|
||||
return;
|
||||
}
|
||||
if (currentClient === resolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentClient = resolved;
|
||||
void load(target, resolved, watchLoadOptions);
|
||||
};
|
||||
|
||||
const unsubscribe = config.subscribeClientChanges(sync);
|
||||
sync();
|
||||
teardown = unsubscribe;
|
||||
} else {
|
||||
const resolved = config.getClient(target.environmentId);
|
||||
if (!resolved) {
|
||||
return NOOP;
|
||||
}
|
||||
void load(target, resolved, watchLoadOptions);
|
||||
teardown = NOOP;
|
||||
}
|
||||
|
||||
watched.set(targetKey, { refCount: 1, teardown });
|
||||
return () => unwatch(targetKey);
|
||||
}
|
||||
|
||||
function unwatch(targetKey: string): void {
|
||||
const entry = watched.get(targetKey);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
entry.refCount -= 1;
|
||||
if (entry.refCount > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
entry.teardown();
|
||||
watched.delete(targetKey);
|
||||
}
|
||||
|
||||
function invalidate(target?: GitBranchTarget): void {
|
||||
if (target) {
|
||||
const targetKey = getGitBranchTargetKey(target);
|
||||
@@ -219,11 +295,16 @@ export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
for (const entry of watched.values()) {
|
||||
entry.teardown();
|
||||
}
|
||||
watched.clear();
|
||||
invalidate();
|
||||
}
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
watch,
|
||||
load,
|
||||
loadNext,
|
||||
invalidate,
|
||||
|
||||
@@ -19,3 +19,4 @@ export * from "./wsRpcProtocol.ts";
|
||||
export * from "./wsTransport.ts";
|
||||
export * from "./wsRpcClient.ts";
|
||||
export * from "./environmentConnection.ts";
|
||||
export * from "./composerPathSearchState.ts";
|
||||
@@ -50,11 +50,17 @@ function unresolvedDiscovery() {
|
||||
|
||||
let registry = AtomRegistry.make();
|
||||
|
||||
const noop = () => undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
registry.dispose();
|
||||
registry = AtomRegistry.make();
|
||||
});
|
||||
|
||||
function flushAsyncWork(): Promise<void> {
|
||||
return Promise.resolve().then(() => undefined);
|
||||
}
|
||||
|
||||
it("stores refreshed discovery data in an atom snapshot", async () => {
|
||||
const manager = createSourceControlDiscoveryManager({
|
||||
getRegistry: () => registry,
|
||||
@@ -181,3 +187,99 @@ it("ignores an in-flight refresh after the target is invalidated", async () => {
|
||||
isPending: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("watches a discovery target with ref-counted client-change subscriptions", async () => {
|
||||
let listener: () => void = noop;
|
||||
let subscribeCalls = 0;
|
||||
let unsubscribeCalls = 0;
|
||||
let discoveryCalls = 0;
|
||||
const client = {
|
||||
discoverSourceControl: async () => {
|
||||
discoveryCalls += 1;
|
||||
return EMPTY_RESULT;
|
||||
},
|
||||
};
|
||||
const manager = createSourceControlDiscoveryManager({
|
||||
getRegistry: () => registry,
|
||||
getClient: () => client,
|
||||
subscribeClientChanges: (nextListener) => {
|
||||
subscribeCalls += 1;
|
||||
listener = nextListener;
|
||||
return () => {
|
||||
unsubscribeCalls += 1;
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const firstUnwatch = manager.watch({ key: "primary" });
|
||||
const secondUnwatch = manager.watch({ key: "primary" });
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.strictEqual(subscribeCalls, 1);
|
||||
assert.strictEqual(discoveryCalls, 1);
|
||||
assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), {
|
||||
data: EMPTY_RESULT,
|
||||
error: null,
|
||||
isPending: false,
|
||||
});
|
||||
|
||||
listener();
|
||||
await flushAsyncWork();
|
||||
assert.strictEqual(discoveryCalls, 1);
|
||||
|
||||
firstUnwatch();
|
||||
assert.strictEqual(unsubscribeCalls, 0);
|
||||
|
||||
secondUnwatch();
|
||||
assert.strictEqual(unsubscribeCalls, 1);
|
||||
});
|
||||
|
||||
it("refreshes a watched discovery target when the resolved client is replaced", async () => {
|
||||
let listener: () => void = noop;
|
||||
let activeResult = EMPTY_RESULT;
|
||||
let discoveryCalls = 0;
|
||||
const firstClient = {
|
||||
discoverSourceControl: async () => {
|
||||
discoveryCalls += 1;
|
||||
return activeResult;
|
||||
},
|
||||
};
|
||||
const secondClient = {
|
||||
discoverSourceControl: async () => {
|
||||
discoveryCalls += 1;
|
||||
return activeResult;
|
||||
},
|
||||
};
|
||||
let activeClient = firstClient;
|
||||
const manager = createSourceControlDiscoveryManager({
|
||||
getRegistry: () => registry,
|
||||
getClient: () => activeClient,
|
||||
subscribeClientChanges: (nextListener) => {
|
||||
listener = nextListener;
|
||||
return () => undefined;
|
||||
},
|
||||
});
|
||||
|
||||
const unwatch = manager.watch({ key: "primary" });
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), {
|
||||
data: EMPTY_RESULT,
|
||||
error: null,
|
||||
isPending: false,
|
||||
});
|
||||
|
||||
activeClient = secondClient;
|
||||
activeResult = GITHUB_RESULT;
|
||||
listener();
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.strictEqual(discoveryCalls, 2);
|
||||
assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), {
|
||||
data: GITHUB_RESULT,
|
||||
error: null,
|
||||
isPending: false,
|
||||
});
|
||||
|
||||
unwatch();
|
||||
});
|
||||
@@ -17,6 +17,11 @@ export interface SourceControlDiscoveryClient {
|
||||
readonly discoverSourceControl: () => Promise<SourceControlDiscoveryResult>;
|
||||
}
|
||||
|
||||
interface WatchedEntry {
|
||||
refCount: number;
|
||||
teardown: () => void;
|
||||
}
|
||||
|
||||
/* --- Constants ------------------------------------------------------ */
|
||||
|
||||
export const EMPTY_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze<SourceControlDiscoveryState>({
|
||||
@@ -71,13 +76,29 @@ export interface SourceControlDiscoveryManagerConfig<TKey extends string = strin
|
||||
* clients without changing the state primitive.
|
||||
*/
|
||||
readonly getClient: (key: TKey) => SourceControlDiscoveryClient | null;
|
||||
/**
|
||||
* Optional: subscribe to environment/client availability changes.
|
||||
*
|
||||
* When provided, `watch` refreshes as clients appear or are replaced
|
||||
* instead of relying on React hooks to manually kick discovery.
|
||||
*/
|
||||
readonly subscribeClientChanges?: (listener: () => void) => () => void;
|
||||
}
|
||||
|
||||
const NOOP: () => void = () => undefined;
|
||||
|
||||
export function createSourceControlDiscoveryManager<TKey extends string = string>(
|
||||
config: SourceControlDiscoveryManagerConfig<TKey>,
|
||||
) {
|
||||
const refreshInFlight = new Map<string, Promise<SourceControlDiscoveryResult | null>>();
|
||||
const refreshInFlight = new Map<
|
||||
string,
|
||||
{
|
||||
readonly client: SourceControlDiscoveryClient;
|
||||
readonly promise: Promise<SourceControlDiscoveryResult | null>;
|
||||
}
|
||||
>();
|
||||
const refreshVersions = new Map<string, number>();
|
||||
const watched = new Map<string, WatchedEntry>();
|
||||
|
||||
function getRefreshVersion(targetKey: string): number {
|
||||
return refreshVersions.get(targetKey) ?? 0;
|
||||
@@ -154,11 +175,6 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
const existing = refreshInFlight.get(targetKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const resolvedClient = client ?? config.getClient(targetKey);
|
||||
if (!resolvedClient) {
|
||||
const error = new Error("Source control discovery client is unavailable.");
|
||||
@@ -166,6 +182,15 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
|
||||
return Promise.resolve(getSnapshot(target).data);
|
||||
}
|
||||
|
||||
const existing = refreshInFlight.get(targetKey);
|
||||
if (existing) {
|
||||
if (!client || existing.client === resolvedClient) {
|
||||
return existing.promise;
|
||||
}
|
||||
|
||||
return existing.promise.then(() => refresh(target, resolvedClient));
|
||||
}
|
||||
|
||||
markPending(targetKey);
|
||||
const refreshVersion = getRefreshVersion(targetKey);
|
||||
const promise = resolvedClient.discoverSourceControl().then(
|
||||
@@ -184,11 +209,14 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
|
||||
);
|
||||
let tracked: Promise<SourceControlDiscoveryResult | null>;
|
||||
tracked = promise.finally(() => {
|
||||
if (refreshInFlight.get(targetKey) === tracked) {
|
||||
if (refreshInFlight.get(targetKey)?.promise === tracked) {
|
||||
refreshInFlight.delete(targetKey);
|
||||
}
|
||||
});
|
||||
refreshInFlight.set(targetKey, tracked);
|
||||
refreshInFlight.set(targetKey, {
|
||||
client: resolvedClient,
|
||||
promise: tracked,
|
||||
});
|
||||
return tracked;
|
||||
}
|
||||
|
||||
@@ -228,12 +256,93 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
|
||||
return config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep discovery warm for `target`.
|
||||
*
|
||||
* Multiple callers sharing a target key are ref-counted. With
|
||||
* `subscribeClientChanges`, the manager refreshes whenever a client first
|
||||
* appears or is replaced after reconnect.
|
||||
*/
|
||||
function watch(
|
||||
target: SourceControlDiscoveryTarget<TKey>,
|
||||
client?: SourceControlDiscoveryClient,
|
||||
): () => void {
|
||||
const targetKey = getSourceControlDiscoveryTargetKey(target);
|
||||
if (targetKey === null) {
|
||||
return NOOP;
|
||||
}
|
||||
|
||||
const existing = watched.get(targetKey);
|
||||
if (existing) {
|
||||
existing.refCount += 1;
|
||||
return () => unwatch(targetKey);
|
||||
}
|
||||
|
||||
let teardown: () => void;
|
||||
|
||||
if (client) {
|
||||
void refresh(target, client);
|
||||
teardown = NOOP;
|
||||
} else if (config.subscribeClientChanges) {
|
||||
let currentClient: SourceControlDiscoveryClient | null = null;
|
||||
|
||||
const sync = () => {
|
||||
const resolved = config.getClient(targetKey);
|
||||
if (!resolved) {
|
||||
currentClient = null;
|
||||
markPending(targetKey);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentClient === resolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentClient = resolved;
|
||||
void refresh(target, resolved);
|
||||
};
|
||||
|
||||
const unsubChanges = config.subscribeClientChanges(sync);
|
||||
sync();
|
||||
teardown = unsubChanges;
|
||||
} else {
|
||||
const resolved = config.getClient(targetKey);
|
||||
if (!resolved) {
|
||||
return NOOP;
|
||||
}
|
||||
void refresh(target, resolved);
|
||||
teardown = NOOP;
|
||||
}
|
||||
|
||||
watched.set(targetKey, { refCount: 1, teardown });
|
||||
return () => unwatch(targetKey);
|
||||
}
|
||||
|
||||
function unwatch(targetKey: string): void {
|
||||
const entry = watched.get(targetKey);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
entry.refCount -= 1;
|
||||
if (entry.refCount > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
entry.teardown();
|
||||
watched.delete(targetKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear in-flight refresh tracking and reset every known discovery atom.
|
||||
* Primarily used by tests and runtime teardown.
|
||||
*/
|
||||
function reset(): void {
|
||||
const keys = new Set([...knownSourceControlDiscoveryKeys, ...refreshInFlight.keys()]);
|
||||
for (const entry of watched.values()) {
|
||||
entry.teardown();
|
||||
}
|
||||
watched.clear();
|
||||
refreshInFlight.clear();
|
||||
for (const key of keys) {
|
||||
bumpRefreshVersion(key);
|
||||
@@ -242,6 +351,7 @@ export function createSourceControlDiscoveryManager<TKey extends string = string
|
||||
}
|
||||
|
||||
return {
|
||||
watch,
|
||||
refresh,
|
||||
getSnapshot,
|
||||
invalidate,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
diff --git a/package.json b/package.json
|
||||
index c0e762b13b56247b256520754e439cbc16bb797d..d298b87c175ec891d1b50f681c9031f4b1929e67 100644
|
||||
--- a/package.json
|
||||
+++ b/package.json
|
||||
@@ -51,6 +51,18 @@
|
||||
"./worker/worker-portable.js": {
|
||||
"types": "./dist/worker/worker-portable.d.ts",
|
||||
"import": "./dist/worker/worker-portable.js"
|
||||
+ },
|
||||
+ "./types": {
|
||||
+ "types": "./dist/types.d.ts",
|
||||
+ "import": "./dist/types.js"
|
||||
+ },
|
||||
+ "./utils/getFiletypeFromFileName": {
|
||||
+ "types": "./dist/utils/getFiletypeFromFileName.d.ts",
|
||||
+ "import": "./dist/utils/getFiletypeFromFileName.js"
|
||||
+ },
|
||||
+ "./utils/parsePatchFiles": {
|
||||
+ "types": "./dist/utils/parsePatchFiles.d.ts",
|
||||
+ "import": "./dist/utils/parsePatchFiles.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@@ -0,0 +1,15 @@
|
||||
diff --git a/ios/EXDevLauncherController.m b/ios/EXDevLauncherController.m
|
||||
index c9ca6fbfe758e6f97d6f05b0c88e382f0eebae2f..7ed12652528ab31350ecbc9cca736bcda7adf3f3 100644
|
||||
--- a/ios/EXDevLauncherController.m
|
||||
+++ b/ios/EXDevLauncherController.m
|
||||
@@ -625,7 +625,9 @@ -(void)copyToClipboard:(NSString *)content {
|
||||
- (void)setDevMenuAppBridge
|
||||
{
|
||||
DevMenuManager *manager = [DevMenuManager shared];
|
||||
- [manager updateCurrentBridge:self.appBridge];
|
||||
+ // Expo SDK 55's dev launcher still references `self.appBridge`,
|
||||
+ // but React Native 0.83 removed that property from the delegate base class.
|
||||
+ // Newer Expo builds stop updating the dev menu bridge here.
|
||||
|
||||
if (self.manifest != nil) {
|
||||
[manager updateCurrentManifest:self.manifest manifestURL:self.manifestURL];
|
||||
@@ -0,0 +1,16 @@
|
||||
diff --git a/package.json b/package.json
|
||||
index 4e4366fb9d05a6c250acfc62e79487475d8ac05b..200e4680d77cbb4f14d22eb986efde1275a0d3e8 100644
|
||||
--- a/package.json
|
||||
+++ b/package.json
|
||||
@@ -88,6 +88,11 @@
|
||||
"jsSrcsDir": "./src",
|
||||
"android": {
|
||||
"javaPackageName": "com.margelo.nitro"
|
||||
+ },
|
||||
+ "ios": {
|
||||
+ "modulesProvider": {
|
||||
+ "NitroModules": "NativeNitroModules"
|
||||
+ }
|
||||
}
|
||||
},
|
||||
"jest": {
|
||||
@@ -40,8 +40,10 @@ const sourceExtensions = new Set([".swift", ".kt", ".kts"]);
|
||||
const excludedDirectories = new Set([
|
||||
".expo",
|
||||
".git",
|
||||
"android",
|
||||
"build",
|
||||
"DerivedData",
|
||||
"ios",
|
||||
"node_modules",
|
||||
"Pods",
|
||||
"Vendor",
|
||||
@@ -188,19 +190,7 @@ const runNativeStaticChecks = Effect.fn("runNativeStaticChecks")(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const androidProject = path.join(root, "android");
|
||||
const gradlew = path.join(
|
||||
androidProject,
|
||||
process.platform === "win32" ? "gradlew.bat" : "gradlew",
|
||||
);
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
if (yield* fs.exists(gradlew)) {
|
||||
const stat = yield* fs.stat(gradlew);
|
||||
if (stat.type === "File") {
|
||||
yield* runCommand(gradlew, ["lint"], androidProject);
|
||||
}
|
||||
}
|
||||
yield* Console.log("Skipping generated native project folders: android/, ios/.");
|
||||
});
|
||||
|
||||
export const mobileNativeStaticCheckCommand = Command.make("mobile-native-static-check", {}, () =>
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const root = process.cwd();
|
||||
|
||||
const candidates = [join(root, "node_modules/expo-dev-launcher/ios/EXDevLauncherController.m")];
|
||||
|
||||
const bunStorePath = join(root, "node_modules/.bun");
|
||||
|
||||
if (existsSync(bunStorePath)) {
|
||||
for (const entry of readdirSync(bunStorePath)) {
|
||||
if (!entry.startsWith("expo-dev-launcher@")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
candidates.push(
|
||||
join(bunStorePath, entry, "node_modules/expo-dev-launcher/ios/EXDevLauncherController.m"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const targetLine = "[manager updateCurrentBridge:self.appBridge];";
|
||||
const replacement = [
|
||||
" // Expo SDK 55's dev launcher still references `self.appBridge`,",
|
||||
" // but React Native 0.83 removed that property from the delegate base class.",
|
||||
" // Newer Expo builds stop updating the dev menu bridge here.",
|
||||
].join("\n");
|
||||
|
||||
let patchedCount = 0;
|
||||
let locatedCount = 0;
|
||||
|
||||
for (const filePath of candidates) {
|
||||
if (!existsSync(filePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
locatedCount += 1;
|
||||
const source = readFileSync(filePath, "utf8");
|
||||
|
||||
if (source.includes(replacement)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!source.includes(targetLine)) {
|
||||
throw new Error(
|
||||
`Found expo-dev-launcher source at ${filePath}, but the expected bridge line was missing.`,
|
||||
);
|
||||
}
|
||||
|
||||
const nextSource = source.replace(` ${targetLine}`, replacement);
|
||||
writeFileSync(filePath, nextSource);
|
||||
patchedCount += 1;
|
||||
}
|
||||
|
||||
if (patchedCount > 0) {
|
||||
console.log(
|
||||
`[patch-expo-dev-launcher] patched ${patchedCount} expo-dev-launcher installation(s).`,
|
||||
);
|
||||
} else if (locatedCount > 0) {
|
||||
console.log("[patch-expo-dev-launcher] expo-dev-launcher already patched.");
|
||||
} else {
|
||||
console.log("[patch-expo-dev-launcher] expo-dev-launcher not installed; skipping.");
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const root = process.cwd();
|
||||
const bunStorePath = join(root, "node_modules/.bun");
|
||||
|
||||
const packageDirs = [];
|
||||
|
||||
if (existsSync(join(root, "node_modules/@pierre/diffs"))) {
|
||||
packageDirs.push(join(root, "node_modules/@pierre/diffs"));
|
||||
}
|
||||
|
||||
if (existsSync(bunStorePath)) {
|
||||
for (const entry of readdirSync(bunStorePath)) {
|
||||
if (!entry.startsWith("@pierre+diffs@")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
packageDirs.push(join(bunStorePath, entry, "node_modules/@pierre/diffs"));
|
||||
}
|
||||
}
|
||||
|
||||
const utilsIndexJs = [
|
||||
'export { parsePatchFiles, processFile, processPatch } from "./parsePatchFiles.js";',
|
||||
"export {",
|
||||
" EXTENSION_TO_FILE_FORMAT,",
|
||||
" getCustomExtensionsMap,",
|
||||
" getCustomExtensionsVersion,",
|
||||
" getFiletypeFromFileName,",
|
||||
" replaceCustomExtensions,",
|
||||
" setCustomExtension,",
|
||||
'} from "./getFiletypeFromFileName.js";',
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
const utilsIndexDts = [
|
||||
'export { parsePatchFiles, processFile, processPatch } from "./parsePatchFiles.js";',
|
||||
"export {",
|
||||
" EXTENSION_TO_FILE_FORMAT,",
|
||||
" getCustomExtensionsMap,",
|
||||
" getCustomExtensionsVersion,",
|
||||
" getFiletypeFromFileName,",
|
||||
" replaceCustomExtensions,",
|
||||
" setCustomExtension,",
|
||||
'} from "./getFiletypeFromFileName.js";',
|
||||
'export type { ChangeTypes, FileDiffMetadata, ParsedPatch, SupportedLanguages } from "../types.js";',
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
let patchedCount = 0;
|
||||
let locatedCount = 0;
|
||||
|
||||
for (const packageDir of packageDirs) {
|
||||
if (!existsSync(packageDir)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
locatedCount += 1;
|
||||
|
||||
const packageJsonPath = join(packageDir, "package.json");
|
||||
const utilsIndexJsPath = join(packageDir, "dist/utils/index.js");
|
||||
const utilsIndexDtsPath = join(packageDir, "dist/utils/index.d.ts");
|
||||
|
||||
const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
||||
const currentUtilsExport = pkg.exports?.["./utils"];
|
||||
|
||||
const expectedUtilsExport = {
|
||||
types: "./dist/utils/index.d.ts",
|
||||
import: "./dist/utils/index.js",
|
||||
};
|
||||
|
||||
const needsExportPatch =
|
||||
currentUtilsExport?.types !== expectedUtilsExport.types ||
|
||||
currentUtilsExport?.import !== expectedUtilsExport.import;
|
||||
|
||||
if (needsExportPatch) {
|
||||
pkg.exports = {
|
||||
...pkg.exports,
|
||||
"./utils": expectedUtilsExport,
|
||||
};
|
||||
writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
}
|
||||
|
||||
const currentJs = existsSync(utilsIndexJsPath) ? readFileSync(utilsIndexJsPath, "utf8") : null;
|
||||
if (currentJs !== utilsIndexJs) {
|
||||
writeFileSync(utilsIndexJsPath, utilsIndexJs);
|
||||
}
|
||||
|
||||
const currentDts = existsSync(utilsIndexDtsPath) ? readFileSync(utilsIndexDtsPath, "utf8") : null;
|
||||
if (currentDts !== utilsIndexDts) {
|
||||
writeFileSync(utilsIndexDtsPath, utilsIndexDts);
|
||||
}
|
||||
|
||||
if (needsExportPatch || currentJs !== utilsIndexJs || currentDts !== utilsIndexDts) {
|
||||
patchedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (patchedCount > 0) {
|
||||
console.log(`[patch-pierre-diffs-utils] patched ${patchedCount} @pierre/diffs installation(s).`);
|
||||
} else if (locatedCount > 0) {
|
||||
console.log("[patch-pierre-diffs-utils] @pierre/diffs already patched.");
|
||||
} else {
|
||||
console.log("[patch-pierre-diffs-utils] @pierre/diffs not installed; skipping.");
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const root = process.cwd();
|
||||
|
||||
const candidates = [join(root, "node_modules/react-native-nitro-modules/package.json")];
|
||||
|
||||
const bunStorePath = join(root, "node_modules/.bun");
|
||||
|
||||
if (existsSync(bunStorePath)) {
|
||||
for (const entry of readdirSync(bunStorePath)) {
|
||||
if (!entry.startsWith("react-native-nitro-modules@")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
candidates.push(
|
||||
join(bunStorePath, entry, "node_modules/react-native-nitro-modules/package.json"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let patchedCount = 0;
|
||||
let locatedCount = 0;
|
||||
|
||||
for (const filePath of candidates) {
|
||||
if (!existsSync(filePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
locatedCount += 1;
|
||||
|
||||
const source = readFileSync(filePath, "utf8");
|
||||
const pkg = JSON.parse(source);
|
||||
|
||||
if (pkg.codegenConfig == null || typeof pkg.codegenConfig !== "object") {
|
||||
throw new Error(
|
||||
`Found react-native-nitro-modules package at ${filePath}, but codegenConfig was missing.`,
|
||||
);
|
||||
}
|
||||
|
||||
const iosConfig =
|
||||
pkg.codegenConfig.ios != null && typeof pkg.codegenConfig.ios === "object"
|
||||
? pkg.codegenConfig.ios
|
||||
: {};
|
||||
|
||||
const modulesProvider =
|
||||
iosConfig.modulesProvider != null && typeof iosConfig.modulesProvider === "object"
|
||||
? iosConfig.modulesProvider
|
||||
: {};
|
||||
|
||||
if (modulesProvider.NitroModules === "NativeNitroModules") {
|
||||
continue;
|
||||
}
|
||||
|
||||
modulesProvider.NitroModules = "NativeNitroModules";
|
||||
iosConfig.modulesProvider = modulesProvider;
|
||||
pkg.codegenConfig.ios = iosConfig;
|
||||
|
||||
writeFileSync(filePath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
patchedCount += 1;
|
||||
}
|
||||
|
||||
if (patchedCount > 0) {
|
||||
console.log(
|
||||
`[patch-react-native-nitro-modules] patched ${patchedCount} react-native-nitro-modules installation(s).`,
|
||||
);
|
||||
} else if (locatedCount > 0) {
|
||||
console.log("[patch-react-native-nitro-modules] react-native-nitro-modules already patched.");
|
||||
} else {
|
||||
console.log(
|
||||
"[patch-react-native-nitro-modules] react-native-nitro-modules not installed; skipping.",
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user