diff --git a/.gitattributes b/.gitattributes index 24860868b59bc..ab74efd46bf7f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,7 +3,8 @@ # Batch files need CRLF for cmd.exe to parse them reliably. *.cmd text eol=crlf *.bat text eol=crlf -# GitHub's and Expo's GraphQL schemas and the operations graphqlgen writes from them. +# GitHub's, Linear's and Expo's GraphQL schemas and the operations graphqlgen writes from them. packages/source-control-github/schema/** linguist-generated +packages/issue-tracker-linear/schema/** linguist-generated apps/server/schema/** linguist-generated **/*.graphql.ts linguist-generated diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 356a097b4bfbc..40c84a71ad84b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,6 +110,12 @@ jobs: - name: Check generated Expo GraphQL operations run: vp run --filter t3 generate --check + - name: Check generated Linear GraphQL operations + run: vp run --filter @t3tools/issue-tracker-linear generate --check + + - name: Check i18n catalogs + run: vp run i18n:check + - name: Check run: vp check diff --git a/AGENTS.md b/AGENTS.md index f0fd0a9dfa8d1..7632479b2ab5a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,7 @@ The most common defect in this repo is a change that works on the path you teste - **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow. - **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug. - **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real. +- **Languages.** User-facing text ships in every locale: translate new keys in `apps/{web,mobile}/src/i18n/translations` after `vp run i18n:generate` (`vp run i18n:check` gates it) and in `apps/marketing/src/i18n`. - **Docs.** Check whether the change makes existing guidance inaccurate. Apply the [documentation rules](#documentation) before adding anything. ## Dev servers diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts index 04b75c9be98a1..7e140f9db5445 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.test.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -15,7 +15,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import { startFileDrag } from "./fileDrag.ts"; -it.effect("only drags existing absolute paths from the Mac host environment and app window", () => +it.effect("only drags existing absolute paths from the host environment and app window", () => Effect.gen(function* () { startDrag.mockClear(); getFileIcon.mockClear(); @@ -43,9 +43,13 @@ it.effect("only drags existing absolute paths from the Mac host environment and assert.isFalse(yield* run("host", filePath, "darwin", 2)); assert.strictEqual(startDrag.mock.calls.length, 0); assert.isTrue(yield* run("host", filePath)); - assert.deepEqual(startDrag.mock.calls, [[{ file: filePath, icon: "file-icon" }]]); + assert.isTrue(yield* run("host", filePath, "win32")); + assert.deepEqual(startDrag.mock.calls, [ + [{ file: filePath, icon: "file-icon" }], + [{ file: filePath, icon: "file-icon" }], + ]); yield* fs.remove(path.join(stateDir, "environment-id")); assert.isFalse(yield* run("host", filePath)); - assert.strictEqual(startDrag.mock.calls.length, 1); + assert.strictEqual(startDrag.mock.calls.length, 2); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts index 9701dfafcda32..227849c5935be 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -16,7 +16,8 @@ export const startFileDrag = makeIpcMethod({ result: Schema.Boolean, handler: Effect.fn("desktop.ipc.fileDrag.start")(function* (input, event) { const environment = yield* DesktopEnvironment.DesktopEnvironment; - if (environment.platform !== "darwin" || !environment.path.isAbsolute(input.path)) return false; + if (environment.platform !== "darwin" && environment.platform !== "win32") return false; + if (!environment.path.isAbsolute(input.path)) return false; const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; const window = yield* (yield* ElectronWindow.ElectronWindow).main; diff --git a/apps/mobile/assets/icons/issue.png b/apps/mobile/assets/icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/assets/icons/issue.png differ diff --git a/apps/mobile/assets/icons/issue@2x.png b/apps/mobile/assets/icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/assets/icons/issue@2x.png differ diff --git a/apps/mobile/assets/icons/issue@3x.png b/apps/mobile/assets/icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/assets/icons/issue@3x.png differ diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index caecb158e6388..8afd72b24433c 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -8,6 +8,8 @@ import "react-native-gesture-handler"; import { AppRegistry, LogBox } from "react-native"; import { featureFlags } from "react-native-screens"; +// Before any GT module initializes: GT validates locales with Intl APIs that Hermes lacks. +import "./src/i18n/intl-polyfills"; import App from "./src/App"; import { AssistantPanelRoot } from "./src/features/assistant/AssistantPanel"; diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 736f7cd3019f0..1208f3176935d 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -126,7 +126,7 @@ class T3WorkspaceNavigationView( private val onTabSelected by EventDispatcher() private val onNewThread by EventDispatcher() private val onOverlayChange by EventDispatcher() - var tabs by mutableStateOf(listOf("threads", "pullRequests", "usage", "settings")) + var tabs by mutableStateOf(listOf("threads", "pullRequests", "issues", "usage", "settings")) var selectedTab by mutableStateOf("threads") var rail by mutableStateOf(false) var floating by mutableStateOf(false) @@ -415,6 +415,7 @@ class T3WorkspaceNavigationView( private fun tabTitle(tab: String) = when (tab) { "threads" -> "Chats" "pullRequests" -> "Pulls" + "issues" -> "Issues" "usage" -> "Usage" else -> "Settings" } @@ -427,6 +428,7 @@ class T3WorkspaceNavigationView( when (tab) { "threads" -> R.drawable.t3_chats "pullRequests" -> R.drawable.t3_pull_requests + "issues" -> R.drawable.t3_issues "usage" -> R.drawable.t3_usage else -> R.drawable.t3_settings } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml new file mode 100644 index 0000000000000..14de69947215f --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec index c32f88b0dacb3..ed5fd7f091dba 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec @@ -15,6 +15,6 @@ Pod::Spec.new do |s| s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', } - s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png'] } + s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png', 'Resources/Icons/issue*.png'] } s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}' end diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index 78fd2ec1fe379..9df738d37fa67 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -40,7 +40,7 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private let composeButton = UIButton(type: .system) private lazy var tabBarTrailing = tabBar.trailingAnchor.constraint(equalTo: trailingAnchor) private var itemsByTab: [String: UITabBarItem] = [:] - var tabs = ["threads", "pullRequests", "usage", "settings"] { + var tabs = ["threads", "pullRequests", "issues", "usage", "settings"] { didSet { if tabs != oldValue { updateItems() } } } var selectedTab = "threads" { didSet { updateSelection() } } @@ -109,10 +109,11 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private func prepareItems() { let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:)) let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let labels = ["threads": "Chats", "pullRequests": "PRs", "usage": "Usage", "settings": "Settings"] + let labels = ["threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "usage": "Usage", "settings": "Settings"] + let issueIcon = UIImage(named: "issue", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"] for (tab, label) in labels { - let icon = tab == "pullRequests" ? pullRequestIcon : UIImage(systemName: symbols[tab] ?? "circle") + let icon = tab == "pullRequests" ? pullRequestIcon : tab == "issues" ? issueIcon : UIImage(systemName: symbols[tab] ?? "circle") let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0) item.accessibilityLabel = label item.accessibilityIdentifier = "workspace-tab-\(tab)" diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png new file mode 100644 index 0000000000000..1e55bbd87a57f Binary files /dev/null and b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png differ diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml new file mode 100644 index 0000000000000..8125e99ad560e --- /dev/null +++ b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml @@ -0,0 +1,4 @@ + + diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index dc0a7454d958d..e7a5ea6a02589 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -38,6 +38,11 @@ import { PullRequestReviewersScreen } from "./features/pull-requests/PullRequest import { PullRequestLabelsScreen } from "./features/pull-requests/PullRequestLabelsScreen"; import { PullRequestEditScreen } from "./features/pull-requests/PullRequestEditScreen"; import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequestFilterSearchScreen"; +import { IssueAssigneesScreen } from "./features/issues/IssueAssigneesScreen"; +import { IssueEditScreen } from "./features/issues/IssueEditScreen"; +import { IssueLabelsScreen } from "./features/issues/IssueLabelsScreen"; +import { IssueFilterSearchScreen } from "./features/issues/IssueFilterSearchScreen"; +import { IssueRouteScreen } from "./features/issues/IssueRouteScreen"; import { RenderErrorBoundary, RenderFailureView, @@ -101,6 +106,10 @@ import { SettingsDiagnosticsRouteScreen } from "./features/diagnostics/SettingsD import { SettingsProviderAccountsRouteScreen } from "./features/settings/SettingsProviderAccountsRouteScreen"; import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen"; import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen"; +import { + SettingsIssueTrackerRouteScreen, + SettingsSourceControlProviderRouteScreen, +} from "./features/settings/SettingsSourceControlDetailRouteScreens"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; import { SettingsLanguageRouteScreen } from "./features/settings/SettingsLanguageRouteScreen"; @@ -196,7 +205,15 @@ const SETTINGS_SCREENS = { SettingsEnvironmentSourceControl: createNativeStackScreen({ screen: SettingsEnvironmentSourceControlRouteScreen, linking: "settings/source-control", - options: settingsPage("Source control"), + options: settingsPage("Source control & issues"), + }), + SettingsSourceControlProvider: createNativeStackScreen({ + screen: SettingsSourceControlProviderRouteScreen, + options: settingsPage("Provider"), + }), + SettingsIssueTracker: createNativeStackScreen({ + screen: SettingsIssueTrackerRouteScreen, + options: settingsPage("Issue tracker"), }), SettingsEnvironmentAgentBehavior: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, @@ -590,6 +607,27 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: PullRequestEditScreen, options: sheetRoute({ detent: 0.75, androidFit: true }), }), + Issue: createNativeStackScreen({ + screen: IssueRouteScreen, + linking: "issues/:environmentId/:projectId/:tracker/:scope/:issueKey", + options: pageRoute({ duoMinimize: "never" }), + }), + IssueEdit: createNativeStackScreen({ + screen: IssueEditScreen, + options: sheetRoute({ detent: 0.75, androidFit: true }), + }), + IssueLabels: createNativeStackScreen({ + screen: IssueLabelsScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueAssignees: createNativeStackScreen({ + screen: IssueAssigneesScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueFilterSearch: createNativeStackScreen({ + screen: IssueFilterSearchScreen, + options: SEARCH_SHEET_ROUTE, + }), Thread: createNativeStackScreen({ screen: ThreadRouteScreen, linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] }, diff --git a/apps/mobile/src/components/ComposerSurface.tsx b/apps/mobile/src/components/ComposerSurface.tsx new file mode 100644 index 0000000000000..6d215e8cf25a1 --- /dev/null +++ b/apps/mobile/src/components/ComposerSurface.tsx @@ -0,0 +1,292 @@ +import { useState, type ReactNode } from "react"; +import { I18nManager, Platform, type ViewStyle } from "react-native"; +import Animated, { + FadeIn, + type LayoutAnimationFunction, + ReduceMotion, + useAnimatedStyle, + useDerivedValue, + useSharedValue, + withTiming, +} from "react-native-reanimated"; + +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout"; +import { useSidebarWorkspaceTabs } from "../features/layout/workspace/useSystemWorkspaceTabBar"; +import { useAndroidFloatingTabs } from "../features/settings/appearance/AppearancePreferencesProvider"; +import { compactEditorInsets } from "../features/threads/compactEditorInsets"; +import { + useDeviceType, + useDuoBottomBarInset, + useNativeLayoutMetrics, +} from "../native/native-layout-metrics"; +import type { ScaledTextRole } from "../features/settings/appearance/useScaledTextRole"; +import { cn } from "../lib/cn"; +import { useThemeRadius, useThemeRaised } from "../lib/forkThemeStyle"; +import { MOBILE_TYPOGRAPHY } from "../lib/typography"; +import { useUniwindTheme } from "../lib/useUniwindTheme"; +import { GlassSurface } from "./ui/GlassSurface"; + +const COLLAPSED_EDITOR_DEFAULT_INSET = 6; +// iOS puts line-height slack above glyphs. DM Sans's lowercase midline is +// descender (0.31em) + half x-height (0.504em) above the line bottom. +const LOWERCASE_MIDLINE_EM = 0.562; + +function lowercaseMidline(text: ScaledTextRole): number { + return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize; +} + +function collapsedEditorInset(text: ScaledTextRole): number { + const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body); + return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift)); +} + +const EXPANDED_EDITOR_INSET = 14; +// Room under the expanded editor for the toolbar row. +const EXPANDED_EDITOR_BOTTOM = 52; + +export function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) { + const [contentSize, setContentSize] = useState({ width: 0, height: 0 }); + const [compactWidth, setCompactWidth] = useState(0); + const contentHeight = contentSize.height; + const rowWidth = useSharedValue(0); + const editorX = useSharedValue(0); + const editorWidth = useSharedValue(0); + const inset = + Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text); + const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset); + const height = Math.max( + minimum, + Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset), + ); + // A line that fits the expanded editor may still overflow its compact slot. + // Compare its measured width too so widening cannot trigger a collapse loop. + const isExpanded = + value.length > 0 && + (contentHeight > text.lineHeight * 1.5 || + (compactWidth > 0 && contentSize.width > compactWidth)); + const compactRowHeight = Math.max(44, minimum); + const compactBottom = (compactRowHeight - minimum) / 2; + const isRTL = I18nManager.isRTL; + const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM; + const expansion = useDerivedValue(() => { + const target = isExpanded ? 1 : 0; + return animate + ? withTiming(target, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : target; + }); + const editorStyle = useAnimatedStyle(() => { + const compactInsets = compactEditorInsets({ + slotX: editorX.value, + slotWidth: editorWidth.value, + rowWidth: rowWidth.value, + isRTL, + }); + const progress = expansion.value; + // Hanging from the row top lets the text ride the growing edge and ignore the stale + // height measured while it still wrapped in the compact slot. Layout props only: + // Reanimated applies transforms frames ahead of layout, which tore the text from its frame. + return { + position: "absolute", + overflow: "hidden", + // The compact slot is unknown until its first layout, so the editor would draw over the + button. + opacity: isExpanded || editorWidth.value > 0 ? 1 : 0, + height, + top: compactBottom * (1 - progress), + left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress, + // Snapping the far edge keeps the line from rewrapping while the near edge moves. + right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right, + }; + }); + const containerStyle = useAnimatedStyle(() => ({ + height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value, + })); + return { + isExpanded, + containerStyle, + // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted. + // An entering animation hides it from its first frame, which a shared-value opacity cannot. + toolbarControlsEntering: + animate && isExpanded + ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2) + .duration(COMPOSER_TRANSITION_DURATION_MS / 2) + .reduceMotion(ReduceMotion.System) + : undefined, + editorStyle, + onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => { + rowWidth.set(event.nativeEvent.layout.width); + }, + onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => { + // The expanded toolbar gives this slot to the model control. Keep the + // compact geometry for the return transition, rather than recording zero. + if (!isExpanded) { + editorX.set(event.nativeEvent.layout.x); + editorWidth.set(event.nativeEvent.layout.width); + setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8)); + } + }, + editorProps: { + singleLineCentered: !isExpanded, + scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4, + contentInsetVertical: inset, + onContentSizeChange: (size: { width: number; height: number }) => { + setContentSize(size); + }, + style: { flex: 1 }, + }, + }; +} + +export const COMPOSER_TRANSITION_DURATION_MS = 220; +// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar. +const composerHeightTransition: LayoutAnimationFunction = (values) => { + "worklet"; + const timing = { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }; + return { + initialValues: { + originX: values.targetOriginX, + originY: values.currentOriginY, + width: values.targetWidth, + height: values.currentHeight, + }, + animations: { + originX: values.targetOriginX, + originY: withTiming(values.targetOriginY, timing), + width: values.targetWidth, + height: withTiming(values.targetHeight, timing), + }, + }; +}; +const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition; +// Share of the one-row composer the draft keeps; a long model name truncates first. +export const INLINE_EDITOR_MIN_WIDTH = "40%"; +const INLINE_EDITOR_HEIGHT = 36; + +const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface); + +export function ComposerSurface(props: { + readonly children: ReactNode; + readonly style: ViewStyle; + readonly animateLayout?: boolean; +}) { + const colors = useUniwindTheme(); + // Fork: a published theme sets the radius, the outline and the shadow (lib/forkThemeStyle.ts). + const targetBorderRadius = useThemeRadius( + typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0, + ); + const raised = useThemeRaised(); + const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android"; + const animatedBorderRadius = useDerivedValue(() => + shouldAnimate + ? withTiming(targetBorderRadius, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : targetBorderRadius, + ); + const borderCurve = props.style.borderCurve; + const animatedShapeStyle = useAnimatedStyle(() => ({ + borderRadius: animatedBorderRadius.value, + ...(borderCurve ? { borderCurve } : {}), + })); + const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined; + + // Animate every native frame or glass and content jump to final height inside the clip. + return ( + + + {null} + + + {props.children} + + + ); +} + +/** Space below the composer pill, inside the bottom inset it is given. */ +export const COMPOSER_BOTTOM_GUTTER = 6; + +/** Control size and pill shape: larger beside a sidebar tab picker and on iPad. */ +export function useComposerChrome() { + const { layout } = useAdaptiveWorkspaceLayout(); + const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView; + const sidebarWorkspaceTabs = useSidebarWorkspaceTabs(); + const deviceType = useDeviceType(); + const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad"; + return { + usesLargeControls, + controlSize: usesLargeControls ? ("large" as const) : ("regular" as const), + borderRadius: usesLargeControls ? 31 : 27, + paddingVertical: usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2, + }; +} + +/** + * The inset below a composer pinned to the bottom of a page. Fixed while the keyboard animates: + * changing it at keyboardDidHide makes the composer land low, then jump back above the safe area. + */ +export function useComposerBottomInset() { + const insets = useSafeAreaInsets(); + const windowMetrics = useNativeLayoutMetrics(); + const { layout } = useAdaptiveWorkspaceLayout(); + const bottomBarInset = useDuoBottomBarInset(); + const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker"; + // A pushed screen temporarily inherits the outgoing tab bar's safe area. + // Use the window edge so hiding that bar cannot move the composer mid-push. + const bottomSafeArea = + Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom; + // The pill already adds its own gutter; iPad and Duo align its edge with the native bar. + const alignedBottomInset = + bottomBarInset ?? + (Platform.OS === "ios" && Platform.isPad + ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0) + : undefined); + // The Duo's floating sidebar pill ends three points below the composer's usual gutter. + return Math.max( + 0, + (alignedBottomInset !== undefined + ? alignedBottomInset - COMPOSER_BOTTOM_GUTTER + : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0), + ); +} + +/** The editor's text style: the composer's scaled role in the theme's foreground color. */ +export function useComposerTextStyle(text: ScaledTextRole) { + return { ...text, color: useUniwindTheme()["--color-foreground"] }; +} diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index 2e8b5ff059b1e..9da08fd70e6af 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -159,6 +159,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, "arrow.branch": IconGitBranch, "arrow.left": IconArrowLeft, "arrow.right": IconArrowRight, @@ -324,6 +325,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon @@ -335,6 +337,7 @@ const SF_ICON_LOOKUP: Partial< | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsx index 146a9ccb305e7..896765db5d233 100644 --- a/apps/mobile/src/components/ui/AppSymbol.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.tsx @@ -4,6 +4,7 @@ import IconGitCommit from "@tabler/icons-react-native/IconGitCommit"; import IconGitPullRequestClosed from "@tabler/icons-react-native/IconGitPullRequestClosed"; import IconGitPullRequestDraft from "@tabler/icons-react-native/IconGitPullRequestDraft"; import type { SFSymbol } from "expo-symbols"; +import IconCircleDot from "@tabler/icons-react-native/IconCircleDot"; import IconGitPullRequest from "@tabler/icons-react-native/IconGitPullRequest"; import IconFileDiff from "@tabler/icons-react-native/IconFileDiff"; import IconRobot from "@tabler/icons-react-native/IconRobot"; @@ -23,6 +24,7 @@ const CUSTOM_ICONS = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, robot: IconRobot, }; diff --git a/apps/mobile/src/features/home/home-route-visibility.test.tsx b/apps/mobile/src/features/home/home-route-visibility.test.tsx index dae399420944a..1dba3c32a0dc3 100644 --- a/apps/mobile/src/features/home/home-route-visibility.test.tsx +++ b/apps/mobile/src/features/home/home-route-visibility.test.tsx @@ -41,6 +41,7 @@ function setup() { presented: true, selectedThreadKey: "env-1:thread-1", selectedPullRequestKey: null, + selectedIssueKey: null, }; return { registry, diff --git a/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx b/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx new file mode 100644 index 0000000000000..6d182964084a7 --- /dev/null +++ b/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx @@ -0,0 +1,106 @@ +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useAtom } from "@effect/atom-react"; +import { + issueAssigneeHeld, + issueAssigneesAfterPicks, + issuePicksAfterFailedWrite, + issuePicksFor, + issueWriteAfterPicks, + noIssuePicks, +} from "@t3tools/client-runtime/issue-selection"; +import { isSelected, toggleSelection } from "@t3tools/client-runtime/pull-request-selection"; +import type { IssueAssigneeCandidate } from "@t3tools/contracts"; +import { useEffect, useState } from "react"; + +import * as Dialog from "../../components/ui/Dialog"; +import { issueEnvironment, refreshIssueLists } from "../../state/issues"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation"; +import { IssueCandidatesSheet } from "./IssueCandidatesSheet"; +import { issueParamsKey, issueTarget, type IssueParams } from "./issueParams"; +import { issueAssigneePicksFamily } from "./issuePicks"; +import { issueCommandError, useIssueAccess } from "./issuePresentation"; + +export function IssueAssigneesScreen({ route }: StaticScreenProps) { + const navigation = useNavigation(); + const target = issueTarget(route.params); + const detail = useEnvironmentQuery(issueEnvironment.detail(target)).data; + const access = useIssueAccess(route.params, detail); + const result = useEnvironmentQuery(issueEnvironment.candidates(target)); + const update = useAtomCommand(issueEnvironment.update, { reportFailure: false }); + const [query, setQuery] = useState(""); + // The atom carries a closed sheet's picks to the next one; this sheet's own live here. + const [stored, setStored] = useAtom(issueAssigneePicksFamily(issueParamsKey(route.params))); + // Picks against an older read are dropped once, when the sheet opens. + const [picks, setPicks] = useState(() => + detail ? issuePicksFor(stored, detail, false) : noIssuePicks(), + ); + const own = detail ? issuePicksFor(picks, detail, true) : noIssuePicks(); + // What was last sent is read from the atom, so a write that fails while this sheet is open is + // sent again when it closes. + const current = { ...own, written: stored.basis === detail ? stored.written : null }; + const draft = current.draft; + const allowed = access?.assignees === true; + const held = (candidate: IssueAssigneeCandidate) => + detail ? issueAssigneeHeld(detail, candidate) : false; + const needle = query.trim().toLowerCase(); + const candidates = (result.data?.assignees ?? []).filter((candidate) => + `${candidate.login} ${candidate.name ?? ""}`.toLowerCase().includes(needle), + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed + useEffect( + () => + navigation.addListener("beforeRemove", () => { + if (!detail) return; + const assignees = issueWriteAfterPicks( + issueAssigneesAfterPicks(detail, draft), + detail.assignees.map((actor) => actor.login), + current.written, + ); + if (assignees === null) return; + const sent = { ...current, written: assignees }; + setStored(sent); + void update({ ...target, input: { ...target.input, assignees } }).then((response) => { + const failure = issueCommandError(response); + if (failure === null) return refreshIssueLists(target.environmentId); + // Picks made after this write was sent are kept. + setStored((latest) => issuePicksAfterFailedWrite(latest, sent)); + Dialog.alert("Couldn't change assignees", failure); + }); + }), + [navigation, detail, draft, current, setStored, update, target], + ); + return ( + ({ + key: candidate.id, + title: candidate.login, + ...(candidate.name ? { subtitle: candidate.name } : {}), + leading: , + // Sent when the sheet closes; a failure puts the tracker's answer back. + selected: isSelected(draft, candidate.id, held(candidate)), + }))} + allowed={allowed} + notice={ + detail && !allowed + ? (access?.blocked ?? "Changing assignees needs triage access on this tracker.") + : null + } + pending={result.isPending && !result.data} + loadError={result.data ? null : result.error} + onRetry={result.refresh} + truncated={result.data?.truncated === true} + onToggle={(id) => { + const candidate = candidates.find((entry) => entry.id === id); + if (candidate) { + setPicks({ ...current, draft: toggleSelection(draft, id, candidate, held(candidate)) }); + } + }} + /> + ); +} diff --git a/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx new file mode 100644 index 0000000000000..e4d859e2e5d71 --- /dev/null +++ b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx @@ -0,0 +1,120 @@ +import { LegendList } from "@legendapp/list/react-native"; +import type { ReactNode } from "react"; +import { Platform, View } from "react-native"; + +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { EmptyState } from "../../components/ui/EmptyState"; +import { SelectionRow } from "../../components/ui/SelectionRow"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { PullRequestSearchSheet } from "../pull-requests/PullRequestSearchSheet"; + +interface Candidate { + readonly key: string; + readonly title: string; + readonly subtitle?: string; + readonly leading: ReactNode; + readonly selected: boolean; +} + +/** The searchable checklist behind the label and assignee pickers. */ +export function IssueCandidatesSheet(props: { + readonly title: string; + readonly noun: "labels" | "people"; + readonly query: string; + readonly onQueryChange: (query: string) => void; + readonly candidates: ReadonlyArray; + readonly allowed: boolean; + readonly notice: string | null; + readonly pending: boolean; + readonly loadError: string | null; + readonly onRetry: () => void; + readonly truncated: boolean; + readonly onToggle: (key: string) => void; +}) { + const searching = props.query.trim().length > 0; + return ( + + {({ paddingBottom }) => ( + candidate.key} + extraData={props.candidates} + estimatedItemSize={64} + recycleItems + className="flex-1" + contentInsetAdjustmentBehavior="automatic" + automaticallyAdjustKeyboardInsets={Platform.OS === "ios"} + keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"} + keyboardShouldPersistTaps="handled" + showsVerticalScrollIndicator={false} + contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }} + ListHeaderComponent={ + props.notice ? ( + + {props.notice} + {props.loadError && props.candidates.length > 0 ? ( + + + + + + + + ); +} diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index a755b97994fe5..e8cef0eee58dd 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -215,6 +215,7 @@ vi.mock("../hooks/useSettings", async () => { return { useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) => select(DEFAULT_CLIENT_SETTINGS), + ensureClientSettingsHydrated: async () => {}, getClientSettings: () => DEFAULT_CLIENT_SETTINGS, }; }); diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index 570c44fb1fb3c..76247ad2ccde8 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -114,24 +114,27 @@ export function AssistantCitationCommentEditor({ ) : null}
- - + {/* Wrap as a pair so the recording pill never pushes Save alone onto a new row under Cancel. */} +
+ + +
); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index a775de5adbd50..a92de2fb3597a 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2201,7 +2201,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) toastManager.add({ type: "info", title: "Still compressing a pasted image.", - description: "Send again once its thumbnail appears.", + description: "Send again in a moment, once it finishes compressing.", }); return false; } diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index d147497a2f8e6..3836ddb850f3f 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -49,6 +49,8 @@ import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; import { TimelineRowCtx } from "./timelineRowContext"; import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; +import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; import { toastManager } from "../ui/toast"; import type { CitedHistory } from "./citationProcedure"; @@ -865,6 +867,30 @@ describe("MessagesTimeline messages", () => { expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined(); }); + it("shows the spaces typed at the start of user lines, where find also matches them", async () => { + const source = "Plan\n Step one\n\tDetail"; + await using screen = await renderTimeline([ + message(source), + message(source, { role: "assistant" }, "assistant-1"), + ]); + const [user, assistant] = screen.container.querySelectorAll( + "[data-timeline-row-kind=message]", + ); + expect(user?.querySelector("[data-user-message-body]")?.innerText).toBe(source); + expect(assistant?.querySelector(".chat-markdown")?.innerText).toBe( + "Plan Step one Detail", + ); + const query = " Step one"; + const indexed = searchableMessageSegments({ role: "user", text: source, streaming: false }); + const ranges = collectThreadFindRanges(screen.container, query); + expect(ranges.map(({ rowId, range }) => [rowId, range.toString()])).toEqual([ + [user?.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id"), query], + ]); + expect( + indexed?.reduce((count, segment) => count + countThreadSearchOccurrences(segment, query), 0), + ).toBe(ranges.length); + }); + it("keeps single tildes in user paths literal without changing double tildes or assistant text", async () => { const source = "Install the skill as ~/folder-a/skills/x, then follow the guide (~/folder-a/guide.md)."; diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx index 65a7539140494..046c3d6f40a56 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx @@ -1,11 +1,18 @@ import { RegistryContext } from "@effect/atom-react"; import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads"; -import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { + CommandId, + EnvironmentId, + MessageId, + OrchestrationV2DispatchCommandError, + ThreadId, +} from "@t3tools/contracts"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { formatComposerContextReference, toComposerContextId, } from "@t3tools/shared/composerContextReferences"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity"; @@ -16,6 +23,7 @@ import { page } from "vite-plus/test/browser"; const state = vi.hoisted(() => ({ threadState: null as unknown as Atom.Writable>, workflow: null as unknown, + commandResult: undefined as unknown, })); vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({ @@ -66,7 +74,7 @@ vi.mock(import("../../state/threads"), async (importOriginal) => { vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({ ...(await importOriginal()), - useAtomCommand: (() => async () => undefined) as never, + useAtomCommand: (() => async () => state.commandResult) as never, })); vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({ @@ -80,12 +88,14 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/th import { act, render as renderUi } from "../../../test/render"; import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures"; +import { ToastProvider } from "../ui/toast"; import { QueuedRunsControl } from "./QueuedRunsControl"; import { ExpandedImageDialog } from "./ExpandedImageDialog"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; function setup() { state.workflow = null; + state.commandResult = undefined; } const baseProps = { @@ -400,3 +410,37 @@ it("does not re-render while assistant text streams into the thread", async () = await act(() => registry.set(state.threadState, thread("Hello there", true))); expect(renders).toBeGreaterThan(settled); }); + +it("tells the user why Send now was rejected", async () => { + setup(); + const reason = "Target run run:active is stopping and cannot be steered."; + state.workflow = { + activeRun: { id: "run:active" }, + canPromoteToSteer: true, + queuedRuns: [ + { + run: { id: "run:queued", userMessageId: "message:queued" }, + text: "Follow up", + attachments: [], + }, + ], + }; + state.commandResult = AsyncResult.failure( + Cause.fail( + new OrchestrationV2DispatchCommandError({ + commandId: CommandId.make("command:promote"), + commandType: "queued-message.promote-to-steer", + message: reason, + detail: reason, + }), + ), + ); + await using _screen = await renderUi( + + + , + ); + + await page.getByRole("button", { name: "Send now" }).click(); + await vi.waitFor(() => expect(page.getByText(reason).element()).toBeVisible()); +}); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index bd8446f9212cc..767f1765a3ce6 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -1,4 +1,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { @@ -35,6 +39,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { isImageAttachment, type ChatImageAttachment, type ChatMessage } from "../../types"; import { cn } from "~/lib/utils"; import { Button, InlineButton } from "../ui/button"; +import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { objectMenuActionsProps, objectMenuProps } from "../../objectMenu"; import { ShortcutHint, ShortcutTrigger } from "../focusLevels/ShortcutHint"; @@ -177,19 +182,27 @@ export function QueuedRunsControl({ } steerInFlightRef.current = true; setBusyRunId(queuedRunId); - if (workflow?.canSendNow) { - await resumeQueue({ - environmentId: props.environmentId, - input: { threadId: props.threadId, runId: queuedRunId }, - }); - } else if (activeRun !== null) { - await promote({ - environmentId: props.environmentId, - input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, - }); - } + const result = workflow?.canSendNow + ? await resumeQueue({ + environmentId: props.environmentId, + input: { threadId: props.threadId, runId: queuedRunId }, + }) + : activeRun !== null + ? await promote({ + environmentId: props.environmentId, + input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, + }) + : null; steerInFlightRef.current = false; setBusyRunId(null); + if (result?._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Could not send queued message", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } }; useImperativeHandle(ref, () => ({ diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 5fa77615aab59..add55180cba85 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -1,6 +1,7 @@ import type { EditorId, EnvironmentId, + IssueTrackerKind, PreviewAnnotationPayload, ProjectId, ResolvedKeybindingsConfig, @@ -19,6 +20,7 @@ import { PersistentThreadTerminalPanel, type PersistentThreadTerminalPanelProps, } from "../PersistentThreadTerminals"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; import { pullRequestPanelContext } from "../pullRequest/pullRequestDetail.logic"; import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; import { PullRequestDetailGhost } from "../pullRequest/PullRequestGhosts"; @@ -79,6 +81,7 @@ export function RightPanelSurfaceContent(props: { readonly onCloseSurface: (surface: RightPanelSurface) => void; readonly terminal: RightPanelTerminalProps; readonly pullRequest: RightPanelPullRequestProps; + readonly issuesSupported: boolean; readonly files: RightPanelFileProps; readonly sideChatParentPanel: SideChatParentPanel; }) { @@ -175,6 +178,40 @@ export function RightPanelSurfaceContent(props: { /> ); } + case "issue": + if (!props.pullRequest.capabilityKnown) return ; + if (!props.issuesSupported) { + return ( + + ); + } + return ( + { + useRightPanelStore.getState().openPullRequest(threadRef, { + projectId: reference.projectId, + repository: reference.repository, + number: reference.number, + ...(reference.host ? { host: reference.host } : {}), + }); + }} + /> + ); case "pull-requests": return ; case "machines": diff --git a/apps/web/src/components/chat/SkillInlineText.tsx b/apps/web/src/components/chat/SkillInlineText.tsx index d2489e6ce2993..2691b8dafbb41 100644 --- a/apps/web/src/components/chat/SkillInlineText.tsx +++ b/apps/web/src/components/chat/SkillInlineText.tsx @@ -8,6 +8,7 @@ import { useRightPanelStore } from "~/rightPanelStore"; import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip"; import { ContextChipPopover } from "../contextChipParts"; import { Button } from "../ui/button"; +import { PopoverClose } from "../ui/popover"; import { ModelMentionChip } from "./ModelMentionChip"; function SkillInlineText(props: { @@ -135,9 +136,12 @@ export function SkillChipPopover(props: {

{props.label}

{props.description || "No description is available for this skill."}

{props.onViewInstructions ? ( - + ) : null} diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx new file mode 100644 index 0000000000000..b529cd6afe6a1 --- /dev/null +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -0,0 +1,43 @@ +import { threadIssueKeyOf, type ThreadIssueLink } from "@t3tools/contracts"; +import type { MouseEvent as ReactMouseEvent } from "react"; + +import { cn } from "~/lib/utils"; + +import { IssueGlyph } from "../issue/issuePresentation"; +import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_LABEL_CLASS, +} from "./threadDetailsPanelStyles"; + +/** + * The thread details panel's issue rows, one per linked issue, beside the pull request rows. A + * row names the issue as it was when linked and opens it in the right panel, which reads its + * live state. + */ +export function ThreadDetailsIssueRows({ + links, + onOpenLink, +}: { + links: ReadonlyArray; + onOpenLink: (event: ReactMouseEvent, link: ThreadIssueLink) => void; +}) { + if (links.length === 0) return null; + return ( + <> + {links.map((link) => ( + onOpenLink(event, link)} + > + + + {link.displayKey}: {link.title} + + + ))} + + ); +} diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index f2f41be10f958..1c3fa1a3899fc 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerKind, ProjectId, SourceControlProviderKind, ThreadId, @@ -119,6 +120,7 @@ import { act, render as renderUi } from "../../../test/render"; import { useComposerDraftStore } from "~/composerDraftStore"; import { useUiStateStore } from "~/uiStateStore"; import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow"; +import { ThreadDetailsIssueRows } from "./ThreadDetailsIssueRows"; import { ThreadDetailsThreadPrRows } from "./ThreadDetailsPrRows"; const threadRef: ScopedThreadRef = { @@ -173,7 +175,6 @@ it("merges with the last selected merge method", async () => { status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} />, ); @@ -202,7 +203,6 @@ it("requires a new merge click after passing checks become pending and pass agai status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} /> ); @@ -266,7 +266,6 @@ it("adds the failing checks to a given composer instead of opening a new thread" status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} composerTarget={threadRef} />, @@ -333,3 +332,66 @@ it.each([ `using ${expected}`, ); }); + +it("names a linked pull request row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + state.projects = [repositoryProject]; + state.pullRequests = [ + { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + linkedAt: "2026-10-30T00:00:00.000Z", + snapshot: null, + stack: null, + }, + ]; + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Test PR"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/pull request/i); + expect(name).toContain("#1"); + expect(name).toContain("Test PR"); +}); + +it("names a linked issue row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Sidebar flickers on resize"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/issue/i); + expect(name).toContain("#123"); + expect(name).toContain("Sidebar flickers on resize"); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index acf9629a10347..c067632980156 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -94,7 +94,6 @@ export function ThreadDetailsPrRow({ status, project, label, - openAriaLabel, onOpen, onActed, onStopWatching, @@ -107,7 +106,6 @@ export function ThreadDetailsPrRow({ status: PrStatusIndicator | null; project: EnvironmentProject | null; label: string; - openAriaLabel: string; onOpen: (event: ReactMouseEvent) => void; onActed?: () => void; onStopWatching?: (() => void) | undefined; @@ -265,6 +263,15 @@ export function ThreadDetailsPrRow({ ); + const stateLabel = ( + statePresentation ?? + (pr ? resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }) : null) + )?.label.toLowerCase(); + const title = (detail?.title ?? pr?.title)?.trim(); + const openAriaLabel = `${capitalizeTerm(terminology.singular)} #${number}${ + stateLabel ? `, ${stateLabel}` : "" + }${title ? `: ${title}` : ""}`; + const rowTooltip = detail === null || statePresentation === null ? ( diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx index 65f796341d3fe..31ea6c6865a4c 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx @@ -71,7 +71,6 @@ function ThreadDetailsPrLinkRow({ status={prStatusIndicator(pr, linked?.sourceControlProvider)} project={project} label={`#${link.number}${link.snapshot === null ? "" : `: ${link.snapshot.title}`}`} - openAriaLabel={link.url} onOpen={onOpen} onStopWatching={onStopWatching} composerTarget={composerTarget} @@ -207,7 +206,6 @@ export function ThreadDetailsThreadPrRows({ status={displayed.status} project={rowProject} label={`#${number}${pr?.title.trim() ? `: ${pr.title}` : ""}`} - openAriaLabel={url} onOpen={(event) => openPrLink(event, url)} composerTarget={composerTarget} {...(onActed ? { onActed } : {})} diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx index 3a32ec20400d9..c6234895025ec 100644 --- a/apps/web/src/components/chat/TimelineMinimap.tsx +++ b/apps/web/src/components/chat/TimelineMinimap.tsx @@ -186,7 +186,6 @@ export function TimelineMinimap({ onMouseDown={(event) => event.preventDefault()} type="button" > -
{items.map((item, index) => { const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`; const activeDistance = diff --git a/apps/web/src/components/chat/TimelineRowParts.tsx b/apps/web/src/components/chat/TimelineRowParts.tsx index 549b9c7a422f9..c881b845dd21a 100644 --- a/apps/web/src/components/chat/TimelineRowParts.tsx +++ b/apps/web/src/components/chat/TimelineRowParts.tsx @@ -41,14 +41,22 @@ export function TimelineRowTimestamp({ ); } -export function ActivityShimmerOverlay({ children }: { children: ReactNode }) { +export function ActivityShimmerOverlay({ + children, + className, +}: { + children: ReactNode; + className?: string; +}) { return ( - {children} + + {children} + ); diff --git a/apps/web/src/components/chat/markdownFragments.ts b/apps/web/src/components/chat/markdownFragments.ts index 90a419039053e..9acacb8c65fe2 100644 --- a/apps/web/src/components/chat/markdownFragments.ts +++ b/apps/web/src/components/chat/markdownFragments.ts @@ -68,7 +68,7 @@ type HeadingHastNode = { children?: HeadingHastNode[]; }; -function githubHeadingSlug(text: string): string { +export function githubHeadingSlug(text: string): string { return text .trim() .toLowerCase() diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx index 2574f25fc0431..38ecff7666508 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx @@ -5,16 +5,25 @@ import { } from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; import ReactMarkdown from "react-markdown"; +import remarkMath from "remark-math"; +import type { PluggableList } from "unified"; import { describe, expect, it } from "vite-plus/test"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; +import { rehypeHeadingIds } from "./markdownFragments"; + +const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. -const html = (source: string) => +const renderMarkdown = (source: string, math = false) => renderToStaticMarkup( {source} , @@ -22,9 +31,27 @@ const html = (source: string) => .replace(/>\s+<") .trim(); +const html = (source: string) => renderMarkdown(source); + +const punctuatedHeadings = ["Step 1: Install", "Done:", "apps/web", "Fix (web)", "What's next?"]; + describe("splitMarkdownBlocks", () => { it.each([ "# Title\n\nFirst paragraph with `code` and **bold**.\n\nSecond [link](https://example.com).", + "## Step 1: Install\n\n## Step 1: Install\n\n[second](#step-1-install-1)", + "## /home/a/b.ts\n\n## home/a/b.ts", + "## see https://x.com/a\n\n## see httpsxcoma", + "## Done:\n\n## Done", + "## `Setup`\n\n## Setup", + "## a ` x ` b\n\n## a x b", + "# Setup\n\n# $$ Setup $$\n\n[second](#setup-1)", + "# Setup\n\n# Setup\n\n[Second setup](#setup-1)", + "\ufeff# Setup\n\n# Setup\n\n[second](#setup-1)", + "> Setup\n> ===\n\n> Setup\n> ===", + "# onetwo\n\none\ntwo\n===", + "# Setup\n\n# Setup\n\n[second](#setup-1)", + "# Setup\n\npara\n\n- a\n\n ```\n b\nx\n\nSetup\n===\n", + "Setup\n===\n\n> ## **Setup**\n\n- # [Setup](https://example.com)\n\n```sh\n# Setup\n```", "- one\n- two\n\n- loose three\n\n continued\n\nAfter the list.", "1. first\n\n2. second\n\nText\n\n3) restarted", "```ts\nconst a = 1;\n\n\nconst b = 2;\n```\n\nafter\n\n~~~\nx\n\n~~~~\n\ny\n~~~\n\nend", @@ -39,18 +66,29 @@ describe("splitMarkdownBlocks", () => { ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => { for (let end = 0; end <= text.length; end++) { const source = text.slice(0, end); - const blocks = splitMarkdownBlocks(source); - expect(blocks?.join("")).toBe(source); - expect(blocks!.map(html).join("")).toBe(html(source)); + const blocks = splitMarkdownBlocks(source) ?? [source]; + expect(blocks.join("")).toBe(source); + expect(blocks.map(html).join("")).toBe(html(source)); + expect(blocks.map((block) => renderMarkdown(block, true)).join("")).toBe( + renderMarkdown(source, true), + ); } }); + it.each(punctuatedHeadings)("keeps splitting headings with prose punctuation: %s", (heading) => { + expect(splitMarkdownBlocks(`## ${heading}\n\nNext paragraph.`)).toEqual([ + `## ${heading}\n\n`, + "Next paragraph.", + ]); + }); + it("splits only between closed blocks", () => { expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([ "a\n\n", "```\nb\n\nc\n```\n\n- d\n\n- e\n\n", "f", ]); + expect(splitMarkdownBlocks("a\n\n---\n\nb")).toEqual(["a\n\n", "---\n\n", "b"]); }); it.each([ diff --git a/apps/web/src/components/chat/markdownStreamBlocks.ts b/apps/web/src/components/chat/markdownStreamBlocks.ts index 107d5d0143c72..36decaa301838 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.ts +++ b/apps/web/src/components/chat/markdownStreamBlocks.ts @@ -1,3 +1,5 @@ +import { githubHeadingSlug } from "./markdownFragments"; + // Definitions, footnotes, raw HTML, container directives and display math can tie blocks together. const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m; // A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span. @@ -7,13 +9,22 @@ const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/; // Claude insight fences render as one callout, so they stay in one block until the closing rule. const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; +// An ATX heading, also inside a list item or blockquote; group 1 is its text. +const ATX_HEADING_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*#{1,6}(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/; +// Setext headings may span a paragraph and containers, so leave their parsing to the renderer. +const SETEXT_UNDERLINE_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*(?:=+|-+)[ \t]*$/; /** * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it - * would inside the whole text. Returns null when the text uses syntax that spans blocks. + * would inside the whole text. Returns null when the text uses syntax that spans blocks, such as + * headings with the same slug, whose ids are numbered across the whole text. */ export function splitMarkdownBlocks(text: string): string[] | null { - if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null; + // remark-parse strips a leading BOM before recognizing the first heading. + if (text.startsWith("\ufeff") || text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) + return null; const blocks: string[] = []; let blockStart = 0; let lineStart = 0; @@ -21,11 +32,35 @@ export function splitMarkdownBlocks(text: string): string[] | null { let fenceIndent = 0; let afterBlankLine = false; let insightIndent: string | null = null; + const headingKeys = new Set(); + const needsWholeHeading = (headingText: string | undefined) => { + if (headingText === undefined) return false; + // Inline syntax and path/directive colons need the renderer before their slug is known. + if (/[`*_~[\]<&\\!$]|:(?!\s|$)/.test(headingText)) return true; + const key = githubHeadingSlug(headingText); + if (!key) return false; + if (headingKeys.has(key)) return true; + headingKeys.add(key); + return false; + }; + const headingNeedsWholeDocument = (line: string, mayUnderline = true) => + (mayUnderline && SETEXT_UNDERLINE_PATTERN.test(line)) || + needsWholeHeading(ATX_HEADING_PATTERN.exec(line)?.[1]); + // Only a line right after paragraph text can underline it; elsewhere "---" is a thematic break. + let afterContentLine = false; for (const line of text.split("\n")) { const opener = FENCE_PATTERN.exec(line)?.[1]; + const mayUnderline = afterContentLine; + afterContentLine = false; if (fence !== null) { // A line left of an indented fence may end the list item holding it, which isn't tracked. - if (/\S/.test(line.slice(0, fenceIndent))) break; + if (/\S/.test(line.slice(0, fenceIndent))) { + const rest = text.slice(lineStart).split("\n"); + for (const restLine of rest) { + if (headingNeedsWholeDocument(restLine)) return null; + } + break; + } if ( opener && opener[0] === fence[0] && @@ -40,6 +75,8 @@ export function splitMarkdownBlocks(text: string): string[] | null { } else if (line.trim() === "") { afterBlankLine = true; } else { + if (headingNeedsWholeDocument(line, mayUnderline)) return null; + afterContentLine = opener === undefined; if ( afterBlankLine && insightIndent === null && diff --git a/apps/web/src/components/chat/useThreadRightPanel.tsx b/apps/web/src/components/chat/useThreadRightPanel.tsx index aee9b798a88cb..ff17ac85620bf 100644 --- a/apps/web/src/components/chat/useThreadRightPanel.tsx +++ b/apps/web/src/components/chat/useThreadRightPanel.tsx @@ -218,6 +218,7 @@ export function useThreadRightPanel(input: { const canvasPreview = useThreadPreviewCanvasSource(activeThreadRef, shownPreviewMiniPlayer); const pullRequestsCapabilityKnown = serverConfig !== null; const supportsPullRequests = serverConfig?.environment.capabilities.pullRequests === true; + const supportsIssues = serverConfig?.environment.capabilities.issues === true; const supportsThreadPullRequests = serverConfig?.environment.capabilities.threadPullRequests === true; const visiblePullRequests = visibleThreadPullRequests(input.pullRequests); @@ -398,6 +399,7 @@ export function useThreadRightPanel(input: { terminalLabelsById: activeTerminalLabelsById, pullRequestsCapabilityKnown, supportsPullRequests, + supportsIssues, visiblePullRequests, visiblePullRequestCount, pullRequestsSurfaceAvailable, @@ -463,6 +465,7 @@ export function ThreadRightPanelView(props: { getShortcutContext={getShortcutContext} onSendAnnotation={props.onSendAnnotation} onCloseSurface={panel.closeRightPanelSurface} + issuesSupported={panel.supportsIssues} // A terminal thread screen has no composer or terminal drawer, so a side chat tab here runs // no shell commands. Revisit if terminal threads can open side chats. sideChatParentPanel={{ openToolDiff: panel.onOpenToolDiffStable, runShellCommand: () => {} }} diff --git a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx index cc3640fc2a166..40c84cc69fde6 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx @@ -1,11 +1,15 @@ -import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; +import { + FILE_PREVIEW_SCROLL_SCRIPT, + injectHtmlRenderBootstrap, + readFilePreviewScroll, +} from "@t3tools/shared/htmlRender"; import { describe, expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; -import { HtmlRenderDocument } from "./BrowserDocumentFrame"; +import { BrowserDocumentFrame, HtmlRenderDocument } from "./BrowserDocumentFrame"; const sizeChanged = (height: number) => ({ jsonrpc: "2.0", @@ -219,3 +223,98 @@ it("keeps the first and last selected card rings inside the fitted renderer fram expect(bounds.scrollWidth).toBeLessThanOrEqual(bounds.viewportWidth); } }); + +describe("BrowserDocumentFrame", () => { + it("keeps a page on screen until its next revision has loaded", async () => { + using pages = (() => { + const urls = ["first", "second", "third"].map((name) => + URL.createObjectURL(new Blob([`

${name}

`], { type: "text/html" })), + ); + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) }; + })(); + const [first, second, third] = pages.urls as [string, string, string]; + const frame = (revision: string, src: string) => ( +
+ +
+ ); + await using screen = await render(frame("1", first)); + const srcs = () => Array.from(screen.container.querySelectorAll("iframe"), (f) => f.src); + const onScreen = () => { + const box = screen.container.getBoundingClientRect(); + const hit = document.elementFromPoint(box.left + box.width / 2, box.top + 10); + return hit instanceof HTMLIFrameElement ? hit.src : null; + }; + await vi.waitFor(() => expect(onScreen()).toBe(first)); + + // The incoming frame cannot have loaded when it is inserted, so the current page must cover it. + const atInsertion = new Promise((resolve) => { + const observer = new MutationObserver(() => { + if (!srcs().includes(second)) return; + observer.disconnect(); + resolve(onScreen()); + }); + observer.observe(screen.container, { childList: true, subtree: true }); + }); + await screen.rerender(frame("2", second)); + expect(await atInsertion).toBe(first); + await vi.waitFor(() => expect(srcs()).toEqual([second])); + expect(onScreen()).toBe(second); + + await screen.rerender(frame("3", third)); + await screen.rerender(frame("2", second)); + expect(srcs(), "returning to the shown revision kept the pending frame").toEqual([second]); + await screen.rerender(frame("3", third)); + await vi.waitFor(() => expect(onScreen()).toBe(third)); + }); + + it("opens the next revision where the reader left the page", async () => { + // The first page scrolls itself, as a reader would; the second is served without scrolling. + const tall = '
report
'; + using pages = (() => { + const urls = [ + `${tall}`, + tall, + ].map((body) => + URL.createObjectURL(new Blob([body + FILE_PREVIEW_SCROLL_SCRIPT], { type: "text/html" })), + ); + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) }; + })(); + const [first, second] = pages.urls as [string, string]; + const reports: Array<{ source: MessageEventSource | null; y: number }> = []; + const onMessage = (event: MessageEvent) => { + const scroll = readFilePreviewScroll(event.data); + if (scroll !== undefined) reports.push({ source: event.source, y: scroll.y }); + }; + window.addEventListener("message", onMessage); + using _listener = { [Symbol.dispose]: () => window.removeEventListener("message", onMessage) }; + const frame = (revision: string, src: string) => ( +
+ +
+ ); + await using screen = await render(frame("1", first)); + const iframes = () => Array.from(screen.container.querySelectorAll("iframe")); + await vi.waitFor(() => expect(reports.map((report) => report.y)).toContain(1200)); + + await screen.rerender(frame("2", second)); + await vi.waitFor(() => expect(iframes().map((element) => element.src)).toEqual([second])); + const shown = iframes()[0]!.contentWindow; + expect( + reports.filter((report) => report.source === shown).map((report) => report.y), + "the next revision was uncovered before it took the reader's position", + ).toContain(1200); + }); +}); diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index 4dba7607f81c0..bfa699cf252b4 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -7,6 +7,10 @@ import { THREAD_JUMP_KEYBINDING_COMMANDS, } from "@t3tools/contracts"; import { + type FilePreviewScroll, + filePreviewRestoreScrollMessage, + isFilePreviewScrollRestored, + readFilePreviewScroll, type HtmlRenderShortcut, htmlRenderShortcutsMessage, htmlRenderThemeFragment, @@ -157,21 +161,119 @@ export function BrowserDocumentFrame(props: { className="min-h-0 flex-1" /> ) : ( - + ); } -// URL renewals must not discard form input or scroll; a new key mounts a fresh document. -function FileDocument(props: { readonly src: string; readonly title: string }) { - const [src] = useState(props.src); +interface FileDocumentRevision { + readonly key: string; + readonly src: string; +} + +interface FileDocumentFrames { + readonly shown: FileDocumentRevision; + readonly next: FileDocumentRevision | null; +} + +// Identity, not key, so a late load from a replaced frame cannot uncover a newer unloaded one. +const showRevision = + (next: FileDocumentRevision) => + (current: FileDocumentFrames): FileDocumentFrames => + current.next === next ? { shown: next, next: null } : current; + +// A page whose load never fires (a stalled subresource) must not pin the previous revision. +const FILE_DOCUMENT_SWAP_TIMEOUT_MS = 5_000; + +// URL renewals keep a revision's first URL, so they do not discard form input or scroll. A new +// revision loads beneath the page on screen, takes its scroll position and replaces it once +// painted, so no blank frame shows and the reader keeps their place. +function FileDocument(props: { + readonly documentKey: string; + readonly src: string; + readonly title: string; +}) { + const [frames, setFrames] = useState(() => ({ + shown: { key: props.documentKey, src: props.src }, + next: null, + })); + if ((frames.next ?? frames.shown).key !== props.documentKey) { + setFrames({ + shown: frames.shown, + next: + frames.shown.key === props.documentKey ? null : { key: props.documentKey, src: props.src }, + }); + } + const { next } = frames; + const shownFrame = useRef(null); + const nextFrame = useRef(null); + // The page reports its scroll position (see FILE_PREVIEW_SCROLL_SCRIPT); the next revision + // scrolls there before it is uncovered. + const scroll = useRef(null); + // Two frames let the browser paint the incoming page before it is uncovered. + const reveal = (revision: FileDocumentRevision) => + requestAnimationFrame(() => requestAnimationFrame(() => setFrames(showRevision(revision)))); + const onFrameMessage = useEffectEvent((event: MessageEvent) => { + const position = readFilePreviewScroll(event.data); + if (position !== undefined) { + if (event.source === shownFrame.current?.contentWindow) scroll.current = position; + } else if ( + next !== null && + event.source === nextFrame.current?.contentWindow && + isFilePreviewScrollRestored(event.data) + ) { + reveal(next); + } + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for the frames' scroll reports + useEffect(() => { + const onMessage = (event: MessageEvent) => onFrameMessage(event); + window.addEventListener("message", onMessage); + return () => window.removeEventListener("message", onMessage); + }, []); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- swaps in a revision whose load event never arrives + useEffect(() => { + if (next === null) return; + const timer = setTimeout(() => setFrames(showRevision(next)), FILE_DOCUMENT_SWAP_TIMEOUT_MS); + return () => clearTimeout(timer); + }, [next]); + // The shown frame stays last so it paints on top and is never moved, which would reload it. return ( -