Refactor review sheet into focused native review hooks
- Split file visibility, diff data, and comment selection logic out of `ReviewSheet` - Add tests for review file visibility and native diff bridge behavior - Wire review selection and mobile remote connect state through shared hooks
This commit is contained in:
1 parent
594df47fb7
commit
d950f45672
16 files changed
+1391
-1606
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getDefaultReviewExpandedFileIds,
|
||||
getValidExplicitReviewFileIds,
|
||||
getValidReviewFileIds,
|
||||
removeReviewFileId,
|
||||
toggleReviewFileId,
|
||||
} from "./reviewFileVisibility";
|
||||
import type { ReviewRenderableFile } from "./reviewModel";
|
||||
|
||||
function makeFile(id: string): ReviewRenderableFile {
|
||||
return {
|
||||
id,
|
||||
cacheKey: id,
|
||||
path: id,
|
||||
previousPath: null,
|
||||
changeType: "change",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
languageHint: null,
|
||||
additionLines: [],
|
||||
deletionLines: [],
|
||||
rows: [],
|
||||
};
|
||||
}
|
||||
|
||||
describe("review file visibility", () => {
|
||||
const files = [makeFile("a.ts"), makeFile("b.ts")];
|
||||
|
||||
it("defaults expanded files to every renderable file", () => {
|
||||
expect(getDefaultReviewExpandedFileIds(files)).toEqual(["a.ts", "b.ts"]);
|
||||
expect(getValidReviewFileIds(files, undefined)).toEqual(["a.ts", "b.ts"]);
|
||||
});
|
||||
|
||||
it("filters stale cached file ids", () => {
|
||||
expect(getValidReviewFileIds(files, ["missing.ts", "b.ts"])).toEqual(["b.ts"]);
|
||||
expect(getValidExplicitReviewFileIds(files, undefined)).toEqual([]);
|
||||
expect(getValidExplicitReviewFileIds(files, ["a.ts", "missing.ts"])).toEqual(["a.ts"]);
|
||||
});
|
||||
|
||||
it("toggles and removes ids without mutating the original array", () => {
|
||||
const original = ["a.ts"];
|
||||
|
||||
expect(toggleReviewFileId(original, "b.ts")).toEqual(["a.ts", "b.ts"]);
|
||||
expect(toggleReviewFileId(original, "a.ts")).toEqual([]);
|
||||
expect(removeReviewFileId(original, "a.ts")).toEqual([]);
|
||||
expect(original).toEqual(["a.ts"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { updateReviewExpandedFileIds, updateReviewViewedFileIds } from "./reviewState";
|
||||
import type { ReviewRenderableFile } from "./reviewModel";
|
||||
|
||||
export function getDefaultReviewExpandedFileIds(
|
||||
files: ReadonlyArray<ReviewRenderableFile>,
|
||||
): ReadonlyArray<string> {
|
||||
return files.map((file) => file.id);
|
||||
}
|
||||
|
||||
export function getValidReviewFileIds(
|
||||
files: ReadonlyArray<ReviewRenderableFile>,
|
||||
fileIds: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
if (fileIds === undefined) {
|
||||
return getDefaultReviewExpandedFileIds(files);
|
||||
}
|
||||
|
||||
const fileIdSet = new Set(files.map((file) => file.id));
|
||||
return fileIds.filter((id) => fileIdSet.has(id));
|
||||
}
|
||||
|
||||
export function getValidExplicitReviewFileIds(
|
||||
files: ReadonlyArray<ReviewRenderableFile>,
|
||||
fileIds: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
if (fileIds === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return getValidReviewFileIds(files, fileIds);
|
||||
}
|
||||
|
||||
export function toggleReviewFileId(
|
||||
fileIds: ReadonlyArray<string>,
|
||||
fileId: string,
|
||||
): ReadonlyArray<string> {
|
||||
return fileIds.includes(fileId) ? fileIds.filter((id) => id !== fileId) : [...fileIds, fileId];
|
||||
}
|
||||
|
||||
export function removeReviewFileId(
|
||||
fileIds: ReadonlyArray<string>,
|
||||
fileId: string,
|
||||
): ReadonlyArray<string> {
|
||||
return fileIds.includes(fileId) ? fileIds.filter((id) => id !== fileId) : fileIds;
|
||||
}
|
||||
|
||||
export function useReviewFileVisibility(input: {
|
||||
readonly threadKey: string | null;
|
||||
readonly sectionId: string | null;
|
||||
readonly files: ReadonlyArray<ReviewRenderableFile>;
|
||||
readonly cachedExpandedFileIds: ReadonlyArray<string> | undefined;
|
||||
readonly cachedViewedFileIds: ReadonlyArray<string> | undefined;
|
||||
}) {
|
||||
const { cachedExpandedFileIds, cachedViewedFileIds, files, sectionId, threadKey } = input;
|
||||
|
||||
const expandedFileIds = useMemo(
|
||||
() => getValidReviewFileIds(files, cachedExpandedFileIds),
|
||||
[cachedExpandedFileIds, files],
|
||||
);
|
||||
const viewedFileIds = useMemo(
|
||||
() => getValidExplicitReviewFileIds(files, cachedViewedFileIds),
|
||||
[cachedViewedFileIds, files],
|
||||
);
|
||||
const collapsedFileIds = useMemo(() => {
|
||||
const expandedFileIdSet = new Set(expandedFileIds);
|
||||
return files.reduce<string[]>((fileIds, file) => {
|
||||
if (!expandedFileIdSet.has(file.id)) {
|
||||
fileIds.push(file.id);
|
||||
}
|
||||
return fileIds;
|
||||
}, []);
|
||||
}, [expandedFileIds, files]);
|
||||
|
||||
const toggleExpandedFile = useCallback(
|
||||
(fileId: string) => {
|
||||
if (!threadKey || !sectionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateReviewExpandedFileIds(threadKey, sectionId, (existing) =>
|
||||
toggleReviewFileId(getValidReviewFileIds(files, existing), fileId),
|
||||
);
|
||||
},
|
||||
[files, sectionId, threadKey],
|
||||
);
|
||||
|
||||
const toggleViewedFile = useCallback(
|
||||
(fileId: string) => {
|
||||
if (!threadKey || !sectionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldCollapse = !viewedFileIds.includes(fileId);
|
||||
updateReviewViewedFileIds(threadKey, sectionId, (existing) =>
|
||||
toggleReviewFileId(getValidExplicitReviewFileIds(files, existing), fileId),
|
||||
);
|
||||
|
||||
if (shouldCollapse) {
|
||||
updateReviewExpandedFileIds(threadKey, sectionId, (existing) =>
|
||||
removeReviewFileId(getValidReviewFileIds(files, existing), fileId),
|
||||
);
|
||||
}
|
||||
},
|
||||
[files, sectionId, threadKey, viewedFileIds],
|
||||
);
|
||||
|
||||
return {
|
||||
expandedFileIds,
|
||||
viewedFileIds,
|
||||
collapsedFileIds,
|
||||
toggleExpandedFile,
|
||||
toggleViewedFile,
|
||||
};
|
||||
}
|
||||
@@ -78,6 +78,18 @@ const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>
|
||||
),
|
||||
);
|
||||
|
||||
export interface ReviewCacheForThread {
|
||||
readonly threadKey: string | null;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string>>;
|
||||
readonly selectedSectionId: string | null;
|
||||
readonly expandedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
|
||||
readonly revealedLargeFileIdsBySection: Readonly<
|
||||
Record<string, ReadonlyArray<string> | undefined>
|
||||
>;
|
||||
readonly viewedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
|
||||
}
|
||||
|
||||
function buildThreadKey(input: {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly threadId?: ThreadId;
|
||||
@@ -94,7 +106,7 @@ function buildSectionCacheKey(threadKey: string, sectionId: string): string {
|
||||
export function useReviewCacheForThread(input: {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly threadId?: ThreadId;
|
||||
}) {
|
||||
}): ReviewCacheForThread {
|
||||
const threadKey = buildThreadKey(input);
|
||||
const gitSections = useAtomValue(
|
||||
threadKey ? reviewGitSectionsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_GIT_SECTIONS_ATOM,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildNativeReviewTokensResetKey, hashReviewDiffKey } from "./useNativeReviewDiffBridge";
|
||||
|
||||
describe("native review diff bridge", () => {
|
||||
it("builds stable reset keys from the rendered diff identity", () => {
|
||||
const input = {
|
||||
threadKey: "env:thread",
|
||||
sectionId: "turn:2",
|
||||
scheme: "dark" as const,
|
||||
diff: "diff --git a/a.ts b/a.ts",
|
||||
fileCount: 1,
|
||||
rowCount: 4,
|
||||
};
|
||||
|
||||
expect(buildNativeReviewTokensResetKey(input)).toBe(buildNativeReviewTokensResetKey(input));
|
||||
expect(buildNativeReviewTokensResetKey({ ...input, rowCount: 5 })).not.toBe(
|
||||
buildNativeReviewTokensResetKey(input),
|
||||
);
|
||||
expect(buildNativeReviewTokensResetKey({ ...input, diff: null })).toContain(":empty:");
|
||||
});
|
||||
|
||||
it("includes diff length in the hash key to reduce accidental collisions", () => {
|
||||
expect(hashReviewDiffKey("abc")).toMatch(/^3:/);
|
||||
expect(hashReviewDiffKey("abcd")).toMatch(/^4:/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import type { NativeSyntheticEvent } from "react-native";
|
||||
|
||||
import { type NativeReviewDiffHighlightScheme } from "../diffs/nativeReviewDiffHighlighter";
|
||||
import {
|
||||
createNativeReviewDiffTheme,
|
||||
NATIVE_REVIEW_DIFF_STYLE,
|
||||
type NativeReviewDiffData,
|
||||
} from "./nativeReviewDiffAdapter";
|
||||
import { useNativeReviewDiffHighlighting } from "./useNativeReviewDiffHighlighting";
|
||||
|
||||
export function hashReviewDiffKey(diff: string | null | undefined): string {
|
||||
if (!diff) {
|
||||
return "empty";
|
||||
}
|
||||
|
||||
let hash = 5381;
|
||||
for (let index = 0; index < diff.length; index += 1) {
|
||||
hash = (hash * 33) ^ diff.charCodeAt(index);
|
||||
}
|
||||
|
||||
return `${diff.length}:${(hash >>> 0).toString(36)}`;
|
||||
}
|
||||
|
||||
export function buildNativeReviewTokensResetKey(input: {
|
||||
readonly threadKey: string | null;
|
||||
readonly sectionId: string | null;
|
||||
readonly scheme: NativeReviewDiffHighlightScheme;
|
||||
readonly diff: string | null | undefined;
|
||||
readonly fileCount: number;
|
||||
readonly rowCount: number;
|
||||
}): string {
|
||||
return [
|
||||
input.threadKey ?? "none",
|
||||
input.sectionId ?? "none",
|
||||
input.scheme,
|
||||
hashReviewDiffKey(input.diff),
|
||||
input.fileCount,
|
||||
input.rowCount,
|
||||
].join(":");
|
||||
}
|
||||
|
||||
export function useNativeReviewDiffBridge(input: {
|
||||
readonly threadKey: string | null;
|
||||
readonly sectionId: string | null;
|
||||
readonly diff: string | null | undefined;
|
||||
readonly data: NativeReviewDiffData;
|
||||
readonly scheme: NativeReviewDiffHighlightScheme;
|
||||
readonly collapsedFileIds: ReadonlyArray<string>;
|
||||
readonly viewedFileIds: ReadonlyArray<string>;
|
||||
readonly selectedRowIds: ReadonlyArray<string>;
|
||||
readonly canHighlight: boolean;
|
||||
}) {
|
||||
const {
|
||||
canHighlight,
|
||||
collapsedFileIds,
|
||||
data,
|
||||
diff,
|
||||
scheme,
|
||||
sectionId,
|
||||
selectedRowIds,
|
||||
threadKey,
|
||||
viewedFileIds,
|
||||
} = input;
|
||||
const [collapsedCommentIds, setCollapsedCommentIds] = useState<ReadonlySet<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
|
||||
const theme = useMemo(() => createNativeReviewDiffTheme(scheme), [scheme]);
|
||||
const rowsJson = useMemo(() => JSON.stringify(data.rows), [data.rows]);
|
||||
const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]);
|
||||
const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
|
||||
const selectedRowIdsJson = useMemo(() => JSON.stringify(selectedRowIds), [selectedRowIds]);
|
||||
const collapsedCommentIdsJson = useMemo(
|
||||
() => JSON.stringify(Array.from(collapsedCommentIds)),
|
||||
[collapsedCommentIds],
|
||||
);
|
||||
const themeJson = useMemo(() => JSON.stringify(theme), [theme]);
|
||||
const styleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []);
|
||||
const tokensResetKey = useMemo(
|
||||
() =>
|
||||
buildNativeReviewTokensResetKey({
|
||||
threadKey,
|
||||
sectionId,
|
||||
scheme,
|
||||
diff,
|
||||
fileCount: data.files.length,
|
||||
rowCount: data.rows.length,
|
||||
}),
|
||||
[data.files.length, data.rows.length, diff, scheme, sectionId, threadKey],
|
||||
);
|
||||
const { tokensPatchJson, updateVisibleRange } = useNativeReviewDiffHighlighting({
|
||||
files: data.files,
|
||||
rows: data.rows,
|
||||
scheme,
|
||||
resetKey: tokensResetKey,
|
||||
enabled: canHighlight,
|
||||
});
|
||||
|
||||
const onDebug = useCallback(
|
||||
(event: NativeSyntheticEvent<Record<string, unknown>>) => {
|
||||
const payload = event.nativeEvent;
|
||||
const message = payload.message;
|
||||
if (
|
||||
(message === "draw-metrics" || message === "visible-range") &&
|
||||
typeof payload.firstRowIndex === "number" &&
|
||||
typeof payload.lastRowIndex === "number"
|
||||
) {
|
||||
updateVisibleRange({
|
||||
firstRowIndex: payload.firstRowIndex,
|
||||
lastRowIndex: payload.lastRowIndex,
|
||||
});
|
||||
}
|
||||
},
|
||||
[updateVisibleRange],
|
||||
);
|
||||
|
||||
const onToggleComment = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly commentId?: string }>) => {
|
||||
const { commentId } = event.nativeEvent;
|
||||
if (!commentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCollapsedCommentIds((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(commentId)) {
|
||||
next.delete(commentId);
|
||||
} else {
|
||||
next.add(commentId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
theme,
|
||||
rowsJson,
|
||||
collapsedFileIdsJson,
|
||||
collapsedCommentIdsJson,
|
||||
viewedFileIdsJson,
|
||||
selectedRowIdsJson,
|
||||
themeJson,
|
||||
styleJson,
|
||||
tokensPatchJson,
|
||||
tokensResetKey,
|
||||
onDebug,
|
||||
onToggleComment,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
highlightNativeReviewDiffVisibleRows,
|
||||
type NativeReviewDiffHighlightEngine,
|
||||
type NativeReviewDiffHighlightScheme,
|
||||
} from "../diffs/nativeReviewDiffHighlighter";
|
||||
import type { NativeReviewDiffRow } from "../diffs/nativeReviewDiffSurface";
|
||||
import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
|
||||
|
||||
interface NativeReviewVisibleRange {
|
||||
readonly firstRowIndex: number;
|
||||
readonly lastRowIndex: number;
|
||||
}
|
||||
|
||||
function createEmptyTokenPatch(resetKey: string): string {
|
||||
return JSON.stringify({ resetKey, tokensByRowId: {} });
|
||||
}
|
||||
|
||||
function isReviewDiffDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
function logReviewDiffDiagnostic(message: string, details?: Record<string, unknown>): void {
|
||||
if (!isReviewDiffDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (details) {
|
||||
console.log(`[review-sheet] ${message}`, details);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[review-sheet] ${message}`);
|
||||
}
|
||||
|
||||
export function useNativeReviewDiffHighlighting(input: {
|
||||
readonly files: ReadonlyArray<NativeReviewDiffFile>;
|
||||
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
|
||||
readonly scheme: NativeReviewDiffHighlightScheme;
|
||||
readonly resetKey: string;
|
||||
readonly enabled: boolean;
|
||||
}) {
|
||||
const { enabled, files, resetKey, rows, scheme } = input;
|
||||
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
|
||||
const visibleRangeRef = useRef<NativeReviewVisibleRange>({
|
||||
firstRowIndex: 0,
|
||||
lastRowIndex: 80,
|
||||
});
|
||||
const visibleChunkIndexRef = useRef(0);
|
||||
const [tokensPatchJson, setTokensPatchJson] = useState(() => createEmptyTokenPatch(resetKey));
|
||||
const [visibleHighlightRequest, setVisibleHighlightRequest] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
highlightedRowIdsRef.current = new Set();
|
||||
visibleChunkIndexRef.current = 0;
|
||||
visibleRangeRef.current = { firstRowIndex: 0, lastRowIndex: 80 };
|
||||
setTokensPatchJson(createEmptyTokenPatch(resetKey));
|
||||
if (enabled && rows.length > 0) {
|
||||
setVisibleHighlightRequest((request) => request + 1);
|
||||
}
|
||||
}, [enabled, resetKey, rows.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
const requestRange = visibleRangeRef.current;
|
||||
const engine: NativeReviewDiffHighlightEngine = "native";
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await highlightNativeReviewDiffVisibleRows({
|
||||
files,
|
||||
rows,
|
||||
scheme,
|
||||
engine,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
alreadyHighlightedRowIds: highlightedRowIdsRef.current,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
if (abortController.signal.aborted || result.rowCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const rowId of Object.keys(result.tokensByRowId)) {
|
||||
highlightedRowIdsRef.current.add(rowId);
|
||||
}
|
||||
|
||||
const chunkIndex = visibleChunkIndexRef.current;
|
||||
visibleChunkIndexRef.current += 1;
|
||||
setTokensPatchJson(
|
||||
JSON.stringify({
|
||||
resetKey,
|
||||
chunkIndex,
|
||||
fileId: "visible",
|
||||
filePath: "visible rows",
|
||||
language: "diff",
|
||||
lineCount: result.rowCount,
|
||||
durationMs: result.durationMs,
|
||||
tokensByRowId: result.tokensByRowId,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
logReviewDiffDiagnostic("native visible highlight failed", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [enabled, files, resetKey, rows, scheme, visibleHighlightRequest]);
|
||||
|
||||
const updateVisibleRange = useCallback((nextRange: NativeReviewVisibleRange) => {
|
||||
const previousRange = visibleRangeRef.current;
|
||||
const movedRows =
|
||||
Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) +
|
||||
Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex);
|
||||
|
||||
visibleRangeRef.current = nextRange;
|
||||
if (movedRows >= 20) {
|
||||
setVisibleHighlightRequest((request) => request + 1);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
tokensPatchJson,
|
||||
updateVisibleRange,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { NativeSyntheticEvent } from "react-native";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildReviewCommentTarget,
|
||||
clearReviewCommentTarget,
|
||||
formatReviewSelectedRangeLabel,
|
||||
getSelectedReviewCommentLines,
|
||||
setReviewCommentTarget,
|
||||
useReviewCommentTarget,
|
||||
} from "./reviewCommentSelection";
|
||||
import type {
|
||||
NativeReviewDiffData,
|
||||
NativeReviewDiffCommentTarget,
|
||||
} from "./nativeReviewDiffAdapter";
|
||||
import type { ReviewSectionItem } from "./reviewModel";
|
||||
|
||||
interface PendingNativeCommentSelection extends NativeReviewDiffCommentTarget {
|
||||
readonly sectionId: string;
|
||||
readonly sectionTitle: string;
|
||||
readonly rowId: string;
|
||||
}
|
||||
|
||||
export function useReviewCommentSelectionController(input: {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly selectedSection: ReviewSectionItem | null;
|
||||
readonly nativeReviewDiffData: NativeReviewDiffData;
|
||||
}) {
|
||||
const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input;
|
||||
const { push } = useRouter();
|
||||
const activeCommentTarget = useReviewCommentTarget();
|
||||
const [pendingNativeCommentSelection, setPendingNativeCommentSelection] =
|
||||
useState<PendingNativeCommentSelection | null>(null);
|
||||
|
||||
const openReviewCommentSheet = useCallback(() => {
|
||||
if (!environmentId || !threadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
push({
|
||||
pathname: "/threads/[environmentId]/[threadId]/review-comment",
|
||||
params: { environmentId, threadId },
|
||||
});
|
||||
}, [environmentId, push, threadId]);
|
||||
|
||||
const selectedRowIds = useMemo(() => {
|
||||
if (
|
||||
activeCommentTarget &&
|
||||
activeCommentTarget.sectionTitle === selectedSection?.title &&
|
||||
activeCommentTarget.startIndex !== activeCommentTarget.endIndex
|
||||
) {
|
||||
return getSelectedReviewCommentLines(activeCommentTarget).flatMap((line) => {
|
||||
const rowId = nativeReviewDiffData.rowIdByCommentLineId.get(line.id);
|
||||
return rowId ? [rowId] : [];
|
||||
});
|
||||
}
|
||||
|
||||
return pendingNativeCommentSelection ? [pendingNativeCommentSelection.rowId] : [];
|
||||
}, [
|
||||
activeCommentTarget,
|
||||
nativeReviewDiffData.rowIdByCommentLineId,
|
||||
pendingNativeCommentSelection,
|
||||
selectedSection?.title,
|
||||
]);
|
||||
|
||||
const selectionAction = useMemo(() => {
|
||||
if (
|
||||
activeCommentTarget &&
|
||||
activeCommentTarget.sectionTitle === selectedSection?.title &&
|
||||
activeCommentTarget.startIndex !== activeCommentTarget.endIndex
|
||||
) {
|
||||
return {
|
||||
title: `Comment on ${formatReviewSelectedRangeLabel(activeCommentTarget)}`,
|
||||
onOpenComment: openReviewCommentSheet,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
pendingNativeCommentSelection &&
|
||||
pendingNativeCommentSelection.sectionTitle === selectedSection?.title
|
||||
) {
|
||||
return {
|
||||
title: "Select range end",
|
||||
onOpenComment: null,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [
|
||||
activeCommentTarget,
|
||||
openReviewCommentSheet,
|
||||
pendingNativeCommentSelection,
|
||||
selectedSection?.title,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
clearReviewCommentTarget();
|
||||
setPendingNativeCommentSelection(null);
|
||||
}, [selectedSection?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeCommentTarget === null) {
|
||||
setPendingNativeCommentSelection(null);
|
||||
}
|
||||
}, [activeCommentTarget]);
|
||||
|
||||
const onPressLine = useCallback(
|
||||
(
|
||||
event: NativeSyntheticEvent<{
|
||||
readonly rowId?: string;
|
||||
readonly gesture?: "tap" | "longPress";
|
||||
}>,
|
||||
) => {
|
||||
if (!selectedSection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { rowId, gesture } = event.nativeEvent;
|
||||
if (!rowId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = nativeReviewDiffData.commentTargetsByRowId.get(rowId);
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (gesture === "longPress") {
|
||||
clearReviewCommentTarget();
|
||||
setPendingNativeCommentSelection({
|
||||
...target,
|
||||
sectionId: selectedSection.id,
|
||||
sectionTitle: selectedSection.title,
|
||||
rowId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
pendingNativeCommentSelection &&
|
||||
pendingNativeCommentSelection.sectionTitle === selectedSection.title &&
|
||||
pendingNativeCommentSelection.filePath === target.filePath
|
||||
) {
|
||||
setReviewCommentTarget(
|
||||
buildReviewCommentTarget(
|
||||
{
|
||||
sectionTitle: pendingNativeCommentSelection.sectionTitle,
|
||||
sectionId: pendingNativeCommentSelection.sectionId,
|
||||
filePath: pendingNativeCommentSelection.filePath,
|
||||
lines: pendingNativeCommentSelection.lines,
|
||||
},
|
||||
pendingNativeCommentSelection.lineIndex,
|
||||
target.lineIndex,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingNativeCommentSelection(null);
|
||||
setReviewCommentTarget({
|
||||
sectionTitle: selectedSection.title,
|
||||
sectionId: selectedSection.id,
|
||||
filePath: target.filePath,
|
||||
lines: target.lines,
|
||||
startIndex: target.lineIndex,
|
||||
endIndex: target.lineIndex,
|
||||
});
|
||||
openReviewCommentSheet();
|
||||
},
|
||||
[
|
||||
nativeReviewDiffData.commentTargetsByRowId,
|
||||
openReviewCommentSheet,
|
||||
pendingNativeCommentSelection,
|
||||
selectedSection,
|
||||
],
|
||||
);
|
||||
|
||||
const clearSelection = useCallback(() => {
|
||||
clearReviewCommentTarget();
|
||||
setPendingNativeCommentSelection(null);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
selectedRowIds,
|
||||
selectionAction,
|
||||
onPressLine,
|
||||
clearSelection,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection";
|
||||
import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter";
|
||||
import { markReviewEvent, measureReviewWork } from "./reviewPerf";
|
||||
import { getCachedReviewParsedDiff } from "./reviewState";
|
||||
import type { ReviewParsedDiff, ReviewSectionItem } from "./reviewModel";
|
||||
|
||||
function isReviewDiffDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
function logReviewDiffDiagnostic(message: string, details?: Record<string, unknown>): void {
|
||||
if (!isReviewDiffDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (details) {
|
||||
console.log(`[review-sheet] ${message}`, details);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[review-sheet] ${message}`);
|
||||
}
|
||||
|
||||
export function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {
|
||||
readonly additions: string | null;
|
||||
readonly deletions: string | null;
|
||||
} {
|
||||
if (parsedDiff.kind !== "files") {
|
||||
return { additions: null, deletions: null };
|
||||
}
|
||||
|
||||
return {
|
||||
additions: `+${parsedDiff.additions}`,
|
||||
deletions: `-${parsedDiff.deletions}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function useReviewDiffData(input: {
|
||||
readonly threadKey: string | null;
|
||||
readonly selectedSection: ReviewSectionItem | null;
|
||||
readonly draftMessage: string;
|
||||
}) {
|
||||
const { draftMessage, selectedSection, threadKey } = input;
|
||||
const parsedDiff = useMemo(
|
||||
() =>
|
||||
measureReviewWork("parse-diff", () =>
|
||||
getCachedReviewParsedDiff({
|
||||
threadKey,
|
||||
sectionId: selectedSection?.id ?? null,
|
||||
diff: selectedSection?.diff,
|
||||
}),
|
||||
),
|
||||
[selectedSection?.diff, selectedSection?.id, threadKey],
|
||||
);
|
||||
const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);
|
||||
const inlineReviewComments = useMemo(
|
||||
() => parseReviewInlineComments(draftMessage),
|
||||
[draftMessage],
|
||||
);
|
||||
const selectedSectionInlineComments = useMemo(
|
||||
() =>
|
||||
selectedSection
|
||||
? inlineReviewComments.filter((comment) => comment.sectionId === selectedSection.id)
|
||||
: [],
|
||||
[inlineReviewComments, selectedSection],
|
||||
);
|
||||
const nativeReviewDiffData = useMemo(
|
||||
() =>
|
||||
measureReviewWork("build-native-diff-data", () =>
|
||||
buildNativeReviewDiffData({
|
||||
parsedDiff,
|
||||
comments: selectedSectionInlineComments,
|
||||
}),
|
||||
),
|
||||
[parsedDiff, selectedSectionInlineComments],
|
||||
);
|
||||
const pendingReviewCommentCount = useMemo(
|
||||
() => countReviewCommentContexts(draftMessage),
|
||||
[draftMessage],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (parsedDiff.kind !== "files") {
|
||||
return;
|
||||
}
|
||||
|
||||
markReviewEvent("parsed-diff-ready", {
|
||||
sectionId: selectedSection?.id ?? null,
|
||||
fileCount: parsedDiff.fileCount,
|
||||
additions: parsedDiff.additions,
|
||||
deletions: parsedDiff.deletions,
|
||||
renderedItems: nativeReviewDiffData.rows.length,
|
||||
});
|
||||
logReviewDiffDiagnostic("parsed diff files", {
|
||||
selectedSectionId: selectedSection?.id ?? null,
|
||||
fileCount: parsedDiff.fileCount,
|
||||
renderableFileCount: parsedDiff.files.length,
|
||||
});
|
||||
}, [nativeReviewDiffData.rows.length, parsedDiff, selectedSection?.id]);
|
||||
|
||||
return {
|
||||
parsedDiff,
|
||||
headerDiffSummary,
|
||||
nativeReviewDiffData,
|
||||
pendingReviewCommentCount,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import {
|
||||
buildReviewSectionItems,
|
||||
getDefaultReviewSectionId,
|
||||
getReadyReviewCheckpoints,
|
||||
getReviewSectionIdForCheckpoint,
|
||||
} from "./reviewModel";
|
||||
import {
|
||||
setReviewGitSections,
|
||||
setReviewSelectedSectionId,
|
||||
setReviewTurnDiff,
|
||||
type ReviewCacheForThread,
|
||||
} from "./reviewState";
|
||||
|
||||
export function useReviewSections(input: {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly reviewCache: ReviewCacheForThread;
|
||||
}) {
|
||||
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 turnDiffByIdRef = useRef(reviewCache.turnDiffById);
|
||||
|
||||
useEffect(() => {
|
||||
turnDiffByIdRef.current = reviewCache.turnDiffById;
|
||||
}, [reviewCache.turnDiffById]);
|
||||
|
||||
const readyCheckpoints = useMemo(
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
);
|
||||
const checkpointBySectionId = useMemo(() => {
|
||||
return Object.fromEntries(
|
||||
readyCheckpoints.map((checkpoint) => [
|
||||
getReviewSectionIdForCheckpoint(checkpoint),
|
||||
checkpoint,
|
||||
]),
|
||||
) as Record<string, OrchestrationCheckpointSummary>;
|
||||
}, [readyCheckpoints]);
|
||||
const reviewSections = useMemo(
|
||||
() =>
|
||||
buildReviewSectionItems({
|
||||
checkpoints: readyCheckpoints,
|
||||
gitSections: reviewCache.gitSections,
|
||||
turnDiffById: reviewCache.turnDiffById,
|
||||
loadingTurnIds,
|
||||
}),
|
||||
[loadingTurnIds, readyCheckpoints, reviewCache.gitSections, reviewCache.turnDiffById],
|
||||
);
|
||||
const selectedSection = useMemo(
|
||||
() =>
|
||||
reviewSections.find((section) => section.id === reviewCache.selectedSectionId) ??
|
||||
reviewSections[0] ??
|
||||
null,
|
||||
[reviewCache.selectedSectionId, reviewSections],
|
||||
);
|
||||
const fallbackSectionId = useMemo(
|
||||
() => getDefaultReviewSectionId(reviewSections),
|
||||
[reviewSections],
|
||||
);
|
||||
const hasReviewSections = reviewSections.length > 0;
|
||||
const selectedSectionIdExists = useMemo(
|
||||
() =>
|
||||
reviewCache.selectedSectionId
|
||||
? reviewSections.some((section) => section.id === reviewCache.selectedSectionId)
|
||||
: false,
|
||||
[reviewCache.selectedSectionId, reviewSections],
|
||||
);
|
||||
|
||||
const loadGitDiffs = useCallback(async () => {
|
||||
if (!environmentId || !selectedThreadCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
setError("Remote connection is not ready.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingGitDiffs(true);
|
||||
setError(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.");
|
||||
} finally {
|
||||
setLoadingGitDiffs(false);
|
||||
}
|
||||
}, [environmentId, reviewCache.threadKey, selectedThreadCwd]);
|
||||
|
||||
const loadTurnDiff = useCallback(
|
||||
async (checkpoint: OrchestrationCheckpointSummary, force = false) => {
|
||||
if (!environmentId || !threadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sectionId = getReviewSectionIdForCheckpoint(checkpoint);
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
|
||||
}
|
||||
|
||||
if (!force && turnDiffByIdRef.current[sectionId] !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
setError("Remote connection is not ready.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingTurnIds((current) => ({ ...current, [sectionId]: true }));
|
||||
setError(null);
|
||||
try {
|
||||
const result = await client.orchestration.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1),
|
||||
toTurnCount: checkpoint.checkpointTurnCount,
|
||||
});
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff);
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Failed to load turn diff.");
|
||||
} finally {
|
||||
setLoadingTurnIds((current) => {
|
||||
const next = { ...current };
|
||||
delete next[sectionId];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[environmentId, reviewCache.threadKey, threadId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void loadGitDiffs();
|
||||
}, [loadGitDiffs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasReviewSections) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (reviewCache.threadKey && (!reviewCache.selectedSectionId || !selectedSectionIdExists)) {
|
||||
setReviewSelectedSectionId(reviewCache.threadKey, fallbackSectionId);
|
||||
}
|
||||
}, [
|
||||
fallbackSectionId,
|
||||
hasReviewSections,
|
||||
reviewCache.selectedSectionId,
|
||||
reviewCache.threadKey,
|
||||
selectedSectionIdExists,
|
||||
]);
|
||||
|
||||
const latestCheckpoint = readyCheckpoints[0] ?? null;
|
||||
const latestSectionId = latestCheckpoint
|
||||
? getReviewSectionIdForCheckpoint(latestCheckpoint)
|
||||
: null;
|
||||
const latestTurnDiffLoaded = latestSectionId
|
||||
? reviewCache.turnDiffById[latestSectionId] !== undefined
|
||||
: true;
|
||||
const latestTurnDiffLoading = latestSectionId ? loadingTurnIds[latestSectionId] === true : false;
|
||||
|
||||
useEffect(() => {
|
||||
if (!latestCheckpoint || !latestSectionId || latestTurnDiffLoaded || latestTurnDiffLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
void loadTurnDiff(latestCheckpoint);
|
||||
}, [
|
||||
latestCheckpoint,
|
||||
latestSectionId,
|
||||
latestTurnDiffLoaded,
|
||||
latestTurnDiffLoading,
|
||||
loadTurnDiff,
|
||||
]);
|
||||
|
||||
const selectedTurnCheckpoint =
|
||||
selectedSection?.kind === "turn" ? (checkpointBySectionId[selectedSection.id] ?? null) : null;
|
||||
const selectedTurnDiffMissing =
|
||||
selectedSection?.kind === "turn" && selectedSection.diff === null && selectedTurnCheckpoint;
|
||||
const selectedTurnDiffLoading =
|
||||
selectedSection?.kind === "turn" ? loadingTurnIds[selectedSection.id] === true : false;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedTurnDiffMissing || selectedTurnDiffLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
void loadTurnDiff(selectedTurnDiffMissing);
|
||||
}, [loadTurnDiff, selectedTurnDiffLoading, selectedTurnDiffMissing]);
|
||||
|
||||
const refreshSelectedSection = useCallback(async () => {
|
||||
if (!selectedSection) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedSection.kind === "turn") {
|
||||
const checkpoint = checkpointBySectionId[selectedSection.id];
|
||||
if (checkpoint) {
|
||||
await loadTurnDiff(checkpoint, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await loadGitDiffs();
|
||||
}, [checkpointBySectionId, loadGitDiffs, loadTurnDiff, selectedSection]);
|
||||
|
||||
const selectSection = useCallback(
|
||||
(sectionId: string) => {
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
|
||||
}
|
||||
},
|
||||
[reviewCache.threadKey],
|
||||
);
|
||||
|
||||
return {
|
||||
error,
|
||||
loadingGitDiffs,
|
||||
loadingTurnIds,
|
||||
reviewSections,
|
||||
selectedSection,
|
||||
refreshSelectedSection,
|
||||
selectSection,
|
||||
};
|
||||
}
|
||||
@@ -41,6 +41,7 @@ import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
|
||||
import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
|
||||
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
|
||||
import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import { useThreadComposerState } from "../../state/use-thread-composer-state";
|
||||
|
||||
@@ -65,9 +66,8 @@ export function ThreadRouteScreen() {
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const commands = useSelectedThreadCommands({
|
||||
activePendingUserInput: composer.activePendingUserInput,
|
||||
activePendingUserInputAnswers: composer.activePendingUserInputAnswers,
|
||||
refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
|
||||
});
|
||||
const refreshSelectedThread = commands.onRefresh;
|
||||
@@ -369,12 +369,12 @@ export function ThreadRouteScreen() {
|
||||
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={composer.activePendingApproval}
|
||||
respondingApprovalId={commands.respondingApprovalId}
|
||||
activePendingUserInput={composer.activePendingUserInput}
|
||||
activePendingUserInputDrafts={composer.activePendingUserInputDrafts}
|
||||
activePendingUserInputAnswers={composer.activePendingUserInputAnswers}
|
||||
respondingUserInputId={commands.respondingUserInputId}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
activePendingUserInput={requests.activePendingUserInput}
|
||||
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
|
||||
activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
|
||||
respondingUserInputId={requests.respondingUserInputId}
|
||||
draftMessage={composer.draftMessage}
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
@@ -395,10 +395,10 @@ export function ThreadRouteScreen() {
|
||||
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
|
||||
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
|
||||
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
|
||||
onRespondToApproval={commands.onRespondToApproval}
|
||||
onSelectUserInputOption={composer.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={composer.onChangeUserInputCustomAnswer}
|
||||
onSubmitUserInput={commands.onSubmitUserInput}
|
||||
onRespondToApproval={requests.onRespondToApproval}
|
||||
onSelectUserInputOption={requests.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
onSubmitUserInput={requests.onSubmitUserInput}
|
||||
/>
|
||||
|
||||
<ThreadNavigationDrawer
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
type ModelSelection,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -16,23 +14,14 @@ import { useRemoteEnvironmentState } from "./use-remote-environment-registry";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
|
||||
export function useSelectedThreadCommands(input: {
|
||||
readonly activePendingUserInput: {
|
||||
readonly requestId: ApprovalRequestId;
|
||||
} | null;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly refreshSelectedThreadGitStatus: (options?: {
|
||||
readonly quiet?: boolean;
|
||||
readonly cwd?: string | null;
|
||||
}) => Promise<unknown>;
|
||||
}) {
|
||||
const { activePendingUserInput, activePendingUserInputAnswers, refreshSelectedThreadGitStatus } =
|
||||
input;
|
||||
const { refreshSelectedThreadGitStatus } = input;
|
||||
const { selectedThread } = useThreadSelection();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const onRefresh = useCallback(async () => {
|
||||
const targets = selectedThread
|
||||
@@ -187,71 +176,12 @@ export function useSelectedThreadCommands(input: {
|
||||
[selectedThread],
|
||||
);
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingApprovalId(requestId);
|
||||
try {
|
||||
await client.orchestration.dispatchCommand({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
threadId: selectedThread.id,
|
||||
requestId,
|
||||
decision,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
} finally {
|
||||
setRespondingApprovalId((current) => (current === requestId ? null : current));
|
||||
}
|
||||
},
|
||||
[selectedThread],
|
||||
);
|
||||
|
||||
const onSubmitUserInput = useCallback(async () => {
|
||||
if (!selectedThread || !activePendingUserInput || !activePendingUserInputAnswers) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingUserInputId(activePendingUserInput.requestId);
|
||||
try {
|
||||
await client.orchestration.dispatchCommand({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
threadId: selectedThread.id,
|
||||
requestId: activePendingUserInput.requestId,
|
||||
answers: activePendingUserInputAnswers,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
} finally {
|
||||
setRespondingUserInputId((current) =>
|
||||
current === activePendingUserInput.requestId ? null : current,
|
||||
);
|
||||
}
|
||||
}, [activePendingUserInput, activePendingUserInputAnswers, selectedThread]);
|
||||
|
||||
return {
|
||||
respondingApprovalId,
|
||||
respondingUserInputId,
|
||||
onRefresh,
|
||||
onUpdateThreadModelSelection,
|
||||
onUpdateThreadRuntimeMode,
|
||||
onUpdateThreadInteractionMode,
|
||||
onRenameThread,
|
||||
onStopThread,
|
||||
onRespondToApproval,
|
||||
onSubmitUserInput,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { ApprovalRequestId, CommandId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { scopedRequestKey } from "../lib/scopedEntities";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { uuidv4 } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
import { useSelectedThreadDetail } from "./use-thread-detail";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
|
||||
const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
|
||||
|
||||
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[questionId]: {
|
||||
selectedOptionLabel: label,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setUserInputDraftCustomAnswer(
|
||||
requestKey: string,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[questionId]: setPendingUserInputCustomAnswer(
|
||||
current[requestKey]?.[questionId],
|
||||
customAnswer,
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSelectedThreadRequests() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const activePendingApprovals = useMemo(
|
||||
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
activePendingUserInput && selectedThreadShell
|
||||
? (userInputDraftsByRequestKey[
|
||||
scopedRequestKey(selectedThreadShell.environmentId, activePendingUserInput.requestId)
|
||||
] ?? {})
|
||||
: {};
|
||||
const activePendingUserInputAnswers = activePendingUserInput
|
||||
? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftOption(requestKey, questionId, label);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onChangeUserInputCustomAnswer = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThreadShell.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingApprovalId(requestId);
|
||||
try {
|
||||
await client.orchestration.dispatchCommand({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
threadId: selectedThreadShell.id,
|
||||
requestId,
|
||||
decision,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
} finally {
|
||||
setRespondingApprovalId((current) => (current === requestId ? null : current));
|
||||
}
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onSubmitUserInput = useCallback(async () => {
|
||||
if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThreadShell.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingUserInputId(activePendingUserInput.requestId);
|
||||
try {
|
||||
await client.orchestration.dispatchCommand({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
threadId: selectedThreadShell.id,
|
||||
requestId: activePendingUserInput.requestId,
|
||||
answers: activePendingUserInputAnswers,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
} finally {
|
||||
setRespondingUserInputId((current) =>
|
||||
current === activePendingUserInput.requestId ? null : current,
|
||||
);
|
||||
}
|
||||
}, [activePendingUserInput, activePendingUserInputAnswers, selectedThreadShell]);
|
||||
|
||||
return {
|
||||
activePendingApproval,
|
||||
activePendingUserInput,
|
||||
activePendingUserInputDrafts,
|
||||
activePendingUserInputAnswers,
|
||||
respondingApprovalId,
|
||||
respondingUserInputId,
|
||||
onRespondToApproval,
|
||||
onSelectUserInputOption,
|
||||
onChangeUserInputCustomAnswer,
|
||||
onSubmitUserInput,
|
||||
};
|
||||
}
|
||||
@@ -2,13 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type ApprovalRequestId,
|
||||
type EnvironmentId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -18,16 +12,8 @@ import {
|
||||
pickComposerImages,
|
||||
} from "../lib/composerImages";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedRequestKey, scopedThreadKey } from "../lib/scopedEntities";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
buildThreadFeed,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
type PendingUserInputDraftAnswer,
|
||||
type QueuedThreadMessage,
|
||||
} from "../lib/threadActivity";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { buildThreadFeed, type QueuedThreadMessage } from "../lib/threadActivity";
|
||||
import { uuidv4 } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
@@ -58,10 +44,6 @@ const queuedMessagesByThreadKeyAtom = Atom.make<Record<string, ReadonlyArray<Que
|
||||
{},
|
||||
).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-composer:queued-messages"));
|
||||
|
||||
const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
|
||||
|
||||
function setDraftMessage(threadKey: string, value: string): void {
|
||||
const current = appAtomRegistry.get(draftMessageByThreadKeyAtom);
|
||||
appAtomRegistry.set(draftMessageByThreadKeyAtom, {
|
||||
@@ -187,37 +169,6 @@ function removeQueuedMessage(
|
||||
appAtomRegistry.set(queuedMessagesByThreadKeyAtom, next);
|
||||
}
|
||||
|
||||
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[questionId]: {
|
||||
selectedOptionLabel: label,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setUserInputDraftCustomAnswer(
|
||||
requestKey: string,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[questionId]: setPendingUserInputCustomAnswer(
|
||||
current[requestKey]?.[questionId],
|
||||
customAnswer,
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function useQueueDrain(input: {
|
||||
readonly dispatchingQueuedMessageId: MessageId | null;
|
||||
readonly queuedMessagesByThreadKey: Record<string, ReadonlyArray<QueuedThreadMessage>>;
|
||||
@@ -284,15 +235,10 @@ export function useThreadComposerState() {
|
||||
const draftAttachmentsByThreadKey = useAtomValue(draftAttachmentsByThreadKeyAtom);
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useAtomValue(queuedMessagesByThreadKeyAtom);
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
|
||||
const selectedThreadKey = selectedThreadShell
|
||||
? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
|
||||
: null;
|
||||
const selectedRequestKey = selectedThreadShell
|
||||
? (requestId: ApprovalRequestId) =>
|
||||
scopedRequestKey(selectedThreadShell.environmentId, requestId)
|
||||
: null;
|
||||
const selectedThreadQueuedMessages = useMemo(
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
@@ -336,25 +282,6 @@ export function useThreadComposerState() {
|
||||
);
|
||||
}, [queuedSendStartedAt, selectedThread, selectedThreadSessionActivity]);
|
||||
|
||||
const activePendingApprovals = useMemo(
|
||||
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
activePendingUserInput && selectedRequestKey
|
||||
? (userInputDraftsByRequestKey[selectedRequestKey(activePendingUserInput.requestId)] ?? {})
|
||||
: {};
|
||||
const activePendingUserInputAnswers = activePendingUserInput
|
||||
? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
|
||||
: null;
|
||||
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
@@ -442,30 +369,6 @@ export function useThreadComposerState() {
|
||||
clearDraft(threadKey);
|
||||
}, [draftAttachmentsByThreadKey, draftMessageByThreadKey, selectedThreadShell]);
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftOption(requestKey, questionId, label);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onChangeUserInputCustomAnswer = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
@@ -553,10 +456,6 @@ export function useThreadComposerState() {
|
||||
selectedThreadFeed,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
activePendingApproval,
|
||||
activePendingUserInput,
|
||||
activePendingUserInputDrafts,
|
||||
activePendingUserInputAnswers,
|
||||
draftMessage,
|
||||
draftAttachments,
|
||||
activeThreadBusy,
|
||||
@@ -566,7 +465,5 @@ export function useThreadComposerState() {
|
||||
onNativePasteImages,
|
||||
onRemoveDraftImage,
|
||||
onSendMessage,
|
||||
onSelectUserInputOption,
|
||||
onChangeUserInputCustomAnswer,
|
||||
};
|
||||
}
|
||||
@@ -2598,6 +2598,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
it.effect("routes websocket rpc git methods", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
cwd: "/tmp/repo",
|
||||
},
|
||||
layers: {
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { defineConfig, mergeConfig } from "vitest/config";
|
||||
|
||||
import viteConfig from "./vite.config";
|
||||
|
||||
export default mergeConfig(
|
||||
viteConfig,
|
||||
defineConfig({
|
||||
test: {
|
||||
// The web runtime suite exercises auth bootstrap, saved environments,
|
||||
// and websocket subscription lifecycles. Under the full monorepo test
|
||||
// run, those async tests can exceed Vitest's default 5s budget.
|
||||
testTimeout: 15_000,
|
||||
hookTimeout: 15_000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
Reference in new issue
Block a user