TypeScript
feat(mobile): keep pull requests available offline (#18351)
Julius Marminged07a07f33c0a
diff --git a/apps/mobile/src/connection/pull-request-cache-store.ts b/apps/mobile/src/connection/pull-request-cache-store.tsnew file mode 100644index 00000000000..3eab93296e1--- /dev/null+++ b/apps/mobile/src/connection/pull-request-cache-store.ts@@ -0,0 +1,22 @@+import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import { MobileDatabase } from "../persistence/mobile-database";++export const layer = Layer.effect(+ EnvironmentQueryStore,+ Effect.gen(function* () {+ const database = yield* MobileDatabase;+ return {+ load: (environmentId, key) =>+ database+ .loadCache(environmentId, "pull-request", `v1:${key}`)+ .pipe(Effect.catch(() => Effect.succeedNone)),+ save: (environmentId, key, payload) =>+ database+ .saveCache(environmentId, "pull-request", `v1:${key}`, 1, payload)+ .pipe(Effect.catch(() => Effect.logWarning("Offline query database save failed"))),+ } satisfies NonNullable<typeof EnvironmentQueryStore.Service>;+ }),+);diff --git a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestControls.tsxindex 0a7fe6b34f0..156b36b2155 100644--- a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx@@ -123,7 +123,8 @@ export function PullRequestActionToolbar(props: {const agent = usePullRequestAgentActions(props.params, props.pr, props.filePath);const canReview = permissions.verdicts.length > 0;const pendingReview = canReview && draft.comments.length > 0;- const canOpenThread = agent.threads.length > 0 || agent.canAsk;+ const showAgentControls = agent.canAsk || !permissions.connected;+ const canOpenThread = agent.threads.length > 0 || showAgentControls;const threadLabel = agent.threads.length ? "Continue thread" : "Work on PR";const primaryLabel = pendingReview ? `Submit review · ${draft.comments.length}` : threadLabel;const chooseThread = agent.threads.length > 1;@@ -142,7 +143,7 @@ export function PullRequestActionToolbar(props: {// Reserve the native outer margins, custom-button padding, and item gaps.// UIKit needs this space to keep every action out of its overflow menu.// Duo's side rail uses an intrinsic icon item instead.- const sideControls = Number(agent.canAsk) + 1;+ const sideControls = Number(showAgentControls) + 1;const primaryWidth = verticalControls? undefined: Math.max(@@ -166,7 +167,7 @@ export function PullRequestActionToolbar(props: {className="flex-row items-center justify-between gap-3 border-t border-border-subtle bg-screen px-4 pt-2"style={{ paddingBottom: Math.max(insets.bottom, 8) }}>- {agent.canAsk ? (+ {showAgentControls ? (<ControlPillMenutitle="AI helpers"actions={agentActions.map((action) => agent.menuAction(action.task))}@@ -259,7 +260,7 @@ export function PullRequestActionToolbar(props: {/>)) : null;- const agentControl = agent.canAsk ? (+ const agentControl = showAgentControls ? (<NativeHeaderToolbar.Menuidentifier="pull-request-agent"width={controlSize}diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsxindex 70f3fe9184a..b11eeeb9954 100644--- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx@@ -1,13 +1,20 @@-import { useMemo, useState } from "react";-import { ActivityIndicator, Pressable, ScrollView, StyleSheet, View } from "react-native";+import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown";+import {+ PullRequestImageAttachment,+ PullRequestMedia,+ PullRequestMediaContext,+} from "./PullRequestMedia";+import { PullRequestSectionHeading } from "./PullRequestSectionHeading";+import { useContext, useMemo, useState } from "react";+import { Pressable, ScrollView, StyleSheet, View } from "react-native";import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";-import { Image } from "expo-image";+import { pullRequestImageSource } from "./pullRequestMediaSource";import { parseMarkdownWithOptions } from "react-native-nitro-markdown/headless";import { nativeMarkdownWithHtml } from "@t3tools/mobile-markdown-text/markdown";import { SymbolView } from "../../components/AppSymbol";import { AppText as Text } from "../../components/AppText";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";-import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";+import type { FilePreviewItem } from "../../components/FilePreviewModal";import { PullRequestMarkdown } from "./PullRequestMarkdown";import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent";@@ -21,31 +28,33 @@ export function PullRequestDescription(props: {}) {const { expanded, onExpandedChange } = props;const [bodyHeight, setBodyHeight] = useState(0);- const [preview, setPreview] = useState<FilePreviewSource | null>(null);- const openingUri = preview && "uri" in preview ? preview.uri : null;+ const mediaContext = useContext(PullRequestMediaContext);const { themeVariables: colors } = useAppearancePreferences();const content = useMemo(() => {const document = nativeMarkdownWithHtml(parseMarkdownWithOptions(props.markdown, { gfm: true, html: true, math: false }),(markdown) => parseMarkdownWithOptions(markdown, { gfm: true, html: false, math: false }),);- return pullRequestDescriptionContent(document);+ return pullRequestDescriptionContent(document, splitPullRequestBody(props.markdown));}, [props.markdown]);- const gallery = useMemo(+ const gallery = useMemo<FilePreviewItem[]>(() =>- content.attachments.map((attachment) => ({- kind: "image" as const,- uri: attachment.uri,- name: new URL(attachment.uri).pathname.split("/").pop() || "Image",- })),- [content],+ content.attachments+ .filter((attachment) => attachment.kind === "image")+ .map((attachment) => {+ return {+ ...pullRequestImageSource(attachment.uri, mediaContext),+ name: new URL(attachment.uri).pathname.split("/").pop() || "Image",+ };+ }),+ [content, mediaContext],);const canCollapse = bodyHeight > COLLAPSED_HEIGHT;const collapsed = canCollapse && !expanded;return (<View className="gap-5"><View className="gap-3">- <Text className="text-base font-t3-semibold">Description</Text>+ <PullRequestSectionHeading>Description</PullRequestSectionHeading>{props.markdown.trim() ? (<View className="overflow-hidden"><View@@ -130,7 +139,7 @@ export function PullRequestDescription(props: {</View>{content.attachments.length ? (<View className="gap-3">- <Text className="text-base font-t3-semibold">Attachments</Text>+ <PullRequestSectionHeading>Attachments</PullRequestSectionHeading><ScrollViewhorizontalkeyboardShouldPersistTaps="always"@@ -138,50 +147,34 @@ export function PullRequestDescription(props: {showsHorizontalScrollIndicator={false}contentContainerStyle={{ gap: 12 }}>- {content.attachments.map((attachment) => (- <Pressable- key={attachment.uri}- accessibilityRole="imagebutton"- accessibilityLabel={`View attachment: ${attachment.caption}`}- accessibilityState={{ busy: openingUri === attachment.uri }}- disabled={preview !== null}- onPress={() =>- setPreview({- kind: "image",- uri: attachment.uri,- name: gallery.find((item) => item.uri === attachment.uri)?.name ?? "Image",- gallery,- })- }- className="gap-2 active:opacity-70"- style={{ width: 176 }}- >- <View className="overflow-hidden rounded-2xl border border-border-subtle bg-grouped-card">- <Image- source={{ uri: attachment.uri }}- style={{ width: 174, height: 112 }}- contentFit="contain"- cachePolicy="memory-disk"- />- {openingUri === attachment.uri ? (- <View- pointerEvents="none"- style={StyleSheet.absoluteFill}- className="items-center justify-center bg-black/30"- >- <ActivityIndicator color="white" />- </View>- ) : null}- </View>- <Text numberOfLines={1} className="text-xs text-foreground-muted">- {attachment.caption}- </Text>- </Pressable>- ))}+ {content.attachments.map((attachment) =>+ attachment.kind !== "image" ? (+ <PullRequestMedia+ key={attachment.uri}+ url={attachment.uri}+ kind={attachment.kind}+ caption={attachment.caption}+ compact+ />+ ) : (+ <PullRequestImageAttachment+ key={attachment.uri}+ url={attachment.uri}+ caption={attachment.caption}+ source={+ gallery[+ content.attachments+ .filter((item) => item.kind === "image")+ .indexOf(attachment)+ ]!+ }+ gallery={gallery}+ />+ ),+ )}</ScrollView></View>) : null}- <FilePreviewModal source={preview} onRequestClose={() => setPreview(null)} /></View>);}diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsxindex 81f389b8598..795f72bcd48 100644--- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx@@ -118,6 +118,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discussconst resolveLabel = thread?.isResolved ? "Unresolve" : "Resolve";return (<PullRequestMarkdownRepository+ params={params}value={detail.data?.provider === "github" ? detail.data.url : null}><KeyboardAvoidingView automaticOffset behavior="height" className="flex-1 bg-screen">diff --git a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsxindex ea0ab44b68b..d51671955a2 100644--- a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx@@ -1,3 +1,4 @@+import { PullRequestSectionHeading } from "./PullRequestSectionHeading";import { AnimatedLegendList } from "@legendapp/list/reanimated";import Animated from "react-native-reanimated";import { PR_ROW_LAYOUT, PR_ROW_ENTER, PR_ROW_EXIT } from "./pullRequestAnimations";@@ -167,15 +168,15 @@ export function usePullRequestFilesContent(props: {accessibilityState={{ busy: true }}className="min-h-17 flex-row items-center gap-2 py-3">- <View className="min-w-0 flex-1 gap-2">- <Text className="text-base font-t3-semibold">- {fileCount === undefined- ? "Changed files"- : `${fileCount} changed ${fileCount === 1 ? "file" : "files"}`}- </Text>- {filter.hideTestFiles ? (+ <View className="min-w-0 flex-1 gap-1">+ <PullRequestSectionHeading>Changed files</PullRequestSectionHeading>+ {fileCount !== undefined ? (+ <Text className="text-2xs text-foreground-muted">+ {fileCount} {fileCount === 1 ? "file" : "files"}+ </Text>+ ) : (<View className="h-2.5 w-28 rounded bg-subtle-strong" />- ) : null}+ )}</View>{summary?.additions !== undefined && summary.deletions !== undefined ? (<PullRequestDiffStats@@ -196,14 +197,14 @@ export function usePullRequestFilesContent(props: {<><View className="min-h-17 flex-row items-center gap-2 py-3"><View className="min-w-0 flex-1 gap-1">- <Text className="text-base font-t3-semibold">+ <PullRequestSectionHeading>Changed files</PullRequestSectionHeading>+ <Text className="text-2xs text-foreground-muted">{parsed.fileCount} {filter.hiddenCount ? "visible" : "changed"}{" "}{parsed.fileCount === 1 ? "file" : "files"}{viewed.supported? ` · ${parsed.files.filter((file) => viewed.isViewed(file.path)).length} viewed`: ""}- </Text>- <Text className="text-2xs text-foreground-muted">+ {" · "}{filter.hideTestFiles? `${filter.hiddenCount} test ${filter.hiddenCount === 1 ? "file" : "files"} hidden`: "Test files included"}diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsxindex bf5654eed4c..b18bdec364e 100644--- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx@@ -1,3 +1,13 @@+import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown";+import type { ReactNode } from "react";+import { View } from "react-native";+import { useProject } from "../../state/entities";+import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";+import {+ PullRequestMedia,+ PullRequestMediaContext,+ usePullRequestMediaUrl,+} from "./PullRequestMedia";import { videoMimeType } from "@t3tools/shared/video";import { createContext, useContext, useCallback, useMemo, useState } from "react";import { githubMarkdownLinks } from "@t3tools/shared/githubMarkdownLinks";@@ -16,7 +26,8 @@ import {} from "../../native/SelectableMarkdownText";import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";import { markdownImageSources } from "../../lib/markdownImageSources";-import { FilePreviewGallery } from "../../components/FilePreviewGallery";+import { FilePreviewGallery, useFilePreviewGallery } from "../../components/FilePreviewGallery";+import { pullRequestImageSource } from "./pullRequestMediaSource";import {FilePreviewModal,type FilePreviewSource,@@ -25,7 +36,78 @@ import {import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage";import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";-export const PullRequestMarkdownRepository = createContext<string | null>(null);+const RepositoryContext = createContext<string | null>(null);++export function PullRequestMarkdownRepository(props: {+ readonly value: string | null;+ readonly params: PullRequestParams;+ readonly children: ReactNode;+}) {+ const target = pullRequestTarget(props.params);+ const project = useProject({+ environmentId: target.environmentId,+ projectId: target.input.projectId,+ });+ const cwd = project?.workspaceRoot;+ const media = useMemo(+ () => (cwd ? { environmentId: target.environmentId, cwd } : null),+ [target.environmentId, cwd],+ );+ return (+ <RepositoryContext value={props.value}>+ <PullRequestMediaContext value={media}>{props.children}</PullRequestMediaContext>+ </RepositoryContext>+ );+}++function MarkdownImage(props: {+ readonly href: string;+ readonly alt: string | null;+ readonly onPreview: (source: FilePreviewSource) => void;+}) {+ const media = usePullRequestMediaUrl(props.href);+ const context = useContext(PullRequestMediaContext);+ const withGallery = useFilePreviewGallery();+ return (+ <ThreadMarkdownImageView+ uri={media.uri}+ sourceKey={props.href}+ unavailable={media.unavailable || !/^https?:\/\//i.test(props.href)}+ alt={props.alt}+ onPressPreview={(source) =>+ props.onPreview(+ withGallery({+ ...pullRequestImageSource(props.href, context),+ name: source.name,+ sourceIdentifier: source.sourceIdentifier,+ }),+ )+ }+ />+ );+}++export function PullRequestMarkdown(props: {+ readonly markdown: string;+ readonly imageGroupMarkdown?: string;+}) {+ const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]);+ return (+ <View style={{ gap: 12 }}>+ {segments.map((segment) =>+ segment.kind === "markdown" ? (+ <PullRequestMarkdownContent+ key={segment.id}+ markdown={segment.text}+ imageGroupMarkdown={props.imageGroupMarkdown ?? props.markdown}+ />+ ) : (+ <PullRequestMedia key={segment.id} url={segment.url} kind={segment.media} />+ ),+ )}+ </View>+ );+}function renderLink({ href, children }: CustomRendererProps,@@ -61,11 +143,12 @@ function renderHtmlBlock() : null;}-export function PullRequestMarkdown(props: {+function PullRequestMarkdownContent(props: {readonly markdown: string;readonly imageGroupMarkdown?: string;}) {- const repositoryUrl = useContext(PullRequestMarkdownRepository);+ const repositoryUrl = useContext(RepositoryContext);+ const mediaContext = useContext(PullRequestMediaContext);const markdown = useMemo(() => githubMarkdownLinks(props.markdown, repositoryUrl),[props.markdown, repositoryUrl],@@ -85,20 +168,12 @@ export function PullRequestMarkdown(props: {/^https?:\/\//i.test(uri) &&videoMimeType({ name: uri.split(/[?#]/)[0] ?? uri, mimeType: "" }) === null,)- .map((uri) => ({ kind: "image", uri })),- [props.markdown, props.imageGroupMarkdown],+ .map((uri) => pullRequestImageSource(uri, mediaContext)),+ [props.markdown, props.imageGroupMarkdown, mediaContext],);const [preview, setPreview] = useState<FilePreviewSource | null>(null);const renderImage = useCallback<MarkdownImageRenderer>(- (image) => (- <ThreadMarkdownImageView- uri={/^https?:\/\//i.test(image.href) ? image.href : null}- sourceKey={image.href}- unavailable={!/^https?:\/\//i.test(image.href)}- alt={image.alt}- onPressPreview={setPreview}- />- ),+ (image) => <MarkdownImage href={image.href} alt={image.alt} onPreview={setPreview} />,[],);const styles = useMarkdownPreviewStyles(renderImage);diff --git a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsxnew file mode 100644index 00000000000..3ff9a2a82ec--- /dev/null+++ b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx@@ -0,0 +1,142 @@+import { createContext, useContext, useMemo, useState } from "react";+import { pullRequestMediaSource, pullRequestImageSource } from "./pullRequestMediaSource";+import { useFilePreviewGallery } from "../../components/FilePreviewGallery";+import type { AssetResource, EnvironmentId } from "@t3tools/contracts";+import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";+import { videoMimeType } from "@t3tools/shared/video";+import { Pressable, View } from "react-native";+import { Image } from "expo-image";+import { AppText } from "../../components/AppText";+import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets";+import { MediaVideoPlayer } from "../../components/MediaVideoPlayer";+import { VideoAttachmentTile } from "../../components/VideoAttachmentTile";+import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";+import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage";+import {+ FilePreviewModal,+ type FilePreviewSource,+ type FilePreviewItem,+} from "../../components/FilePreviewModal";++export const PullRequestMediaContext = createContext<{+ readonly environmentId: EnvironmentId;+ readonly cwd: string;+} | null>(null);++/** Only GitHub-hosted media needs the environment's authenticated asset path. */+export function usePullRequestMediaUrl(url: string) {+ const context = useContext(PullRequestMediaContext);+ const fetchUrl = githubMediaFetchUrl(url);+ const resource = useMemo<AssetResource | null>(+ () => (context && fetchUrl ? { _tag: "github-media", cwd: context.cwd, url: fetchUrl } : null),+ [context, fetchUrl],+ );+ const asset = useAssetUrlState(context?.environmentId ?? null, resource);+ const refresh = useRefreshAssetUrl(context?.environmentId ?? null, resource);+ return {+ uri: asset._tag === "Success" ? asset.url : resource ? null : url,+ unavailable: resource !== null && asset._tag === "Failure",+ source: pullRequestMediaSource(url, context),+ resolvePlaybackUri: resource ? async () => (await refresh()) ?? null : undefined,+ };+}++export function PullRequestMedia(props: {+ readonly url: string;+ readonly kind: "image" | "video" | "unknown";+ readonly caption?: string;+ readonly compact?: boolean;+}) {+ const media = usePullRequestMediaUrl(props.url);+ const context = useContext(PullRequestMediaContext);+ const withGallery = useFilePreviewGallery();+ const [image, setImage] = useState<FilePreviewSource | null>(null);+ const [video, setVideo] = useState<VideoPreviewSource | null>(null);+ const name = props.caption || new URL(props.url).pathname.split("/").pop() || "Attachment";+ if (props.kind === "image")+ return (+ <>+ <ThreadMarkdownImageView+ uri={media.uri}+ sourceKey={props.url}+ unavailable={media.unavailable}+ alt={name}+ onPressPreview={(source) =>+ setImage(+ withGallery({+ ...pullRequestImageSource(props.url, context),+ name,+ sourceIdentifier: source.sourceIdentifier,+ }),+ )+ }+ />+ <FilePreviewModal source={image} onRequestClose={() => setImage(null)} />+ </>+ );+ return (+ <View style={props.compact ? { width: 176 } : undefined}>+ {props.compact ? (+ <VideoAttachmentTile+ name={name}+ sourceIdentifier={props.url}+ thumbnailSource={media.uri}+ style={{ width: 176, height: 112, borderRadius: 16 }}+ onPress={() =>+ setVideo({+ type: "media",+ ...media.source,+ name,+ mimeType:+ videoMimeType({ name: props.url.split(/[?#]/)[0] ?? props.url, mimeType: "" }) ??+ "video/mp4",+ })+ }+ />+ ) : (+ <MediaVideoPlayer+ uri={media.uri}+ unavailable={media.unavailable}+ name={name}+ thumbnailKey={props.url}+ resolvePlaybackUri={media.resolvePlaybackUri}+ />+ )}+ <VideoPreviewModal source={video} onRequestClose={() => setVideo(null)} />+ </View>+ );+}++export function PullRequestImageAttachment(props: {+ readonly url: string;+ readonly caption: string;+ readonly source: FilePreviewItem;+ readonly gallery: readonly FilePreviewItem[];+}) {+ const media = usePullRequestMediaUrl(props.url);+ const [preview, setPreview] = useState<FilePreviewSource | null>(null);+ return (+ <>+ <Pressable+ accessibilityRole="imagebutton"+ accessibilityLabel={`View attachment: ${props.caption}`}+ onPress={() => setPreview({ ...props.source, gallery: props.gallery })}+ className="gap-2 active:opacity-70"+ style={{ width: 176 }}+ >+ <View className="overflow-hidden rounded-2xl border border-border-subtle bg-grouped-card">+ <Image+ source={media.uri ? { uri: media.uri } : null}+ style={{ width: 174, height: 112 }}+ contentFit="contain"+ cachePolicy="memory-disk"+ />+ </View>+ <AppText numberOfLines={1} className="text-xs text-foreground-muted">+ {props.caption}+ </AppText>+ </Pressable>+ <FilePreviewModal source={preview} onRequestClose={() => setPreview(null)} />+ </>+ );+}diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsxindex 865541fbca0..5ead045fa2b 100644--- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx@@ -54,9 +54,12 @@ export function PullRequestMergeControls(props: {hasStack: stack.stack !== null,isFresh: stack.isFresh,});- const checkingStack = stack.supportsStackActions && !stack.isFresh && !stack.error;+ const checkingStack =+ permissions.connected && stack.supportsStackActions && !stack.isFresh && !stack.error;const reason =- mergeUnavailableReason(pr, permissions.canWrite) ??+ (!permissions.connected+ ? "Reconnect to merge."+ : mergeUnavailableReason(pr, permissions.canWrite)) ??(stack.stack? !stack.supportsStackActions? "This environment can display stacks but cannot merge them."@@ -185,7 +188,7 @@ export function PullRequestMergeControls(props: {<TextclassName={`shrink text-center text-sm font-t3-semibold ${canMerge ? "text-screen" : "text-foreground-muted"}`}>- {busy ? "Working…" : label}+ {busy ? "Working…" : !permissions.connected ? "Reconnect to merge" : label}</Text></Pressable>{methods.length > 0 || canAutoMerge ? (@@ -230,7 +233,8 @@ export function PullRequestMergeControls(props: {</ControlPillMenu>) : null}</View>- {reason &&+ {permissions.connected &&+ reason &&reason !== MERGE_CONFLICT_REASON &&reason !== "Checking stack membership…" &&!(checkingStack && reason === "Refresh the stack before merging.") ? (diff --git a/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx b/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsxindex 8b5b81ce404..7e6e4f490ae 100644--- a/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx@@ -1,3 +1,4 @@+import { PullRequestSectionHeading } from "./PullRequestSectionHeading";import type { PullRequestListEntry } from "@t3tools/contracts";import { View } from "react-native";import { AppText as Text } from "../../components/AppText";@@ -97,7 +98,7 @@ export function PullRequestOverviewLoading({</View>) : null}<View className="gap-3">- <Text className="text-base font-t3-semibold">Description</Text>+ <PullRequestSectionHeading>Description</PullRequestSectionHeading><View className="gap-3 py-1"><View className="h-4 w-full rounded bg-subtle-strong" /><View className="h-4 w-full rounded bg-subtle-strong" />diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsxindex 924bbaa0b34..597cf63b910 100644--- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx@@ -1,3 +1,4 @@+import { usePullRequestConnected } from "./usePullRequestConnected";import { useAtomValue } from "@effect/atom-react";import { useNavigation, type StaticScreenProps } from "@react-navigation/native";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";@@ -60,7 +61,9 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequconst canWrite = useAtomValue(composerPullRequests.requestReviewers.permissionAtom(target.environmentId),);+ const connected = usePullRequestConnected(route.params.environmentId);const allowed =+ connected &&canWrite &&pr?.state === "open" &&pr.capabilities.reviewers.request &&diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsxindex 267b32e07a5..cca2435e5b2 100644--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx@@ -62,6 +62,7 @@ import { SegmentedControl } from "../../components/SegmentedControl";import { SymbolView } from "../../components/AppSymbol";import { relativeTime } from "../../lib/time";import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";+import { usePullRequestConnected } from "./usePullRequestConnected";import { composerPullRequests } from "../../state/pull-requests";import { useEnvironmentQuery } from "../../state/query";import { usePullToRefresh } from "../../state/use-pull-to-refresh";@@ -272,6 +273,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestPconst navigation = useNavigation();const insets = useSafeAreaInsets();const params = route.params;+ const connected = usePullRequestConnected(params.environmentId);const [section, setSection] = useState<"overview" | "activity" | "guide">("overview");// Keep each tab's native list and measured rows alive when it is hidden.const requestedSection = useRef(section);@@ -350,18 +352,23 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP}};return (- <PullRequestMarkdownRepository value={pr?.provider === "github" ? pr.url : null}>+ <PullRequestMarkdownRepository+ params={params}+ value={pr?.provider === "github" ? pr.url : null}+ ><View className="flex-1 bg-screen"><NativeStackScreenOptionsoptions={{title: `#${params.number}`,headerTitle: `#${params.number}`,- unstable_headerSubtitle: params.repository,+ unstable_headerSubtitle: connected+ ? params.repository+ : `${params.repository} · Offline`,}}/>{Platform.OS === "android" ? (<AndroidScreenHeader- title={`#${params.number}`}+ title={`#${params.number}${connected ? "" : " · Offline"}`}onBack={() => navigation.goBack()}actions={[...(permissions.verdicts.lengthdiff --git a/apps/mobile/src/features/pull-requests/PullRequestSectionHeading.tsx b/apps/mobile/src/features/pull-requests/PullRequestSectionHeading.tsxnew file mode 100644index 00000000000..8fd85199a55--- /dev/null+++ b/apps/mobile/src/features/pull-requests/PullRequestSectionHeading.tsx@@ -0,0 +1,6 @@+import type { ReactNode } from "react";+import { AppText } from "../../components/AppText";++export function PullRequestSectionHeading({ children }: { readonly children: ReactNode }) {+ return <AppText className="text-base font-t3-semibold">{children}</AppText>;+}diff --git a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsxindex c331b6b7d15..c39cea3187a 100644--- a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx@@ -1,3 +1,4 @@+import { usePullRequestConnected } from "./usePullRequestConnected";import { useAtomValue } from "@effect/atom-react";import { useNavigation } from "@react-navigation/native";import type { PullRequestAction, PullRequestDetail } from "@t3tools/contracts";@@ -237,7 +238,9 @@ export function PullRequestReviewersRow(props: RowProps) {pullRequestTarget(props.params).environmentId,),);+ const connected = usePullRequestConnected(props.params.environmentId);const canRequest =+ connected &&canWrite &&props.pr.state === "open" &&props.pr.capabilities.reviewers.request &&diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsxindex 53ed9bbef2f..f32a3635726 100644--- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx@@ -99,7 +99,6 @@ export function PullRequestsScreen() {environments.filter((environment) =>- environment.connectionState === "connected" &&configs.get(environment.environmentId)?.environment.capabilities.pullRequests ===true &&(environmentId === null || environment.environmentId === environmentId) &&@@ -121,8 +120,15 @@ export function PullRequestsScreen() {[environments, environmentId, configs, controls, query],);const result = usePullRequestList(targets);+ const connectedTargets = targets.filter((target) =>+ environments.some(+ (environment) =>+ environment.environmentId === target.environmentId &&+ environment.connectionState === "connected",+ ),+ );const { actions, select, busyKey } = usePullRequestListActions(- targets.map((target) => target.environmentId),+ connectedTargets.map((target) => target.environmentId),result.updateEntry,);const selectedKey = primaryColumn?.selectedPullRequestKey;@@ -309,7 +315,7 @@ export function PullRequestsScreen() {) : undefined}ListEmptyComponent={- result.isPending ? (+ result.isPending && connectedTargets.length > 0 ? (<View className="items-center py-12"><ActivityIndicator colorClassName="accent-icon" /></View>@@ -319,17 +325,21 @@ export function PullRequestsScreen() {title={result.error? "Couldn't load pull requests"- : targets.length- ? query- ? "No results"- : "No matching pull requests"- : "Connect an environment"+ : targets.length && connectedTargets.length === 0+ ? "Environment offline"+ : targets.length+ ? query+ ? "No results"+ : "No matching pull requests"+ : "Connect an environment"}detail={result.error ??- (targets.length- ? "Pull requests from the selected environments' projects appear here."- : "Add an environment in Settings to browse its pull requests.")+ (targets.length && connectedTargets.length === 0+ ? "Reconnect to load pull requests that aren't saved on this device."+ : targets.length+ ? "Pull requests from the selected environments' projects appear here."+ : "Add an environment in Settings to browse its pull requests.")}variant="plain"/>diff --git a/apps/mobile/src/features/pull-requests/guide/GuideNotice.tsx b/apps/mobile/src/features/pull-requests/guide/GuideNotice.tsxnew file mode 100644index 00000000000..9701a496904--- /dev/null+++ b/apps/mobile/src/features/pull-requests/guide/GuideNotice.tsx@@ -0,0 +1,85 @@+import { Pressable, View } from "react-native";+import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";+import { AppText as Text } from "../../../components/AppText";+import { SymbolView } from "../../../components/AppSymbol";+import { PR_ROW_EXIT, PR_ROW_LAYOUT } from "../pullRequestAnimations";+import { guideNoticeState } from "./reviewGuideState";+import type { useReviewGuide } from "./useReviewGuide";++const NOTICE_ENTER = FadeIn.delay(180).duration(120).reduceMotion(ReduceMotion.System);++/** Keep the action in one place as loading, writing, and retry states change. */+export function GuideNotice({ state }: { readonly state: ReturnType<typeof useReviewGuide> }) {+ const notice = guideNoticeState(state);+ if (notice.kind === "ready") return null;+ const compact = state.data?.guide != null;+ const failed = notice.kind === "failed" || notice.kind === "unavailable";+ const busy = notice.kind === "loading" || notice.kind === "writing";+ return (+ <Animated.View+ layout={PR_ROW_LAYOUT}+ entering={compact ? NOTICE_ENTER : undefined}+ exiting={PR_ROW_EXIT}+ className={+ compact ? "mb-5 rounded-2xl bg-grouped-card p-4" : "rounded-2xl bg-grouped-card p-5"+ }+ accessibilityLiveRegion="polite"+ accessibilityState={{ busy }}+ >+ <View className="flex-row items-center gap-3">+ <SymbolView+ name={failed ? "exclamationmark.circle" : busy ? "clock" : "list.number"}+ size={19}+ tintColorClassName={failed ? "accent-danger-foreground" : "accent-icon-muted"}+ />+ <Text className="text-base font-t3-semibold">+ {compact ? notice.title : "Review guide"}+ </Text>+ </View>+ <View style={compact ? undefined : { minHeight: 100 }} className="pt-3 pb-4">+ <Text className="text-sm leading-6 text-foreground-muted">{notice.description}</Text>+ </View>+ <View className="min-h-12 flex-row items-center justify-between gap-3">+ {state.canWrite || busy || notice.kind === "unavailable" ? (+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ disabled: busy, busy }}+ disabled={busy}+ style={{ width: 152 }}+ className={+ compact+ ? "min-h-12 items-center justify-center rounded-full bg-secondary px-4 active:opacity-70"+ : "min-h-12 items-center justify-center rounded-full bg-foreground px-4 active:opacity-70"+ }+ onPress={() => (notice.kind === "unavailable" ? state.refresh() : void state.write())}+ >+ <Text+ className={+ compact+ ? "text-center font-t3-medium text-secondary-foreground"+ : "text-center font-t3-medium text-screen"+ }+ >+ {notice.action}+ </Text>+ </Pressable>+ ) : (+ <Text className="text-xs text-foreground-muted">+ {notice.kind === "failed"+ ? "Reconnect or ask someone with write access to retry."+ : "Writing a guide requires a connection and write access."}+ </Text>+ )}+ {notice.kind === "writing" && state.data?.run?._tag === "Running" ? (+ <Text className="shrink text-xs text-foreground-muted">+ Started{" "}+ {new Date(state.data.run.startedAt).toLocaleTimeString([], {+ hour: "2-digit",+ minute: "2-digit",+ })}+ </Text>+ ) : null}+ </View>+ </Animated.View>+ );+}diff --git a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsxindex 1bf9fc02c2d..cb280ea4b78 100644--- a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx+++ b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx@@ -13,7 +13,6 @@ import {import { SymbolView } from "../../../components/AppSymbol";import { GuideOutline } from "./GuideOutline";import { AppText as Text } from "../../../components/AppText";-import { MaterialButton } from "../../../components/MaterialButton";import { ScreenScrollView } from "../../../components/ScreenScrollView";import { ControlPillMenu } from "../../../components/ControlPillMenu";import { MaterialIconButton } from "../../../components/MaterialIconButton";@@ -24,6 +23,9 @@ import { PullRequestMarkdown, PullRequestMarkdownRepository } from "../PullRequeimport { usePullRequestDiff, type PullRequestParams } from "../usePullRequestDiff";import { ReviewGuideExcerpt } from "./ReviewGuideExcerpt";import { reviewGuideState } from "./reviewGuideState";+import { GuideNotice } from "./GuideNotice";+import Animated from "react-native-reanimated";+import { PR_ROW_ENTER, PR_ROW_EXIT, PR_ROW_LAYOUT } from "../pullRequestAnimations";import { useEnvironmentQuery } from "../../../state/query";import { composerPullRequests } from "../../../state/pull-requests";import { usePullRequestPermissions } from "../usePullRequestPermissions";@@ -44,111 +46,47 @@ const attentionLabels = {accessibility: "An accessibility call",};-function GuideNotice({ state }: { readonly state: ReturnType<typeof useReviewGuide> }) {- const { guide, stale, failure } = reviewGuideState(state.data);- const error = state.startError ?? failure ?? state.error;- const label = state.running- ? guide- ? "Rewriting review guide"- : "Writing review guide"- : error- ? "Could not write guide"- : stale- ? "Guide is out of date"- : "No review guide yet";- if (guide && !stale && !error && !state.running) return null;- return (- <View- className={guide ? "gap-3 border-l-2 border-border pl-4 py-1" : "gap-4 py-4"}- accessibilityLiveRegion="polite"- >- <View className="flex-row items-center gap-2">- <SymbolView- name={- state.running- ? "clock"- : error- ? "exclamationmark.circle"- : stale- ? "arrow.clockwise"- : "list.number"- }- size={20}- tintColorClassName={- error- ? "accent-danger-foreground"- : stale- ? "accent-warning-foreground"- : "accent-icon-muted"- }- />- <Text className={guide ? "text-base font-t3-semibold" : "text-xl font-t3-semibold"}>- {label}- </Text>- </View>- <Text className="text-sm leading-6 text-foreground-muted">- {error ??- (state.running- ? "An agent is reading the change. You can leave this screen and return when it’s ready."- : stale- ? "There are new changes since this guide was written. Rewrite it to see the latest code."- : "Walk through the important code in order, with notes on what changed and where to look closely.")}- </Text>- {state.running ? (- <Text className="text-xs text-foreground-muted">- {state.data?.run?._tag === "Running"- ? `Started at ${new Date(state.data.run.startedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`- : "Starting the guide…"}- </Text>- ) : state.canWrite ? (- <MaterialButton- label={error ? "Try again" : guide ? "Rewrite guide" : "Write guide"}- tone={guide ? "secondary" : "contrast"}- onPress={() => void state.write()}- />- ) : null}- </View>- );-}-export function PullRequestGuideContent({ params }: { readonly params: PullRequestParams }) {const navigation = useNavigation();const state = useReviewGuide(params);const { guide, stale } = reviewGuideState(state.data);return (- <View className="w-full max-w-[760px] self-center gap-5">+ <Animated.View layout={PR_ROW_LAYOUT} className="w-full max-w-[760px] self-center">{!state.enabled ? (<Text>Review guides are disabled for this server.</Text>) : (<>- {state.isPending && !state.data ? (- <Text className="text-foreground-muted">Loading review guide…</Text>- ) : (- <GuideNotice state={state} />- )}+ <GuideNotice state={state} />{guide ? (- <GuideOutline- guide={guide}- onOpen={(position) =>- navigation.dispatch(- StackActions.push("PullRequestGuideStop", {- ...params,- position,- guideHeadSha: guide.headSha,- guideGeneratedAt: guide.generatedAt,- }),- )- }- onRewrite={- state.canWrite && !state.running && !stale && !state.startError && !state.error- ? () => void state.write()- : undefined- }- />+ <Animated.View+ key={`outline:${guide.headSha}:${guide.generatedAt}`}+ layout={PR_ROW_LAYOUT}+ entering={PR_ROW_ENTER}+ exiting={PR_ROW_EXIT}+ >+ <GuideOutline+ guide={guide}+ onOpen={(position) =>+ navigation.dispatch(+ StackActions.push("PullRequestGuideStop", {+ ...params,+ position,+ guideHeadSha: guide.headSha,+ guideGeneratedAt: guide.generatedAt,+ }),+ )+ }+ onRewrite={+ state.canWrite && !state.running && !stale && !state.startError && !state.error+ ? () => void state.write()+ : undefined+ }+ />+ </Animated.View>) : null}</>)}- </View>+ </Animated.View>);}@@ -240,6 +178,7 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps<GuideSto</NativeHeaderToolbar.Menu></NativeHeaderToolbar><PullRequestMarkdownRepository+ params={route.params}value={`https://${route.params.host ?? "github.com"}/${route.params.repository}`}><ScreenScrollViewdiff --git a/apps/mobile/src/features/pull-requests/guide/reviewGuideState.test.ts b/apps/mobile/src/features/pull-requests/guide/reviewGuideState.test.tsindex 857a2bd3f2f..228c3ae1b66 100644--- a/apps/mobile/src/features/pull-requests/guide/reviewGuideState.test.ts+++ b/apps/mobile/src/features/pull-requests/guide/reviewGuideState.test.ts@@ -4,7 +4,7 @@ import {ProviderInstanceId,type PullRequestReviewGuideResult,} from "@t3tools/contracts";-import { reviewGuideState } from "./reviewGuideState";+import { guideNoticeState, reviewGuideState } from "./reviewGuideState";const guide: NonNullable<PullRequestReviewGuideResult["guide"]> = {headSha: "old-head",@@ -46,3 +46,58 @@ describe("mobile review guide state", () => {});});});++const view = {+ data: null,+ isPending: false,+ running: false,+ startError: null,+ error: null,+};++describe("guide notice transitions", () => {+ it("does not flash an empty guide before the first response", () => {+ expect(guideNoticeState({ ...view, isPending: true }).kind).toBe("loading");+ expect(+ guideNoticeState({ ...view, data: { guide: null, run: null, currentHeadSha: "head" } }).kind,+ ).toBe("empty");+ });++ it("keeps cached guides visible while refreshing", () => {+ expect(+ guideNoticeState({+ ...view,+ isPending: true,+ data: { guide, run: null, currentHeadSha: guide.headSha },+ }).kind,+ ).toBe("ready");+ });++ it("hides the previous failure as soon as a retry starts", () => {+ const data = {+ guide: null,+ currentHeadSha: "head",+ run: {+ _tag: "Failed" as const,+ headSha: "head",+ failedAt: guide.generatedAt,+ detail: "Writer disconnected",+ },+ };+ expect(guideNoticeState({ ...view, data }).kind).toBe("failed");+ expect(guideNoticeState({ ...view, data, running: true }).kind).toBe("writing");+ });++ it("keeps a stale guide readable through rewriting and completion", () => {+ const data = { guide, currentHeadSha: "head", run: null };+ expect(guideNoticeState({ ...view, data }).kind).toBe("stale");+ expect(guideNoticeState({ ...view, data, running: true }).kind).toBe("writing");+ expect(+ guideNoticeState({ ...view, data: { ...data, guide: { ...guide, headSha: "head" } } }).kind,+ ).toBe("ready");+ });+});++it("distinguishes a failed read from a failed writer", () => {+ expect(guideNoticeState({ ...view, error: "Connection lost" }).kind).toBe("unavailable");+});diff --git a/apps/mobile/src/features/pull-requests/guide/reviewGuideState.ts b/apps/mobile/src/features/pull-requests/guide/reviewGuideState.tsindex da8bf7315e9..702cc8bd4ee 100644--- a/apps/mobile/src/features/pull-requests/guide/reviewGuideState.ts+++ b/apps/mobile/src/features/pull-requests/guide/reviewGuideState.ts@@ -13,3 +13,64 @@ export function reviewGuideState(data: PullRequestReviewGuideResult | null) {: null,};}++/** A pending refresh must not hide cached content, or a new run reveal an old failure. */+export function guideNoticeState(state: {+ readonly data: PullRequestReviewGuideResult | null;+ readonly isPending: boolean;+ readonly running: boolean;+ readonly startError: string | null;+ readonly error: string | null;+}) {+ const { guide, stale, failure } = reviewGuideState(state.data);+ if (state.running) {+ return {+ kind: "writing" as const,+ title: "Rewriting guide",+ description: guide+ ? "You can keep reading this guide while the agent writes the update."+ : "An agent is reading the change and writing the tour. You can leave and come back when it’s ready.",+ action: guide ? "Rewriting…" : "Writing guide…",+ };+ }+ const error = state.startError ?? failure;+ if (error) {+ return {+ kind: "failed" as const,+ title: "Could not write guide",+ description: error,+ action: "Try again",+ };+ }+ if (state.error) {+ return {+ kind: "unavailable" as const,+ title: "Could not refresh guide",+ description: state.error,+ action: "Try again",+ };+ }+ if (!state.data) {+ return {+ kind: "loading" as const,+ title: "Review guide",+ description: "Checking for a saved guide…",+ action: "Loading guide…",+ };+ }+ if (stale) {+ return {+ kind: "stale" as const,+ title: "New changes since this guide",+ description: "You can read the previous guide, or rewrite it for the latest changes.",+ action: "Rewrite guide",+ };+ }+ return {+ kind: guide ? ("ready" as const) : ("empty" as const),+ title: "Review guide",+ description:+ "Get a tour of the change, with code excerpts and notes on what needs a closer look.",+ action: "Write guide",+ };+}diff --git a/apps/mobile/src/features/pull-requests/guide/useReviewGuide.ts b/apps/mobile/src/features/pull-requests/guide/useReviewGuide.tsindex f6850109c4c..e915804c651 100644--- a/apps/mobile/src/features/pull-requests/guide/useReviewGuide.ts+++ b/apps/mobile/src/features/pull-requests/guide/useReviewGuide.ts@@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react";import { useFocusEffect } from "@react-navigation/native";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import { useCallback, useRef, useState } from "react";+import { usePullRequestConnected } from "../usePullRequestConnected";import { composerPullRequests } from "../../../state/pull-requests";import { useEnvironmentQuery } from "../../../state/query";import { serverEnvironment } from "../../../state/server";@@ -19,9 +20,11 @@ export function useReviewGuide(params: PullRequestParams) {const target = pullRequestTarget(params);const enabled = useReviewGuidesEnabled(params);const query = useEnvironmentQuery(enabled ? composerPullRequests.reviewGuide(target) : null);- const canWrite = useAtomValue(+ const connected = usePullRequestConnected(target.environmentId);+ const permitted = useAtomValue(composerPullRequests.generateReviewGuide.permissionAtom(target.environmentId),);+ const canWrite = connected && permitted;const generate = useAtomCommand(composerPullRequests.generateReviewGuide, {reportFailure: false,});@@ -49,8 +52,6 @@ export function useReviewGuide(params: PullRequestParams) {if (result._tag === "Failure") {const cause = squashAtomCommandFailure(result);setError(cause instanceof Error ? cause.message : "Could not start the review guide.");- } else {- refresh();}} finally {pending.current = false;diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescription.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescription.test.tsindex 5247ca1d5ff..f7e0c1ad4b2 100644--- a/apps/mobile/src/features/pull-requests/pullRequestDescription.test.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestDescription.test.ts@@ -15,8 +15,8 @@ describe("PR description overview", () => {],});expect(result.attachments).toEqual([- { uri: "https://example.com/before.png", caption: "Before" },- { uri: "https://example.com/after.png", caption: "After" },+ { uri: "https://example.com/before.png", caption: "Before", kind: "image" },+ { uri: "https://example.com/after.png", caption: "After", kind: "image" },]);expect(result.preview).toContain("Fixes reconnects.");expect(result.preview).not.toContain("Duplicate");diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.tsnew file mode 100644index 00000000000..c69faff2cec--- /dev/null+++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vite-plus/test";+import type { MarkdownNode } from "react-native-nitro-markdown/headless";+import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown";+import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent";++describe("PR attachments", () => {+ it("combines embedded images and detected media without duplicate URLs", () => {+ const uri = "https://drop.example.com/shot.png";+ const document = {+ type: "document",+ children: [+ { type: "image", href: uri, alt: "Screenshot" },+ { type: "image", href: uri, alt: "Duplicate" },+ ],+ } as MarkdownNode;+ const media = splitPullRequestBody(+ `${uri}\n\nhttps://drop.example.com/demo.mp4\n\nhttps://github.com/user-attachments/assets/123-abc`,+ );+ expect(pullRequestDescriptionContent(document, media).attachments).toEqual([+ { uri, caption: "Screenshot", kind: "image" },+ { uri: "https://drop.example.com/demo.mp4", caption: "Video", kind: "video" },+ {+ uri: "https://github.com/user-attachments/assets/123-abc",+ caption: "Video",+ kind: "video",+ },+ ]);+ });++ it("does not collect ordinary links or media examples in code", () => {+ const media = splitPullRequestBody(+ "https://example.com/docs\n\n```\nhttps://drop.example.com/demo.mp4\n```",+ );+ expect(+ pullRequestDescriptionContent({ type: "document" } as MarkdownNode, media).attachments,+ ).toEqual([]);+ });+});diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.tsindex 709c58997b8..76e394ad2c4 100644--- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts@@ -1,13 +1,24 @@+import type { PullRequestBodySegment } from "@t3tools/client-runtime/pull-request-markdown";import type { MarkdownNode } from "react-native-nitro-markdown/headless";/** Read media from the parsed document so code examples never become attachments. */-export function pullRequestDescriptionContent(document: MarkdownNode) {- const attachments = new Map<string, { readonly uri: string; readonly caption: string }>();+export function pullRequestDescriptionContent(+ document: MarkdownNode,+ media: readonly PullRequestBodySegment[] = [],+) {+ const attachments = new Map<+ string,+ { readonly uri: string; readonly caption: string; readonly kind: "image" | "video" | "unknown" }+ >();const text: string[] = [];const visit = (node: MarkdownNode) => {if (node.type === "image") {if (node.href && /^https?:\/\//i.test(node.href) && !attachments.has(node.href)) {- attachments.set(node.href, { uri: node.href, caption: node.alt || node.title || "Image" });+ attachments.set(node.href, {+ uri: node.href,+ caption: node.alt || node.title || "Image",+ kind: "image",+ });}return;}@@ -18,5 +29,15 @@ export function pullRequestDescriptionContent(document: MarkdownNode) {if (node.type === "soft_break" || node.type === "line_break") text.push(" ");};visit(document);+ for (const segment of media) {+ if (segment.kind === "attachment" && !attachments.has(segment.url)) {+ const name = new URL(segment.url).pathname.split("/").pop();+ attachments.set(segment.url, {+ uri: segment.url,+ caption: segment.media === "video" ? "Video" : name || "Image",+ kind: segment.media,+ });+ }+ }return { preview: text.join("").trim(), attachments: [...attachments.values()] };}diff --git a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.tsnew file mode 100644index 00000000000..b5e90f7dedd--- /dev/null+++ b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vite-plus/test";+import { EnvironmentId } from "@t3tools/contracts";+import { filePreviewGallery } from "../../lib/filePreviewGallery";+import { mediaVideoPreviewUri, mediaVideoThumbnailKey } from "../../lib/videoPreviewSource";+import { pullRequestImageSource, pullRequestMediaSource } from "./pullRequestMediaSource";++const location = { environmentId: EnvironmentId.make("test"), cwd: "/repo" };+const url = "https://github.com/user-attachments/assets/abc-123";++describe("PR media previews", () => {+ it("keeps a video resource pending until resolved and accepts refreshed capabilities", () => {+ const source = {+ type: "media" as const,+ name: "Video",+ mimeType: "video/mp4",+ ...pullRequestMediaSource(url, location),+ };+ expect(mediaVideoPreviewUri(source, null)).toBeNull();+ expect(mediaVideoPreviewUri(source, "https://signed/first")).toBe("https://signed/first");+ expect(mediaVideoPreviewUri(source, "https://signed/renewed")).toBe("https://signed/renewed");+ expect(mediaVideoThumbnailKey(source)).toContain("github-media");+ });++ it("keeps every gallery image resolvable and the tapped image appears only once", () => {+ const first = pullRequestImageSource(url, location);+ const second = pullRequestImageSource(`${url}-second`, location);+ const selected = { ...second, sourceIdentifier: "tapped" };+ const gallery = filePreviewGallery(selected, [first, second]);+ expect(gallery).toEqual([first, selected]);+ expect(gallery.every((item) => "resource" in item)).toBe(true);+ });++ it("leaves custom-domain media as direct URLs", () => {+ const external = "https://drop.example/file.mp4";+ expect(pullRequestMediaSource(external, location)).toEqual({ uri: external });+ });+});diff --git a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.tsnew file mode 100644index 00000000000..e45cd548bcc--- /dev/null+++ b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts@@ -0,0 +1,26 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";+import type { FilePreviewItem } from "../../components/FilePreviewModal.types";++export interface PullRequestMediaLocation {+ readonly environmentId: EnvironmentId;+ readonly cwd: string;+}++/** Keep the original resource identity so previewers can resolve and renew its capability. */+export function pullRequestMediaSource(url: string, location: PullRequestMediaLocation | null) {+ const fetchUrl = githubMediaFetchUrl(url);+ return location && fetchUrl+ ? {+ environmentId: location.environmentId,+ resource: { _tag: "github-media" as const, cwd: location.cwd, url: fetchUrl },+ }+ : { uri: url };+}++export function pullRequestImageSource(+ url: string,+ location: PullRequestMediaLocation | null,+): FilePreviewItem {+ return { kind: "image", ...pullRequestMediaSource(url, location) };+}diff --git a/apps/mobile/src/features/pull-requests/usePullRequestAgentActions.test.ts b/apps/mobile/src/features/pull-requests/usePullRequestAgentActions.test.tsnew file mode 100644index 00000000000..db9100ba765--- /dev/null+++ b/apps/mobile/src/features/pull-requests/usePullRequestAgentActions.test.ts@@ -0,0 +1,55 @@+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import type { PullRequestDetail } from "@t3tools/contracts";+import { usePullRequestAgentActions } from "./usePullRequestAgentActions";++const state = vi.hoisted(() => ({+ connected: false,+ canAsk: true,+ ask: vi.fn(),+}));+vi.mock("./usePullRequestConnected", () => ({+ usePullRequestConnected: () => state.connected,+}));+vi.mock("./usePullRequestThreads", () => ({+ usePullRequestThreads: () => ({+ threads: [],+ canAsk: state.canAsk,+ canWatch: true,+ busy: false,+ isPending: true,+ ask: state.ask,+ }),+}));+const params = {+ environmentId: "environment",+ projectId: "project",+ repository: "owner/repo",+ number: 1,+};+const pr = { state: "open", mergeability: "conflicting" } as PullRequestDetail;++beforeEach(() => {+ state.connected = false;+ state.canAsk = true;+ state.ask.mockClear();+});++describe("PR agent drafts", () => {+ it("opens offline drafts without waiting for linked-thread discovery", () => {+ const actions = usePullRequestAgentActions(params, pr);+ expect(actions.disabled).toBe(false);+ actions.start("ask");+ actions.start("explain");+ expect(state.ask.mock.calls).toEqual([+ [undefined, "ask"],+ [undefined, "explain"],+ ]);+ });++ it("does not open drafts when the connection denies task access", () => {+ state.connected = true;+ state.canAsk = false;+ usePullRequestAgentActions(params, pr).start("explain");+ expect(state.ask).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/features/pull-requests/usePullRequestAgentActions.ts b/apps/mobile/src/features/pull-requests/usePullRequestAgentActions.tsindex a9d14a51cea..b3f2c38603a 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestAgentActions.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestAgentActions.ts@@ -5,6 +5,7 @@ import {type PullRequestAgentTask,} from "./pullRequestAgentTasks";import type { PullRequestParams } from "./usePullRequestDiff";+import { usePullRequestConnected } from "./usePullRequestConnected";import { usePullRequestThreads } from "./usePullRequestThreads";/** Shared destinations for toolbar helpers and actions beside PR readiness rows. */@@ -14,8 +15,9 @@ export function usePullRequestAgentActions(filePath?: string,) {const links = usePullRequestThreads(params, pr, filePath);+ const connected = usePullRequestConnected(params.environmentId);const actions = pr ? pullRequestAgentActions(pr, links.canWatch) : [];- const disabled = links.busy || !pr || (links.isPending && !links.threads.length);+ const disabled = links.busy || !pr || (connected && links.isPending && !links.threads.length);const start = (task: PullRequestAgentTask, threadId?: string) => {if (disabled) return;const thread = pullRequestAgentThread(links.threads, threadId);diff --git a/apps/mobile/src/features/pull-requests/usePullRequestConnected.ts b/apps/mobile/src/features/pull-requests/usePullRequestConnected.tsnew file mode 100644index 00000000000..ce2eff93f37--- /dev/null+++ b/apps/mobile/src/features/pull-requests/usePullRequestConnected.ts@@ -0,0 +1,8 @@+import { useWorkspaceEnvironments } from "../../state/workspace";++export function usePullRequestConnected(environmentId: string) {+ return useWorkspaceEnvironments().some(+ (environment) =>+ environment.environmentId === environmentId && environment.connectionState === "connected",+ );+}diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.tsindex 860d39fe1a6..cf882ac0dae 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts@@ -1,3 +1,4 @@+import { usePullRequestConnected } from "./usePullRequestConnected";import { useAtomRefresh, useAtomValue } from "@effect/atom-react";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import type { PullRequestDetail } from "@t3tools/contracts";@@ -12,9 +13,11 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReqconst target = pullRequestTarget(params);const scopeKey = pullRequestReviewKey(params);const supported = Boolean(pr?.capabilities.viewedFiles);- const allowed = useAtomValue(+ const permission = useAtomValue(composerPullRequests.setFilesViewed.permissionAtom(target.environmentId),);+ const connected = usePullRequestConnected(params.environmentId);+ const allowed = connected && permission;const query = useEnvironmentQuery(supported ? composerPullRequests.filesViewed(target) : null);const refresh = useAtomRefresh(composerPullRequests.filesViewed(target));const write = useAtomCommand(composerPullRequests.setFilesViewed, { reportFailure: false });diff --git a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.tsindex bc4e84a6d07..bde66bf9a4b 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts@@ -1,10 +1,12 @@import { useAtomValue } from "@effect/atom-react";import type { PullRequestDetail } from "@t3tools/contracts";+import { usePullRequestConnected } from "./usePullRequestConnected";import { composerPullRequests } from "../../state/pull-requests";import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";export function usePullRequestPermissions(params: PullRequestParams, pr: PullRequestDetail | null) {const { environmentId } = pullRequestTarget(params);+ const connected = usePullRequestConnected(environmentId);const canWrite = useAtomValue(composerPullRequests.runAction.permissionAtom(environmentId));const canComment = useAtomValue(composerPullRequests.comment.permissionAtom(environmentId));const canReview = useAtomValue(composerPullRequests.submitReview.permissionAtom(environmentId));@@ -13,7 +15,9 @@ export function usePullRequestPermissions(params: PullRequestParams, pr: PullReqcomposerPullRequests.setThreadResolution.permissionAtom(environmentId),);return {+ connected,canInlineComment:+ connected &&canReview &&pr?.state === "open" &&pr.capabilities.review.inlineComment &&@@ -21,13 +25,21 @@ export function usePullRequestPermissions(params: PullRequestParams, pr: PullReqpr.capabilities.review.verdicts.some((verdict) =>pr.viewerPermissions.verdicts.includes(verdict),),- canReply: canReply && pr?.capabilities.review.reply === true && pr.viewerPermissions.comment,+ canReply:+ connected &&+ canReply &&+ pr?.capabilities.review.reply === true &&+ pr.viewerPermissions.comment,canResolve:- canResolve && pr?.capabilities.review.resolve === true && pr.viewerPermissions.resolve,- canWrite,- canComment: canComment && pr?.capabilities.comment === true && pr.viewerPermissions.comment,+ connected &&+ canResolve &&+ pr?.capabilities.review.resolve === true &&+ pr.viewerPermissions.resolve,+ canWrite: connected && canWrite,+ canComment:+ connected && canComment && pr?.capabilities.comment === true && pr.viewerPermissions.comment,verdicts:- canReview && pr?.state === "open"+ connected && canReview && pr?.state === "open"? pr.capabilities.review.verdicts.filter((verdict) =>pr.viewerPermissions.verdicts.includes(verdict),)diff --git a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts b/apps/mobile/src/features/pull-requests/usePullRequestThreads.tsindex 075b62986ae..d38ec7d0bc2 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts@@ -27,6 +27,7 @@ import {updateComposerDraftSettings,waitForComposerDraftsLoaded,} from "../../state/use-composer-drafts";+import { usePullRequestConnected } from "./usePullRequestConnected";import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";import {appendPullRequestAgentPrompt,@@ -63,7 +64,10 @@ export function usePullRequestThreads(setLastRelations({ key, data: relations.data });const threads =(relations.data ?? (lastRelations.key === key ? lastRelations.data : null))?.threads ?? [];- const canAsk = useEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope);+ const connected = usePullRequestConnected(params.environmentId);+ const canOperate = useEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope);+ // Composing offline only writes a local draft. The outbox checks grants on delivery.+ const canAsk = !connected || canOperate;const canCheckout = useEnvironmentScope(target.environmentId, AuthSourceControlWriteScope);const navigation = useNavigation();const pending = useRef(false);@@ -76,7 +80,7 @@ export function usePullRequestThreads(pending.current = true;setBusy(true);try {- if (!thread && !canCheckout)+ if (connected && !thread && !canCheckout)throw new Error("Starting work from this PR requires source control write access.");await waitForComposerDraftsLoaded();const draftKey = threaddiff --git a/apps/mobile/src/lib/videoPreviewSource.ts b/apps/mobile/src/lib/videoPreviewSource.tsindex 78a5acf3f33..673db6d2c4d 100644--- a/apps/mobile/src/lib/videoPreviewSource.ts+++ b/apps/mobile/src/lib/videoPreviewSource.ts@@ -17,7 +17,7 @@ export type MediaVideoPreviewSource = {readonly environmentId: EnvironmentId;readonly resource: Extract<AssetResource,- { readonly _tag: "attachment" | "media-file" | "draft-workspace-file" }+ { readonly _tag: "attachment" | "media-file" | "draft-workspace-file" | "github-media" }>;});@@ -47,14 +47,22 @@ export function mediaVideoThumbnailKey(source: MediaVideoPreviewSource): stringsource.resource.path,source.srcFragment ?? "",]- : [- "media-video",- "draft-workspace-file",- source.environmentId,- source.resource.cwd,- source.resource.path,- source.srcFragment ?? "",- ],+ : source.resource._tag === "github-media"+ ? [+ "media-video",+ "github-media",+ source.environmentId,+ source.resource.cwd,+ source.resource.url,+ ]+ : [+ "media-video",+ "draft-workspace-file",+ source.environmentId,+ source.resource.cwd,+ source.resource.path,+ source.srcFragment ?? "",+ ],);}diff --git a/apps/mobile/src/persistence/layer.ts b/apps/mobile/src/persistence/layer.tsindex 965a9cc7f4c..c64adc01547 100644--- a/apps/mobile/src/persistence/layer.ts+++ b/apps/mobile/src/persistence/layer.ts@@ -1,5 +1,6 @@import * as Layer from "effect/Layer";+import * as PullRequestCacheStore from "../connection/pull-request-cache-store";import * as EnvironmentCacheStore from "../connection/environment-cache-store";import * as MobileDatabase from "./mobile-database";import * as MobilePreferences from "./mobile-preferences";@@ -11,6 +12,7 @@ const layerDependent = Layer.mergeAll(MobilePreferences.layer,MobileStorage.layer,EnvironmentCacheStore.layer,+ PullRequestCacheStore.layer,).pipe(Layer.provide(layerBase));export const layer = Layer.merge(layerBase, layerDependent);diff --git a/apps/mobile/src/persistence/mobile-database.test.ts b/apps/mobile/src/persistence/mobile-database.test.tsindex 244331471fd..b790d03b2d9 100644--- a/apps/mobile/src/persistence/mobile-database.test.ts+++ b/apps/mobile/src/persistence/mobile-database.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";+import * as Option from "effect/Option";import { vi } from "vite-plus/test";const openDatabaseAsync = vi.hoisted(() => vi.fn());@@ -69,3 +70,87 @@ describe("mobile database legacy cache migration", () => {).toBeNull();});});++// Exercise the production SQL against SQLite, including the eviction window functions.+describe("offline pull request cache", () => {+ const environmentId = "cached-environment" as import("@t3tools/contracts").EnvironmentId;+ const otherEnvironment = "other-environment" as import("@t3tools/contracts").EnvironmentId;++ async function sqliteDatabase() {+ const { DatabaseSync } = await import("node:sqlite");+ const sqlite = new DatabaseSync(":memory:");+ sqlite.exec("PRAGMA user_version = 1");+ const database = {+ execAsync: async (sql: string) => {+ sqlite.exec(sql);+ },+ runAsync: async (sql: string, ...args: Array<string | number>) =>+ sqlite.prepare(sql).run(...args),+ getFirstAsync: async (sql: string, ...args: Array<string | number>) =>+ sqlite.prepare(sql).get(...args),+ getAllAsync: async (sql: string, ...args: Array<string | number>) =>+ sqlite.prepare(sql).all(...args),+ withExclusiveTransactionAsync: async (run: (transaction: unknown) => Promise<void>) => {+ await run(database);+ },+ closeAsync: async () => {+ sqlite.close();+ },+ };+ openDatabaseAsync.mockResolvedValueOnce(database);+ return sqlite;+ }++ it.effect("restores saved records and clears them with the environment", () =>+ Effect.scoped(+ Effect.gen(function* () {+ yield* Effect.promise(sqliteDatabase);+ const database = yield* MobileDatabase.make;+ yield* database.saveCache(environmentId, "pull-request", "v1:list", 1, '{"entries":[]}');+ yield* database.saveCache(otherEnvironment, "pull-request", "v1:list", 1, "other");+ expect(yield* database.loadCache(environmentId, "pull-request", "v1:list")).toEqual(+ Option.some('{"entries":[]}'),+ );+ yield* database.clearEnvironmentCache(environmentId);+ expect((yield* database.loadCache(environmentId, "pull-request", "v1:list"))._tag).toBe(+ "None",+ );+ expect((yield* database.loadCache(otherEnvironment, "pull-request", "v1:list"))._tag).toBe(+ "Some",+ );+ }),+ ),+ );++ it.effect(+ "expires old records and bounds count and payload size without evicting other cache kinds",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ const sqlite = yield* Effect.promise(sqliteDatabase);+ const database = yield* MobileDatabase.make;+ yield* database.saveCache(environmentId, "thread", "thread", 1, "thread");+ yield* database.saveCache(environmentId, "pull-request", "old", 1, "old");+ sqlite.prepare("UPDATE client_cache SET updated_at = 0 WHERE cache_key = 'old'").run();+ expect((yield* database.loadCache(environmentId, "pull-request", "old"))._tag).toBe(+ "None",+ );+ for (let i = 0; i < 260; i++)+ yield* database.saveCache(environmentId, "pull-request", `page-${i}`, 1, "page");+ expect((yield* database.listCache("pull-request")).length).toBe(256);+ const large = "x".repeat(4 * 1024 * 1024);+ for (let i = 0; i < 10; i++)+ yield* database.saveCache(environmentId, "pull-request", `diff-${i}`, 1, large);+ const summary = yield* database.inspectCaches;+ const prs = summary.find((row) => row.kind === "pull-request");+ expect(prs?.payloadBytes).toBeLessThanOrEqual(32 * 1024 * 1024);+ expect(prs?.recordCount).toBeLessThanOrEqual(256);+ expect((yield* database.loadCache(environmentId, "thread", "thread"))._tag).toBe("Some");+ yield* database.saveCache(environmentId, "pull-request", "oversized", 1, large + "x");+ expect((yield* database.loadCache(environmentId, "pull-request", "oversized"))._tag).toBe(+ "None",+ );+ }),+ ),+ );+});diff --git a/apps/mobile/src/persistence/mobile-database.ts b/apps/mobile/src/persistence/mobile-database.tsindex 7c7b6bc5ded..6796e93674f 100644--- a/apps/mobile/src/persistence/mobile-database.ts+++ b/apps/mobile/src/persistence/mobile-database.ts@@ -22,6 +22,7 @@ export const ClientCacheKind = Schema.Literals(["server-config","vcs-refs","project-favicon",+ "pull-request",]);export type ClientCacheKind = typeof ClientCacheKind.Type;@@ -294,10 +295,12 @@ const makeAvailable = Effect.gen(function* () {database.getFirstAsync<{ readonly payload: string }>(`SELECT payloadFROM client_cache- WHERE environment_id = ? AND kind = ? AND cache_key = ?`,+ WHERE environment_id = ? AND kind = ? AND cache_key = ?+ AND (kind != 'pull-request' OR updated_at >= ?)`,environmentId,kind,cacheKey,+ Date.now() - 30 * 24 * 60 * 60_000,),catch: databaseError("load-cache"),}).pipe(Effect.map((row) => Option.fromNullishOr(row?.payload))),@@ -315,22 +318,51 @@ const makeAvailable = Effect.gen(function* () {saveCache: Effect.fn("MobileDatabase.saveCache")((environmentId, kind, cacheKey, schemaVersion, payload) =>Effect.tryPromise({- try: () =>- database.runAsync(- `INSERT INTO client_cache- (environment_id, kind, cache_key, schema_version, payload, updated_at)- VALUES (?, ?, ?, ?, ?, ?)- ON CONFLICT (environment_id, kind, cache_key) DO UPDATE SET- schema_version = excluded.schema_version,- payload = excluded.payload,- updated_at = excluded.updated_at`,- environmentId,- kind,- cacheKey,- schemaVersion,- payload,- Date.now(),- ),+ try: async () => {+ // Diffs can be large. Keep the offline PR cache within 32 MiB and 256+ // responses per environment, and don't let one huge diff evict it all.+ if (+ kind === "pull-request" &&+ new TextEncoder().encode(payload).length > 4 * 1024 * 1024+ )+ return;+ const save = async (transaction: SQLiteDatabase) => {+ await transaction.runAsync(+ `INSERT INTO client_cache+ (environment_id, kind, cache_key, schema_version, payload, updated_at)+ VALUES (?, ?, ?, ?, ?, ?)+ ON CONFLICT (environment_id, kind, cache_key) DO UPDATE SET+ schema_version = excluded.schema_version,+ payload = excluded.payload,+ updated_at = excluded.updated_at`,+ environmentId,+ kind,+ cacheKey,+ schemaVersion,+ payload,+ Date.now(),+ );+ if (kind === "pull-request") {+ await transaction.runAsync(+ `DELETE FROM client_cache WHERE environment_id = ? AND kind = 'pull-request'+ AND cache_key IN (+ SELECT cache_key FROM (+ SELECT cache_key, updated_at,+ ROW_NUMBER() OVER (ORDER BY updated_at DESC, cache_key) AS position,+ SUM(LENGTH(CAST(payload AS BLOB))) OVER (+ ORDER BY updated_at DESC, cache_key+ ) AS total_bytes+ FROM client_cache WHERE environment_id = ? AND kind = 'pull-request'+ ) WHERE position > 256 OR total_bytes > 33554432 OR updated_at < ?+ )`,+ environmentId,+ environmentId,+ Date.now() - 30 * 24 * 60 * 60_000,+ );+ }+ };+ await save(database);+ },catch: databaseError("save-cache"),}).pipe(Effect.asVoid),),diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsxindex 6ffb54569ef..27fe1bc6b50 100644--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx@@ -90,11 +90,11 @@ export function PullRequestMarkdown({data-image-gallery>{segments.map((segment) => {- if (segment.kind === "markdown") {+ if (segment.kind === "markdown" || segment.media === "image") {return (<ChatMarkdownkey={segment.id}- text={segment.text}+ text={segment.kind === "markdown" ? segment.text : ``}cwd={cwd}threadRef={resolvedThreadRef}pullRequestPanelRef={resolvedThreadRef ?? PULL_REQUESTS_PANEL_REF}diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.tsindex 79ae60e928c..cfcb355a538 100644--- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts@@ -4,149 +4,10 @@ import {type TextMatch,} from "~/vendor/mdast-find-and-replace";-/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */-export type PullRequestBodySegment =- | { readonly id: string; readonly kind: "markdown"; readonly text: string }- | {- readonly id: string;- readonly kind: "attachment";- readonly url: string;- /**- * What the reader can be told the upload is. The uuid says nothing on its own — the type- * only appears in the signed redirect GitHub answers with — but the shape does: GitHub- * writes a dropped image into the body as an `<img>` tag, so a bare attachment link on its- * own line is what it does with a video. Anything else keeps the neutral name.- */- readonly media: "video" | "unknown";- };--const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)$/u;-/**- * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,- * and the bound keeps an unclosed tag from making each one rescan the rest of the body.- */-const VIDEO_TAG_MAX_LINES = 8;-/** Four spaces open an indented code block, so its contents stay verbatim markdown. */-const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;-const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;-const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;-/** A dropped video becomes a bare asset link; a dropped image becomes an `<img>` tag. */-const GITHUB_ASSET_PATTERN = /^https:\/\/github\.com\/user-attachments\/assets\/[\w-]+$/iu;-const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;-/** Only a tag that owns its line is an embed; inline, it is prose the renderer should keep. */-const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;-const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;--/** Anything else — `javascript:`, `data:`, a relative path — is not an upload to link out to. */-function isWebUrl(url: string): boolean {- try {- const parsed = new URL(url);- return parsed.protocol === "https:" || parsed.protocol === "http:";- } catch {- return false;- }-}--function attachmentFromLine(line: string): { url: string; media: "video" | "unknown" } | null {- const url = BARE_URL_PATTERN.exec(line.trim())?.[1];- if (url === undefined || !isWebUrl(url)) return null;- if (VIDEO_EXTENSION_PATTERN.test(url) || GITHUB_ASSET_PATTERN.test(url)) {- return { url, media: "video" };- }- return null;-}--/**- * Splits a pull request body into markdown runs and the uploads embedded in it, which the- * markdown renderer drops: `<video>` is not in its sanitizer's schema, and a bare attachment- * link arrives as prose. Two shapes are recognised, both of which GitHub produces itself: a- * `<video>` (or `<source>`) tag, and a bare link on its own line to a video file or an- * uploaded attachment. Fenced code is copied through untouched so a snippet that happens to- * contain a link is never lifted out of it.- */-export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {- const segments: PullRequestBodySegment[] = [];- const markdown: string[] = [];- let openFence: string | null = null;-- // Blank lines around a run are dropped, but never leading spaces: four of them open an- // indented code block, so trimming a run would silently turn code into prose.- const flushMarkdown = () => {- const text = markdown.join("\n").replace(/^\n+/u, "").replace(/\s+$/u, "");- markdown.length = 0;- if (text.trim().length > 0) {- segments.push({ id: `markdown:${segments.length}`, kind: "markdown", text });- }- };-- const lines = body.split("\n");- for (let index = 0; index < lines.length; index += 1) {- const line = lines[index]!;- const fenceMatch = FENCE_PATTERN.exec(line);- if (fenceMatch !== null) {- const fence = fenceMatch[1]!;- // A fence closes only on the same marker, at least as long as the one that opened it,- // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an- // info string opening a nested fence, not a close.- const closes =- openFence !== null &&- fence[0] === openFence[0] &&- fence.length >= openFence.length &&- fenceMatch[2]!.trim().length === 0;- if (openFence === null) {- openFence = fence;- } else if (closes) {- openFence = null;- }- markdown.push(line);- continue;- }- if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {- markdown.push(line);- continue;- }-- const bareAttachment = attachmentFromLine(line);- if (bareAttachment !== null) {- flushMarkdown();- segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });- continue;- }-- if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {- markdown.push(line);- continue;- }- // A tag can span lines, so look ahead for its close — bounded, and without building the- // joined text until one is actually found.- const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;- let cursor = index;- while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {- cursor += 1;- }- const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)- ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]- : undefined;- if (source !== undefined && isWebUrl(source)) {- flushMarkdown();- segments.push({- id: `attachment:${segments.length}`,- kind: "attachment",- url: source,- // The author wrote the tag, so this one is a video whatever the URL looks like.- media: "video",- });- index = cursor;- } else {- // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the- // lines that were looked at are still parsed on their own terms.- markdown.push(line);- }- }-- flushMarkdown();- return segments;-}+export {+ splitPullRequestBody,+ type PullRequestBodySegment,+} from "@t3tools/client-runtime/pull-request-markdown";const AUTOLINK_CANDIDATE_PATTERN = /#[1-9]\d*|[0-9a-f]{40}/giu;const AUTOLINK_WORD_CHARACTER_PATTERN = /[A-Za-z0-9_]/u;diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex eacccabc5f4..4a222b9102f 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -158,6 +158,10 @@ to read its description, activity, commits, and changed files. Line comments stauntil you submit the review. **Work on PR** opens a chat with the review attached; sendingthe first message prepares a worktree from the review's branch.+Previously loaded lists, review details, guides, and diff pages remain readable on mobile+without a connection, including after restarting the app. Saved content refreshes when the+environment reconnects; submitting changes requires a connection.+Enable **Remove agent credits when merging** in Settings → Source Control to remove recognizedagent co-author and generated-by lines from GitHub merge and squash commit messages. Humanco-authors stay credited. The setting is off by default and projects can override it. It alsodiff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex d7191193b10..672f1992702 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -402,6 +402,14 @@"./review-guide-tour": {"types": "./src/reviewGuideTour.ts","default": "./src/reviewGuideTour.ts"+ },+ "./state/query-persistence": {+ "types": "./src/state/queryPersistence.ts",+ "default": "./src/state/queryPersistence.ts"+ },+ "./pull-request-markdown": {+ "types": "./src/pullRequestMarkdown.ts",+ "default": "./src/pullRequestMarkdown.ts"}},"scripts": {diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.tssimilarity index 86%rename from apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.tsrename to packages/client-runtime/src/pullRequestMarkdown.test.tsindex 5779909a6a6..400fca73b46 100644--- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts+++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vite-plus/test";-import { splitPullRequestBody } from "./pullRequestMarkdown.logic";+import { splitPullRequestBody } from "./pullRequestMarkdown.ts";describe("pull request body segmentation", () => {it("keeps a plain body as a single markdown run", () => {@@ -144,3 +144,23 @@ describe("pull request body segmentation", () => {]);});});++describe("media on custom hosts", () => {+ it.each([+ ["https://drop.example.com/capture.PNG?token=abc#preview", "image"],+ ["[Recording](https://drop.example.com/recording.mov)", "video"],+ ["<https://drop.example.com/shot.webp>", "image"],+ ])("recognizes %s without a request", (body, media) => {+ expect(splitPullRequestBody(body)).toEqual([+ expect.objectContaining({ kind: "attachment", media }),+ ]);+ });++ it("keeps inline links and media examples in code as prose", () => {+ const body =+ "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";+ expect(splitPullRequestBody(body)).toEqual([+ { id: "markdown:0", kind: "markdown", text: body },+ ]);+ });+});diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.tsnew file mode 100644index 00000000000..a9447c36b75--- /dev/null+++ b/packages/client-runtime/src/pullRequestMarkdown.ts@@ -0,0 +1,146 @@+/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */+export type PullRequestBodySegment =+ | { readonly id: string; readonly kind: "markdown"; readonly text: string }+ | {+ readonly id: string;+ readonly kind: "attachment";+ readonly url: string;+ /**+ * What the reader can be told the upload is. The uuid says nothing on its own — the type+ * only appears in the signed redirect GitHub answers with — but the shape does: GitHub+ * writes a dropped image into the body as an `<img>` tag, so a bare attachment link on its+ * own line is what it does with a video. Anything else keeps the neutral name.+ */+ readonly media: "video" | "image" | "unknown";+ };++const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)$/u;+/**+ * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,+ * and the bound keeps an unclosed tag from making each one rescan the rest of the body.+ */+const VIDEO_TAG_MAX_LINES = 8;+/** Four spaces open an indented code block, so its contents stay verbatim markdown. */+const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;+const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;+const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$|[?#])/iu;+const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;+const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;+/** A dropped video becomes a bare asset link; a dropped image becomes an `<img>` tag. */+const GITHUB_ASSET_PATTERN = /^https:\/\/github\.com\/user-attachments\/assets\/[\w-]+$/iu;+const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;+/** Only a tag that owns its line is an embed; inline, it is prose the renderer should keep. */+const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;+const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;++/** Anything else — `javascript:`, `data:`, a relative path — is not an upload to link out to. */+function isWebUrl(url: string): boolean {+ try {+ const parsed = new URL(url);+ return parsed.protocol === "https:" || parsed.protocol === "http:";+ } catch {+ return false;+ }+}++function attachmentFromLine(+ line: string,+): { url: string; media: "video" | "image" | "unknown" } | null {+ const url =+ BARE_URL_PATTERN.exec(line.trim())?.[1] ?? MARKDOWN_LINK_PATTERN.exec(line.trim())?.[1];+ if (url === undefined || !isWebUrl(url)) return null;+ if (VIDEO_EXTENSION_PATTERN.test(url) || GITHUB_ASSET_PATTERN.test(url)) {+ return { url, media: "video" };+ }+ if (IMAGE_EXTENSION_PATTERN.test(url)) return { url, media: "image" };+ return null;+}++/**+ * Lifts standalone media links and video tags out of prose for both clients.+ * Ordinary links and code examples remain markdown. Images already embedded+ * with markdown or HTML keep their original renderer.+ */+export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {+ const segments: PullRequestBodySegment[] = [];+ const markdown: string[] = [];+ let openFence: string | null = null;++ // Blank lines around a run are dropped, but never leading spaces: four of them open an+ // indented code block, so trimming a run would silently turn code into prose.+ const flushMarkdown = () => {+ const text = markdown.join("\n").replace(/^\n+/u, "").replace(/\s+$/u, "");+ markdown.length = 0;+ if (text.trim().length > 0) {+ segments.push({ id: `markdown:${segments.length}`, kind: "markdown", text });+ }+ };++ const lines = body.split("\n");+ for (let index = 0; index < lines.length; index += 1) {+ const line = lines[index]!;+ const fenceMatch = FENCE_PATTERN.exec(line);+ if (fenceMatch !== null) {+ const fence = fenceMatch[1]!;+ // A fence closes only on the same marker, at least as long as the one that opened it,+ // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an+ // info string opening a nested fence, not a close.+ const closes =+ openFence !== null &&+ fence[0] === openFence[0] &&+ fence.length >= openFence.length &&+ fenceMatch[2]!.trim().length === 0;+ if (openFence === null) {+ openFence = fence;+ } else if (closes) {+ openFence = null;+ }+ markdown.push(line);+ continue;+ }+ if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {+ markdown.push(line);+ continue;+ }++ const bareAttachment = attachmentFromLine(line);+ if (bareAttachment !== null) {+ flushMarkdown();+ segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });+ continue;+ }++ if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {+ markdown.push(line);+ continue;+ }+ // A tag can span lines, so look ahead for its close — bounded, and without building the+ // joined text until one is actually found.+ const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;+ let cursor = index;+ while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {+ cursor += 1;+ }+ const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)+ ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]+ : undefined;+ if (source !== undefined && isWebUrl(source)) {+ flushMarkdown();+ segments.push({+ id: `attachment:${segments.length}`,+ kind: "attachment",+ url: source,+ // The author wrote the tag, so this one is a video whatever the URL looks like.+ media: "video",+ });+ index = cursor;+ } else {+ // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the+ // lines that were looked at are still parsed on their own terms.+ markdown.push(line);+ }+ }++ flushMarkdown();+ return segments;+}diff --git a/packages/client-runtime/src/state/pullRequestStatsPersistence.ts b/packages/client-runtime/src/state/pullRequestStatsPersistence.tsnew file mode 100644index 00000000000..ba38a299921--- /dev/null+++ b/packages/client-runtime/src/state/pullRequestStatsPersistence.ts@@ -0,0 +1,43 @@+import {+ PullRequestDiffStat,+ PullRequestListStatsInput,+ type PullRequestListStatsResult,+ type PullRequestRef,+} from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";+import { persistQuery, type QueryPersistence } from "./queryPersistence.ts";++const requestKey = Schema.fromJsonString(Schema.Tuple([Schema.String, PullRequestListStatsInput]));+const statKey = (ref: PullRequestRef) =>+ JSON.stringify(["pull-request-stat", ref.projectId, ref.host ?? "", ref.repository, ref.number]);++/** Visible rows are batched differently after a restart, so store their counts individually. */+export function persistPullRequestStats(): QueryPersistence<PullRequestListStatsResult> {+ const row = persistQuery(PullRequestDiffStat);+ return {+ load: (environmentId, key) =>+ Effect.gen(function* () {+ const [, input] = yield* Schema.decodeEffect(requestKey)(key);+ const rows = yield* Effect.forEach(input.refs, (ref) =>+ row.load(environmentId, statKey(ref)),+ );+ const stats = rows.flatMap((value) => (Option.isSome(value) ? [value.value] : []));+ return stats.length ? Option.some({ stats }) : Option.none();+ }).pipe(Effect.orElseSucceed(() => Option.none())),+ save: (environmentId, key, result) =>+ Effect.gen(function* () {+ const [, input] = yield* Schema.decodeEffect(requestKey)(key);+ yield* Effect.forEach(result.stats, (stat) => {+ const ref = input.refs.find(+ (ref) =>+ ref.projectId === stat.projectId &&+ ref.repository === stat.repository &&+ ref.number === stat.number,+ );+ return ref ? row.save(environmentId, statKey(ref), stat) : Effect.void;+ });+ }).pipe(Effect.ignore),+ };+}diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.tsindex 75b76d8c3f4..0217cfd0007 100644--- a/packages/client-runtime/src/state/pullRequests.test.ts+++ b/packages/client-runtime/src/state/pullRequests.test.ts@@ -4,6 +4,7 @@ import { vi } from "vite-plus/test";import {EnvironmentId,AuthSourceControlWriteScope,+ AuthOrchestrationOperateScope,ProjectId,PullRequestOperationError,WS_METHODS,@@ -2082,3 +2083,48 @@ it.effect("denies a routed write when only the origin has source-control permiss}),),);++it.effect("publishes the accepted guide run before the follow-up read finishes", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const accepted = {+ guide: null,+ currentHeadSha: "head",+ run: { _tag: "Running" as const, headSha: "head", startedAt: "2026-10-11T00:00:00.000Z" },+ };+ let reads = 0;+ const refreshStarted = yield* Latch.make();+ const client = {+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,+ [WS_METHODS.pullRequestsReviewGuide]: () =>+ Effect.gen(function* () {+ if (++reads > 1) {+ yield* refreshStarted.open;+ return yield* Effect.never;+ }+ return { guide: null, run: null, currentHeadSha: "head" };+ }),+ [WS_METHODS.pullRequestsGenerateReviewGuide]: () => Effect.succeed(accepted),+ } as unknown as WsRpcProtocolClient;+ const { atoms, registry } = yield* makeTestRuntime(client);+ const target = {+ environmentId: TARGET.environmentId,+ input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },+ };+ registry.update(+ grantedSessions(target.environmentId),+ AsyncResult.map((session) => ({+ ...session,+ scopes: [...(session.scopes ?? []), AuthOrchestrationOperateScope],+ })),+ );+ const query = atoms.reviewGuide(target);+ registry.mount(query);+ yield* AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });+ const result = yield* Effect.promise(() => atoms.generateReviewGuide.run(registry, target));+ expect(result._tag).toBe("Success");+ yield* refreshStarted.await;+ expect(Option.getOrNull(AsyncResult.value(registry.get(query)))).toEqual(accepted);+ }),+ ),+);diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 2e73b1580d8..feb5f0b3ea4 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -1,5 +1,14 @@import {WS_METHODS,+ PullRequestActivity,+ PullRequestDetail as PullRequestDetailSchema,+ PullRequestPreview,+ PullRequestReviewGuideResult,+ PullRequestListResult,+ PullRequestChecks,+ PullRequestDiffResult,+ PullRequestFilesViewedResult,+ PullRequestLinkedThreadsResult,type EnvironmentId,type PullRequestActor,type PullRequestActionInput,@@ -13,6 +22,9 @@ import {} from "@t3tools/contracts";import * as Data from "effect/Data";import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";+import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";+import { persistQuery } from "./queryPersistence.ts";import * as Option from "effect/Option";import * as SubscriptionRef from "effect/SubscriptionRef";import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";@@ -172,6 +184,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(const activity = writableQueryFamily(createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:activity",+ persistence: persistQuery(PullRequestActivity),tag: WS_METHODS.pullRequestsActivity,execute: (input) => routedRequest(WS_METHODS.pullRequestsActivity, input),staleTimeMs: 60_000,@@ -181,6 +194,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(const detail = writableQueryFamily(createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:detail",+ persistence: persistQuery(PullRequestDetailSchema),tag: WS_METHODS.pullRequestsDetail,execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),staleTimeMs: 60_000,@@ -190,6 +204,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(const preview = writableQueryFamily(createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:preview",+ persistence: persistQuery(PullRequestPreview),tag: WS_METHODS.pullRequestsPreview,execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),staleTimeMs: 60_000,@@ -208,6 +223,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(const reviewGuide = writableQueryFamily(createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:review-guide",+ persistence: persistQuery(PullRequestReviewGuideResult),tag: WS_METHODS.pullRequestsReviewGuide,execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewGuide, input),staleTimeMs: 60_000,@@ -226,6 +242,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(refreshes,linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:linked-threads",+ persistence: persistQuery(PullRequestLinkedThreadsResult),tag: WS_METHODS.pullRequestsLinkedThreads,staleTimeMs: 0,refreshIntervalMs: 10_000,@@ -233,6 +250,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(}),list: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:list",+ persistence: persistQuery(PullRequestListResult),tag: WS_METHODS.pullRequestsList,staleTimeMs: 30_000,refreshTrigger: ({ environmentId, input }) =>@@ -246,6 +264,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(*/listStats: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:list-stats",+ persistence: persistPullRequestStats(),tag: WS_METHODS.pullRequestsListStats,staleTimeMs: 60_000,refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),@@ -254,6 +273,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(preview,checks: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:checks",+ persistence: persistQuery(Schema.NullOr(PullRequestChecks)),tag: WS_METHODS.pullRequestsChecks,execute: (input) => routedRequest(WS_METHODS.pullRequestsChecks, input),staleTimeMs: 45_000,@@ -273,6 +293,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(}),diff: createEnvironmentQueryAtomFamily(runtime, {label: "environment-data:pull-requests:diff",+ persistence: persistQuery(PullRequestDiffResult),staleTimeMs: 60_000,execute: (input: PullRequestDiffInput) =>Effect.gen(function* () {@@ -310,6 +331,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(}),filesViewed: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:files-viewed",+ persistence: persistQuery(PullRequestFilesViewedResult),tag: WS_METHODS.pullRequestsFilesViewed,execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),staleTimeMs: 15_000,@@ -517,7 +539,12 @@ export function createPullRequestEnvironmentAtoms<R, E>(label: "environment-data:pull-requests:generate-review-guide",tag: WS_METHODS.pullRequestsGenerateReviewGuide,execute: (input) => routedRequest(WS_METHODS.pullRequestsGenerateReviewGuide, input),- onSuccess: (target, registry) => Effect.sync(() => registry.refresh(reviewGuide(target))),+ onSuccess: (target, registry, result) =>+ Effect.sync(() => {+ // The command returns the accepted run. Publish it before starting ends so readers+ // never fall back to the empty/failed state while the follow-up query is in flight.+ updateCached(registry, reviewGuide(target), () => result, true);+ }),}),/** Read when the label menu opens, and kept for a minute, like the reviewer candidates. */labelCandidates,diff --git a/packages/client-runtime/src/state/queryPersistence.test.ts b/packages/client-runtime/src/state/queryPersistence.test.tsnew file mode 100644index 00000000000..31983acc0e4--- /dev/null+++ b/packages/client-runtime/src/state/queryPersistence.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from "@effect/vitest";+import { EnvironmentId, ProjectId } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";+import { EnvironmentQueryStore, persistQuery } from "./queryPersistence.ts";++import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";++const env = EnvironmentId.make("one");+const other = EnvironmentId.make("two");+const persisted = persistQuery(Schema.Struct({ title: Schema.String }));++function store(records = new Map<string, string>()) {+ return {+ load: (environmentId: EnvironmentId, key: string) =>+ Effect.sync(() => Option.fromUndefinedOr(records.get(`${environmentId}:${key}`))),+ save: (environmentId: EnvironmentId, key: string, payload: string) =>+ Effect.sync(() => {+ records.set(`${environmentId}:${key}`, payload);+ }),+ };+}++describe("query persistence", () => {+ it.effect("round trips responses without mixing environments or query scopes", () =>+ Effect.gen(function* () {+ yield* persisted.save(env, "open", { title: "saved" });+ expect(yield* persisted.load(env, "open")).toEqual(Option.some({ title: "saved" }));+ expect(yield* persisted.load(other, "open")).toEqual(Option.none());+ expect(yield* persisted.load(env, "closed")).toEqual(Option.none());+ }).pipe(Effect.provideService(EnvironmentQueryStore, store())),+ );++ it.effect("ignores corrupt or incompatible records", () =>+ Effect.gen(function* () {+ expect(yield* persisted.load(env, "broken")).toEqual(Option.none());+ expect(yield* persisted.load(env, "incompatible")).toEqual(Option.none());+ }).pipe(+ Effect.provideService(+ EnvironmentQueryStore,+ store(+ new Map([+ ["one:broken", "not json"],+ ["one:incompatible", '{"title":42}'],+ ]),+ ),+ ),+ ),+ );++ it.effect("does not persist on platforms without a query store", () =>+ Effect.gen(function* () {+ yield* persisted.save(env, "open", { title: "saved" });+ expect(yield* persisted.load(env, "open")).toEqual(Option.none());+ }),+ );+});++it.effect("restores line counts when visible PR batches change", () =>+ Effect.gen(function* () {+ const cache = persistPullRequestStats();+ const first = { projectId: ProjectId.make("project"), repository: "owner/repo", number: 1 };+ const second = { ...first, number: 2 };+ const stat = { ...first, additions: 42, deletions: 3 };+ yield* cache.save(env, JSON.stringify(["stats", { refs: [first, second] }]), { stats: [stat] });+ const key = JSON.stringify(["stats", { refs: [first] }]);+ expect(yield* cache.load(env, key)).toEqual(Option.some({ stats: [stat] }));+ expect(yield* cache.load(other, key)).toEqual(Option.none());+ }).pipe(Effect.provideService(EnvironmentQueryStore, store())),+);diff --git a/packages/client-runtime/src/state/queryPersistence.ts b/packages/client-runtime/src/state/queryPersistence.tsnew file mode 100644index 00000000000..46b578ccbb9--- /dev/null+++ b/packages/client-runtime/src/state/queryPersistence.ts@@ -0,0 +1,49 @@+import type { EnvironmentId } from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";++/** Platforms opt in to storing selected query responses beside their other offline data. */+export class EnvironmentQueryStore extends Context.Reference<{+ readonly load: (+ environmentId: EnvironmentId,+ key: string,+ ) => Effect.Effect<Option.Option<string>>;+ readonly save: (+ environmentId: EnvironmentId,+ key: string,+ payload: string,+ ) => Effect.Effect<void>;+} | null>("@t3tools/client-runtime/EnvironmentQueryStore", {+ defaultValue: () => null,+}) {}++export interface QueryPersistence<A> {+ readonly load: (environmentId: EnvironmentId, key: string) => Effect.Effect<Option.Option<A>>;+ readonly save: (environmentId: EnvironmentId, key: string, value: A) => Effect.Effect<void>;+}++export function persistQuery<A, I>(schema: Schema.Codec<A, I>): QueryPersistence<A> {+ const codec = Schema.fromJsonString(Schema.toCodecJson(schema));+ return {+ load: (environmentId, key) =>+ Effect.gen(function* () {+ const store = yield* EnvironmentQueryStore;+ if (store === null) return Option.none<A>();+ const stored = yield* store.load(environmentId, key);+ if (Option.isNone(stored)) return Option.none<A>();+ return yield* Schema.decodeUnknownEffect(codec)(stored.value).pipe(+ Effect.map(Option.some),+ Effect.catch(() => Effect.succeedNone),+ );+ }),+ save: (environmentId, key, value) =>+ Effect.gen(function* () {+ const store = yield* EnvironmentQueryStore;+ if (store === null) return;+ const payload = yield* Schema.encodeEffect(codec)(value);+ yield* store.save(environmentId, key, payload);+ }).pipe(Effect.catch(() => Effect.logWarning("Offline query cache save failed"))),+ };+}diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.tsindex 2d123c94568..0cc360288c2 100644--- a/packages/client-runtime/src/state/runtime.test.ts+++ b/packages/client-runtime/src/state/runtime.test.ts@@ -26,6 +26,7 @@ import * as EnvironmentRegistry from "../connection/registry.ts";import * as EnvironmentSupervisor from "../connection/supervisor.ts";import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";import type * as RpcSession from "../rpc/session.ts";+import type { QueryPersistence } from "./queryPersistence.ts";import {environmentRpcKey,createAtomCommandScheduler,@@ -85,9 +86,16 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"{refreshTrigger,idleTtlMs,- }: { readonly refreshTrigger?: Atom.Atom<unknown>; readonly idleTtlMs?: number } = {},+ persistence,+ initialState,+ }: {+ readonly refreshTrigger?: Atom.Atom<unknown>;+ readonly idleTtlMs?: number;+ readonly persistence?: QueryPersistence<A>;+ readonly initialState?: SupervisorConnectionState;+ } = {},) {- const supervisorState = yield* SubscriptionRef.make(queryConnectionState());+ const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());const supervisorSession = yield* SubscriptionRef.make(Option.some(QUERY_RPC_SESSION));const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({target: QUERY_ENVIRONMENT,@@ -115,6 +123,7 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"const family = createEnvironmentQueryAtomFamily(runtime, {label: "test.environment-query",staleTimeMs: 60_000,+ ...(persistence === undefined ? {} : { persistence }),execute: () => execute,...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }),...(idleTtlMs === undefined ? {} : { idleTtlMs }),@@ -1126,3 +1135,88 @@ describe("runtime command runner", () => {registry.dispose();});});++describe("persisted environment queries", () => {+ it.effect(+ "restores cached data in a new registry while offline, then refreshes on reconnect",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ let saved = Option.none<string>();+ const persistence: QueryPersistence<string> = {+ load: () => Effect.sync(() => saved),+ save: (_environmentId, _key, value) =>+ Effect.sync(() => {+ saved = Option.some(value);+ }),+ };+ const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {+ persistence,+ });+ const firstRegistry = yield* mountEnvironmentQuery(first.atom);+ expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");+ expect(saved).toEqual(Option.some("first"));++ const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {+ persistence,+ initialState: queryConnectionState({ phase: "offline", network: "offline" }),+ });+ const registry = yield* mountEnvironmentQuery(restarted.atom);+ expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");+ yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());+ yield* Effect.yieldNow;+ expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");+ expect(saved).toEqual(Option.some("updated"));+ }),+ ),+ );++ it.effect("keeps cached content available when revalidation fails", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const harness = yield* makeEnvironmentQueryHarness(+ Effect.fail(new TestQueryError({ message: "failed" })),+ {+ persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },+ },+ );+ const registry = yield* mountEnvironmentQuery(harness.atom);+ yield* Effect.result(readEnvironmentQuery(registry, harness.atom));+ expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");+ }),+ ),+ );++ it.effect("shows persisted data before a live request finishes", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const response = yield* Deferred.make<string>();+ const seeded = yield* Deferred.make<void>();+ const refreshed = yield* Deferred.make<void>();+ const harness = yield* makeEnvironmentQueryHarness(Deferred.await(response), {+ persistence: {+ load: () => Effect.succeedSome("cached"),+ save: () => Effect.void,+ },+ });+ const registry = yield* mountEnvironmentQuery(harness.atom);+ const unsubscribe = registry.subscribe(+ harness.atom,+ (value) => {+ if (Option.getOrNull(AsyncResult.value(value)) === "cached")+ Deferred.doneUnsafe(seeded, Exit.void);+ if (Option.getOrNull(AsyncResult.value(value)) === "fresh")+ Deferred.doneUnsafe(refreshed, Exit.void);+ },+ { immediate: true },+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));+ yield* Deferred.await(seeded);+ expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");+ yield* Deferred.succeed(response, "fresh");+ yield* Deferred.await(refreshed);+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");+ }),+ ),+ );+});diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.tsindex 5dee3aa1367..6995c0e9895 100644--- a/packages/client-runtime/src/state/runtime.ts+++ b/packages/client-runtime/src/state/runtime.ts@@ -1,3 +1,4 @@+import type { QueryPersistence } from "./queryPersistence.ts";import { createCommandPermissions } from "./commandPermissions.ts";import { followStreamInEnvironment } from "./environmentStreams.ts";export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";@@ -65,6 +66,7 @@ interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<input: Input,emit: (value: A) => Effect.Effect<void>,) => Effect.Effect<A, E, R>;+ readonly persistence?: QueryPersistence<A>;readonly staleTimeMs?: number;readonly idleTtlMs?: number;readonly refreshIntervalMs?: number;@@ -550,10 +552,6 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(target.environmentId))),);- if (connection === null) {- return Effect.never;- }- const [connectionState, session] = connection;const emit = (value: A) =>Effect.sync(() => get.setSelf(AsyncResult.success(value, { waiting: true }))).pipe(// A value set while the atom builds wins over the build's own@@ -562,29 +560,64 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(// inside the build) so the settled result arrives asynchronously.Effect.andThen(Effect.promise(() => Promise.resolve())),);- switch (connectionState.phase) {- case "connected":- return Option.isSome(session)- ? runInEnvironment(target.environmentId, options.execute(target.input, emit))- : Effect.never;- case "connecting":- case "backoff":- return Effect.never;- case "available":- case "offline":- case "blocked":- if (connectionState.lastFailure !== null) {- return Effect.fail(connectionState.lastFailure);- }- return Effect.fail(- new EnvironmentRpcUnavailableError({- environmentId: target.environmentId,- message: `Environment ${target.environmentId} is ${- connectionState.phase === "available" ? "not connected" : connectionState.phase- }.`,- }),- );- }+ const execute = (): Effect.Effect<+ A,+ | E+ | ConnectionAttemptError+ | EnvironmentRegistry.EnvironmentNotRegisteredError+ | EnvironmentRpcUnavailableError,+ | EnvironmentRegistry.EnvironmentRegistry+ | AtomRegistry.AtomRegistry+ | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>+ > => {+ if (connection === null) return Effect.never;+ const [connectionState, session] = connection;+ switch (connectionState.phase) {+ case "connected":+ return Option.isSome(session)+ ? runInEnvironment(target.environmentId, options.execute(target.input, emit))+ : Effect.never;+ case "connecting":+ case "backoff":+ return Effect.never;+ case "available":+ case "offline":+ case "blocked":+ if (connectionState.lastFailure !== null) {+ return Effect.fail(connectionState.lastFailure);+ }+ return Effect.fail(+ new EnvironmentRpcUnavailableError({+ environmentId: target.environmentId,+ message: `Environment ${target.environmentId} is ${+ connectionState.phase === "available" ? "not connected" : connectionState.phase+ }.`,+ }),+ );+ }+ };+ if (!options.persistence) return execute();+ const persistence = options.persistence;+ const cacheKey = JSON.stringify([options.label, target.input]);+ const previous = Option.flatMap(+ get.self<AsyncResult.AsyncResult<A, unknown>>(),+ AsyncResult.value,+ );+ return Effect.gen(function* () {+ const cached = Option.isSome(previous)+ ? previous+ : yield* persistence.load(target.environmentId, cacheKey);+ if (+ Option.isSome(cached) &&+ (connection === null || connection[0].phase !== "connected")+ ) {+ return cached.value;+ }+ if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);+ return yield* execute().pipe(+ Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),+ );+ });}).pipe(Atom.swr({@@ -675,6 +708,7 @@ export function createEnvironmentRpcQueryAtomFamily<EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry>;+ readonly persistence?: QueryPersistence<EnvironmentRpcSuccess<TTag>>;readonly staleTimeMs?: number;readonly idleTtlMs?: number;readonly refreshIntervalMs?: number;@@ -686,6 +720,7 @@ export function createEnvironmentRpcQueryAtomFamily<) {return createEnvironmentQueryAtomFamily(runtime, {label: options.label,+ ...(options.persistence === undefined ? {} : { persistence: options.persistence }),...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),...(options.refreshIntervalMs === undefined