import { router, useLocalSearchParams } from "expo-router"; import { errorCode } from "@/lib/action-error"; import { useCallback, useEffect, useMemo, useState } from "react"; import { ActivityIndicator, Alert, Modal, Pressable, ScrollView, View } from "react-native"; import type { Locale } from "@linkshell/client-core"; import type { GitDiffFileStatus } from "@linkshell/wire"; import { Button } from "@/components/button"; import { ConnectionBanner } from "@/components/connection-banner"; import { Text, TextInput } from "@/components/fixed-text"; import { Glass } from "@/components/glass"; import { Icon } from "@/components/icon"; import { EmptyState } from "@/components/state-views"; import { DiffView } from "@/components/timeline/tool-call"; import { useActions, useClient, useConnection, useConnectionStatus } from "@/lib/client"; import { gitDiffFileToChange } from "@/lib/coding-ux"; import { fileChanges, type FileChange } from "@/lib/describe"; import { baseName, shortPath } from "@/lib/format"; import { haptics } from "@/lib/haptics"; import { useLocale, type I18nKey } from "@/lib/locale"; import { DiffStat } from "@/components/diff-stat"; import { colors } from "@/theme/colors"; import { mono, type, radius } from "@/theme/type"; export interface DiffReviewComment { key: string; filePath: string; editIndex: number; lineIndex: number; lineCode: string; comment: string; } export function formatDiffReviewPrompt(comments: DiffReviewComment[], cwd?: string, locale: Locale = "zh"): string { if (comments.length === 0) return ""; const header = locale === "en" ? "Please update the code based on these inline review comments:" : locale === "ja" ? "以下の行単位コードレビューのコメントに従って修正してください:" : "请根据以下行级代码审查意见修改代码:"; const lines: string[] = [header]; for (const item of comments) { const rel = relativePath(item.filePath, cwd); const snippet = item.lineCode.slice(1).trim(); lines.push(`\n- **\`${rel}\`**${snippet ? ` (\`${snippet.slice(0, 80)}\`)` : ""}:\n ${item.comment.trim()}`); } return lines.join("\n"); } type DiffSourceMode = "session" | "git"; interface FileEntry { path: string; added: number; removed: number; kind: FileChange["kind"]; gitStatus?: GitDiffFileStatus; binary?: boolean; edits: FileChange[]; } function collectSessionEdits(items: ReturnType): FileEntry[] { const byPath = new Map(); for (const item of items) { if (item.kind !== "tool" || item.status === "failed") continue; for (const change of fileChanges(item.content)) { const entry = byPath.get(change.path) ?? { path: change.path, added: 0, removed: 0, kind: change.kind, edits: [] }; entry.added += change.added; entry.removed += change.removed; if (change.kind === "delete") entry.kind = "delete"; entry.edits.push(change); byPath.set(change.path, entry); } } return [...byPath.values()]; } function useItems(id: string) { return useClient((state) => state.views[id]?.items) ?? []; } function relativePath(path: string, cwd?: string): string { if (cwd && path.startsWith(`${cwd}/`)) return path.slice(cwd.length + 1); return shortPath(path); } function gitStatusKey(status: GitDiffFileStatus | undefined, kind: FileChange["kind"]): I18nKey | null { if (status === "added") return "changes.statusAdded"; if (status === "deleted") return "changes.statusDeleted"; if (status === "renamed") return "changes.statusRenamed"; if (status === "untracked") return "changes.statusUntracked"; if (status === "modified") return "changes.statusModified"; if (kind === "add") return "changes.statusAdded"; if (kind === "delete") return "changes.statusDeleted"; return null; } function FileRow({ entry, first, cwd, canRevert, reverting, commentsByKey, onSelectLine, onRevert, }: { entry: FileEntry; first: boolean; cwd?: string; canRevert: boolean; reverting: boolean; commentsByKey: Record; onSelectLine: (editIndex: number, lineIndex: number, lineText: string) => void; onRevert: () => void; }) { const { t, pick } = useLocale(); const [open, setOpen] = useState(first); const badgeKey = gitStatusKey(entry.gitStatus, entry.kind); const badgeLabel = badgeKey ? t(badgeKey) : null; const fileCommentCount = Object.values(commentsByKey).filter((c) => c.filePath === entry.path).length; return ( { haptics.selection(); setOpen((value) => !value); }} accessibilityRole="button" accessibilityState={{ expanded: open }} style={{ flexDirection: "row", alignItems: "center", gap: 10, paddingVertical: 12, paddingHorizontal: 14 }} > {baseName(entry.path)} {badgeLabel ? ( {badgeLabel} ) : null} {fileCommentCount > 0 ? ( {t("changes.reviewCount", { count: fileCommentCount })} ) : null} {relativePath(entry.path, cwd)} {canRevert ? ( { e.stopPropagation?.(); onRevert(); }} style={({ pressed }) => ({ paddingHorizontal: 8, paddingVertical: 4, borderRadius: 999, backgroundColor: colors.fill, opacity: reverting ? 0.45 : pressed ? 0.6 : 1, })} > {reverting ? ( ) : ( {t("changes.revertFile")} )} ) : null} {open ? ( {entry.binary ? ( {t("changes.binaryFile")} ) : ( entry.edits.map((edit, editIndex) => { const lineComments: Record = {}; for (const item of Object.values(commentsByKey)) { if (item.filePath === entry.path && item.editIndex === editIndex) { lineComments[item.lineIndex] = item.comment; } } return ( {entry.edits.length > 1 ? ( {pick({ zh: `第 ${editIndex + 1} 次修改`, en: `Edit #${editIndex + 1}`, ja: `${editIndex + 1} 回目の変更`, })} ) : null} onSelectLine(editIndex, lineIndex, lineText)} /> ); }) )} ) : null} ); } export function ChangesScreen() { const { id } = useLocalSearchParams<{ id: string }>(); return ; } export function ChangesContent({ sessionId, embedded = false }: { sessionId: string; embedded?: boolean }) { const { locale, t, pick } = useLocale(); const { link } = useConnection(); const status = useConnectionStatus(); const online = status === "online"; const items = useItems(sessionId); const cwd = useClient((state) => state.sessions[sessionId]?.cwd); const base = useClient( (state) => (state.sessions[sessionId]?.worktree as { branch: string; source: string; base?: string } | undefined)?.base, ); const actions = useActions(); const [mode, setMode] = useState("git"); const [gitFiles, setGitFiles] = useState([]); const [gitBranch, setGitBranch] = useState(undefined); const [gitTruncated, setGitTruncated] = useState(false); const [gitLoading, setGitLoading] = useState(false); const [gitSupported, setGitSupported] = useState(true); const [revertingPath, setRevertingPath] = useState(null); const [wrapUpBusy, setWrapUpBusy] = useState<"commit" | "tests" | null>(null); const sessionFiles = useMemo(() => collectSessionEdits(items), [items]); const loadGitDiff = useCallback(async () => { if (!cwd || !online) return; setGitLoading(true); try { const res = await link.call("git.diff", { cwd, ...(base ? { base } : {}), includeUntracked: true }); const converted: FileEntry[] = res.files.map((file) => { const change = gitDiffFileToChange(file); return { path: file.path, added: file.additions, removed: file.deletions, kind: change.kind, gitStatus: file.status, binary: file.binary, edits: [change], }; }); setGitFiles(converted); setGitBranch(res.branch); setGitTruncated(res.truncated); setGitSupported(true); } catch (reason) { // Only a computer that cannot do this at all loses the tab. A timeout or a dropped link // falls back to the session's own changes and leaves the tab there to try again. if (errorCode(reason) === "host_outdated") setGitSupported(false); setMode("session"); } finally { setGitLoading(false); } }, [base, cwd, link, online]); useEffect(() => { if (mode === "git") void loadGitDiff(); }, [loadGitDiff, mode]); const files = mode === "git" && gitSupported ? gitFiles : sessionFiles; const added = files.reduce((sum, file) => sum + file.added, 0); const removed = files.reduce((sum, file) => sum + file.removed, 0); const [commentsByKey, setCommentsByKey] = useState>({}); const [editingTarget, setEditingTarget] = useState<{ key: string; filePath: string; editIndex: number; lineIndex: number; lineCode: string; } | null>(null); const [draftComment, setDraftComment] = useState(""); const [sendingReview, setSendingReview] = useState(false); const commentList = useMemo(() => Object.values(commentsByKey), [commentsByKey]); const openLineEditor = (filePath: string, editIndex: number, lineIndex: number, lineCode: string) => { const key = `${filePath}:${editIndex}:${lineIndex}`; const existing = commentsByKey[key]?.comment ?? ""; setEditingTarget({ key, filePath, editIndex, lineIndex, lineCode }); setDraftComment(existing); }; const saveLineComment = () => { if (!editingTarget) return; const trimmed = draftComment.trim(); setCommentsByKey((prev) => { const next = { ...prev }; if (!trimmed) { delete next[editingTarget.key]; } else { next[editingTarget.key] = { ...editingTarget, comment: trimmed, }; } return next; }); haptics.success(); setEditingTarget(null); setDraftComment(""); }; const confirmRevertFile = (filePath: string) => { if (!cwd || !online || revertingPath) return; const displayPath = relativePath(filePath, cwd); Alert.alert( t("changes.revertConfirmTitle"), t("changes.revertConfirmBody", { path: displayPath }), [ { text: t("common.cancel"), style: "cancel" }, { text: t("changes.revertFile"), style: "destructive", onPress: async () => { setRevertingPath(filePath); haptics.medium(); try { await link.call("git.revertFile", { cwd, path: filePath }); haptics.success(); await loadGitDiff(); } catch (error) { haptics.error(); Alert.alert( pick({ zh: "还原失败", en: "Revert failed", ja: "復元に失敗しました" }), error instanceof Error ? error.message : String(error), ); } finally { setRevertingPath(null); } }, }, ], ); }; const dispatchWrapUpAction = async (kind: "commit" | "tests") => { if (!online || wrapUpBusy) return; setWrapUpBusy(kind); haptics.medium(); try { const promptText = kind === "commit" ? t("changes.askCommitPrPrompt") : t("changes.askRunTestsPrompt"); const delivery = await actions.send(sessionId, [{ type: "text", text: promptText }]); if (delivery === "failed") { Alert.alert( pick({ zh: "发送失败", en: "Failed to send", ja: "送信に失敗しました" }), pick({ zh: "未能将指令发送给 Agent。", en: "Could not deliver prompt to Agent.", ja: "エージェントに送信できませんでした。" }), ); return; } haptics.success(); if (!embedded) router.back(); } catch (error) { Alert.alert( pick({ zh: "发送失败", en: "Failed to send", ja: "送信に失敗しました" }), error instanceof Error ? error.message : String(error), ); } finally { setWrapUpBusy(null); } }; const submitAllComments = async () => { if (!commentList.length || sendingReview) return; setSendingReview(true); haptics.medium(); try { const promptText = formatDiffReviewPrompt(commentList, cwd, locale); const delivery = await actions.send(sessionId, [{ type: "text", text: promptText }]); if (delivery === "failed") { Alert.alert( pick({ zh: "发送失败", en: "Failed to send", ja: "送信に失敗しました" }), pick({ zh: "未能将代码批注发送给 Agent。", en: "Could not deliver review comments to Agent.", ja: "コメントを送信できませんでした。" }), ); return; } haptics.success(); setCommentsByKey({}); if (!embedded) router.back(); } catch (error) { Alert.alert( pick({ zh: "发送失败", en: "Failed to send", ja: "送信に失敗しました" }), error instanceof Error ? error.message : String(error), ); } finally { setSendingReview(false); } }; return ( 0 ? 96 : 24, gap: 12 }} > {/* Mode Switcher: Real Git Diff vs Session Edits */} {([ { key: "git" as const, label: t("changes.gitWorkingTree"), disabled: !gitSupported }, { key: "session" as const, label: t("changes.sessionEdits"), disabled: false }, ]).map((tab) => { const active = mode === tab.key; return ( { haptics.selection(); setMode(tab.key); }} style={{ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 999, backgroundColor: active ? colors.card : "transparent", opacity: tab.disabled ? 0.45 : 1, }} > {tab.label} ); })} {mode === "git" ? ( void loadGitDiff()} style={({ pressed }) => ({ width: 34, height: 34, borderRadius: 17, backgroundColor: colors.fill, alignItems: "center", justifyContent: "center", opacity: pressed ? 0.6 : 1, })} > {gitLoading ? ( ) : ( )} ) : null} {/* 1-Tap Wrap-Up Actions Bar */} {online && (files.length > 0 || sessionFiles.length > 0) ? (