diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 351150aa4b987..f2a92069f066b 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -6,6 +6,7 @@ import { mergePathValues, readUserLoginShell, setWindowsPath, + windowsEnvironmentValueCommand, } from "@t3tools/shared/shell"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; @@ -232,7 +233,7 @@ const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => ...names.flatMap((name) => { return [ `Write-Output '${startMarker(name)}'`, - `$value = [Environment]::GetEnvironmentVariable('${name}')`, + windowsEnvironmentValueCommand(name), "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }", `Write-Output '${endMarker(name)}'`, ]; diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift index 6732f2dae2f18..065eba4331036 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift @@ -20,6 +20,10 @@ final class T3ScrollEdgeBleedView: ExpoView { /// React Native's clipping, saved while bleeding. React Native only rewrites it when the /// `overflow` style changes, so it stays off while bleeding. private var containerClipped: Bool? + /// The bar's side is read from the root view controller, whose traits can settle after this + /// view's own during a fold; with no size change after that, nothing else would recheck. + private weak var observedWindow: UIWindow? + private var windowTraitRegistration: (any UITraitChangeRegistration)? required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -38,9 +42,33 @@ final class T3ScrollEdgeBleedView: ExpoView { override func didMoveToWindow() { super.didMoveToWindow() + observeWindowTraits() if window == nil { detach() } else { setNeedsLayout() } } + override func safeAreaInsetsDidChange() { + super.safeAreaInsetsDidChange() + setNeedsLayout() + } + + private func observeWindowTraits() { + guard observedWindow !== window else { return } + if let observedWindow, let windowTraitRegistration { + observedWindow.unregisterForTraitChanges(windowTraitRegistration) + } + observedWindow = window + windowTraitRegistration = nil + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), let window { + windowTraitRegistration = window.registerForTraitChanges( + UITraitCollection.systemTraitsAffectingVerticalBarEdge + ) { [weak self] (_: UIWindow, _: UITraitCollection) in + self?.setNeedsLayout() + } + } + #endif + } + override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) setNeedsLayout() diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx index 2d29be6d8b5ec..8957f95c8a97e 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx @@ -219,6 +219,7 @@ function setup(integrated = false) { const onDebug: NonNullable = (event) => handlePullRequestDiffDebugEvent(event, { rowCount: data.rows.length, + lastShownRowIndex: data.rows.length - 1, targetFileId, focusIndex: -1, isIos: true, diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index d72cbe743f23e..0ae3386b45b45 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -1,3 +1,8 @@ +import { + isFileDiffCollapsed, + withFileDiffFold, + type FileDiffFoldChoices, +} from "@t3tools/client-runtime/pull-request-diff-fold"; import { parsePullRequestAnchor, pullRequestAnchorMatchesUrl, @@ -130,8 +135,6 @@ import { sourceControlClients, } from "@t3tools/client-runtime/source-control-clients"; -const EMPTY_IDS: readonly string[] = []; - function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityFilter) { const navigation = useNavigation(); const result = useEnvironmentQuery(composerPullRequests.activity(requestTarget(params))); @@ -1088,7 +1091,26 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { const focusIndex = focusedRows.length ? data.rows.findIndex((row) => row.id === focusedRows[0]?.id) : -1; - const [collapsedIds, setCollapsedIds] = useState(EMPTY_IDS); + const [foldChoices, setFoldChoices] = useState(() => new Map()); + const [foldScope, setFoldScope] = useState(`${scopeKey}:${commit ?? "all"}`); + const [revealedFileId, setRevealedFileId] = useState(null); + if (foldScope !== `${scopeKey}:${commit ?? "all"}`) { + setFoldScope(`${scopeKey}:${commit ?? "all"}`); + setFoldChoices(new Map()); + setRevealedFileId(null); + } + const requestedFileId = + (jumpPath ? data.files.find((file) => file.path === jumpPath)?.id : null) ?? null; + // A linked file must stay open if its Viewed response arrives after the first native draw. + if (requestedFileId !== revealedFileId) { + setRevealedFileId(requestedFileId); + if (requestedFileId) + setFoldChoices((current) => withFileDiffFold(current, requestedFileId, false)); + } + const viewedIdSet = new Set(viewedIds); + const collapsedIds = data.files + .filter((file) => isFileDiffCollapsed(file.id, null, foldChoices, viewedIdSet.has(file.id))) + .map((file) => file.id); const [visibleFileId, setVisibleFileId] = useState(null); const nativeView = useRef(null); // The filter the current jump was made under. Hiding or showing test files replaces the rows, @@ -1114,7 +1136,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { jumpedUnder.current = null; const file = data.files.find((entry) => entry.path === path); if (!file) return; - setCollapsedIds((ids) => ids.filter((id) => id !== file.id)); + setFoldChoices((current) => withFileDiffFold(current, file.id, false)); scrollToFile(file.id); }); // Subscribed for the whole screen, so a pick made while the diff is still loading is kept for @@ -1138,9 +1160,14 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { useEffect(() => { if (!targetFile) loadMore(); }, [targetFile, loadMore]); + const lastFileRowIndex = data.rows.findLastIndex((row) => row.kind === "file"); + const lastFileId = data.rows[lastFileRowIndex]?.fileId; + const lastShownRowIndex = + lastFileId && collapsedIds.includes(lastFileId) ? lastFileRowIndex : data.rows.length - 1; const onDebug: NonNullable = (event) => handlePullRequestDiffDebugEvent(event, { rowCount: data.rows.length, + lastShownRowIndex, targetFileId: targetFile?.id, focusIndex, isIos: Platform.OS === "ios", @@ -1155,8 +1182,8 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { const onToggleFile: NonNullable = (event) => { const id = event.nativeEvent.fileId; if (!id) return; - setCollapsedIds((ids) => - ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id], + setFoldChoices((current) => + withFileDiffFold(current, id, !isFileDiffCollapsed(id, null, current, viewedIdSet.has(id))), ); }; const visibleFile = data.files.find((file) => file.id === visibleFileId) ?? targetFile; @@ -1270,7 +1297,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null }); jumpedUnder.current = null; setSelectedRowId(null); - setCollapsedIds(EMPTY_IDS); + setFoldChoices(new Map()); }} /> @@ -1311,16 +1338,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { onToggleViewedFile={(event) => { const file = data.files.find((file) => file.id === event.nativeEvent.fileId); if (!file || (!commit && !viewed.canToggle)) return; - const wasViewed = commit - ? commitViewedPaths.has(file.path) - : viewed.isViewed(file.path); - setCollapsedIds((ids) => - wasViewed - ? ids.filter((id) => id !== file.id) - : ids.includes(file.id) - ? ids - : [...ids, file.id], - ); + setFoldChoices((current) => withFileDiffFold(current, file.id, undefined)); if (commit) setCommitViewedPaths((current) => { const next = new Set(current); diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts index 23f5ba4726d62..80ccb09e50da2 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts @@ -42,9 +42,11 @@ it.each([true, false])( lastRowIndex: nativeEvent.lastRowIndex as number, }); }; + let lastShownRowIndex = 999; const emit = (nativeEvent: Record) => handlePullRequestDiffDebugEvent({ nativeEvent } as Parameters[0], { rowCount: 1000, + lastShownRowIndex, targetFileId: "last-file", focusIndex: -1, isIos, @@ -74,6 +76,10 @@ it.each([true, false])( expect(loadMore).not.toHaveBeenCalled(); emit({ message: "visible-range", firstRowIndex: 950, lastRowIndex: 990, totalRows: 1000 }); expect(loadMore).toHaveBeenCalledOnce(); + // A folded final file ends at its header, short of the full payload's tail. + lastShownRowIndex = 920; + emit({ message: "visible-range", firstRowIndex: 880, lastRowIndex: 920, totalRows: 1000 }); + expect(loadMore).toHaveBeenCalledTimes(2); } finally { scheduler.cancel(); vi.useRealTimers(); diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts index b6db266c38aa5..52fe61a65a4cc 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts @@ -21,6 +21,8 @@ export function handlePullRequestDiffDebugEvent( event: Parameters>[0], input: { readonly rowCount: number; + /** The last row native can draw: a folded final file ends at its header. */ + readonly lastShownRowIndex: number; readonly targetFileId: string | undefined; readonly focusIndex: number; readonly isIos: boolean; @@ -60,5 +62,9 @@ export function handlePullRequestDiffDebugEvent( } if (!drawn) return; const lastRow = event.nativeEvent.lastRowIndex; - if (typeof lastRow === "number" && lastRow >= input.rowCount - 40) input.loadMore(); + if ( + typeof lastRow === "number" && + lastRow >= Math.min(input.rowCount - 40, input.lastShownRowIndex) + ) + input.loadMore(); } diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 27551a83afa41..3894ab61a4af3 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -30,7 +30,6 @@ import { hasProviderUsageLimits, isUsageLimitsCommand, } from "@t3tools/shared/usageLimits"; -import { parseSideChatCommand } from "@t3tools/shared/composerTrigger"; import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native"; import type { ReactNode } from "react"; import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; @@ -101,7 +100,10 @@ import { useComposerTextRole, type ScaledTextRole } from "../settings/appearance import type { RemoteClientConnectionState } from "../../lib/connection"; import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; import { Menu } from "../../components/ui/Menu"; -import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch"; +import { + composerRunsDraftLocally, + type ActiveTurnComposerAction, +} from "@t3tools/client-runtime/state/composer-dispatch"; import type { FollowUpBehavior } from "../../lib/followUpBehavior"; import { resolveComposerSendPresentation, @@ -502,7 +504,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [previewVideo, setPreviewVideo] = useState(null); const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerDraftKey = props.draftKey ?? composerOwnerKey; - const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey); + const { + text: draftMessage, + attachments: draftAttachments, + context: draftContext, + } = useComposerDraft(composerDraftKey); const queuedEdit = props.queuedEdit ?? null; const hasContent = draftMessage.trim().length > 0 || @@ -534,18 +540,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps serverConfig: props.serverConfig, states: uploadStates, }); - const sendPresentation = resolveComposerSendPresentation({ - editingQueuedMessage: queuedEdit !== null, - // A side-chat command starts a side chat; it never queues or steers the running turn. - running: - props.activeThreadBusy && - (props.redirectsApproval || parseSideChatCommand(draftMessage) === null), - canSteer: props.canSteerActiveTurn, - followUpBehavior: props.followUpBehavior, - deliveryDeferred: - props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading, - }); - const sendLabel = sendPresentation.label; const currentModelSelection = props.selectedThread.modelSelection; const modelUnavailable = props.connectionState === "connected" && @@ -582,6 +576,25 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps props.serverConfig?.providers ?? [], props.serverConfig?.usageLimitSources ?? [], ); + const draftRunsLocally = composerRunsDraftLocally({ + text: draftMessage, + holdsOnlyText: draftAttachments.length === 0, + // A redirect's text answers its approval, so `/side` there is that text. + sideChat: !props.redirectsApproval, + usageLimits: usageLimitsOffered, + codexFeedback: selectedProviderStatus?.driver === "codex", + freshSession: props.onFreshSession !== undefined && draftContext === undefined, + }); + const sendPresentation = resolveComposerSendPresentation({ + editingQueuedMessage: queuedEdit !== null, + running: props.activeThreadBusy && !draftRunsLocally, + canSteer: props.canSteerActiveTurn, + followUpBehavior: props.followUpBehavior, + deliveryDeferred: + !draftRunsLocally && + (props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading), + }); + const sendLabel = sendPresentation.label; const openUsageLimits = () => { const report = collectProviderUsageLimits( currentModelSelection.instanceId, diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 25b8894cc8040..425a5cecac599 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -120,6 +120,7 @@ import { useBarOverlap } from "../../components/ui/useBarInset"; import { useWorkspaceContentWidth, WorkspaceSettledContentWidthContext, + useWorkspaceSettledContentWidth, } from "../layout/workspace-content-width"; import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context"; import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns"; @@ -328,12 +329,14 @@ export interface ThreadDetailScreenProps { // iOS questions overlay the controls; Android questions stack with child approvals. const ComposerPanels = Platform.OS === "android" ? Animated.ScrollView : Animated.View; -/** Hands the feed the screen width measured for a native column; elsewhere keeps the inherited one. */ +/** + * Hands the feed the screen width measured for a native column; elsewhere keeps the inherited one. + * Always the same element, so the feed below is not remounted when the width arrives. + */ function ColumnWidth(props: { readonly width: number | null; readonly children: React.ReactNode }) { - return props.width === null ? ( - props.children - ) : ( - + const inherited = useWorkspaceSettledContentWidth(); + return ( + {props.children} ); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index d3786eb4932aa..3e1ee80f2831f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -143,7 +143,10 @@ import { useFilePreviewGallery, FilePreviewGallery } from "../../components/ui/F import { assetImageSource } from "../../lib/assetImageSource"; import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery"; import { composerImageGallery } from "../../lib/composerImageGallery"; -import { isFileBackedComposerAttachment } from "../../lib/composerImages"; +import { + isFileBackedComposerAttachment, + type FileBackedComposerAttachment, +} from "../../lib/composerImages"; import { useLocalAttachmentPreview } from "../../lib/localAttachmentPreview"; import { rememberSentImage, @@ -180,7 +183,11 @@ import { import { AppText as Text } from "../../components/ui/AppText"; import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal"; import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia"; -import { attachmentVideoPreviewSource } from "../../lib/videoPreviewSource"; +import { + attachmentVideoPreviewSource, + mediaVideoThumbnailKey, + type MediaVideoPreviewSource, +} from "../../lib/videoPreviewSource"; import { CopyTextButton } from "./CopyTextButton"; import { getReviewSectionIdForCheckpoint } from "../review/reviewModel"; import { setReviewSelectedSectionId } from "../review/reviewState"; @@ -672,7 +679,6 @@ function MessageAttachmentFile(props: { readonly attachment: ChatFileAttachment; readonly onPressPreview: (source: FilePreviewSource) => void; readonly onPlaybackStart: () => void; - readonly standaloneMedia?: boolean; readonly standaloneFile?: boolean; readonly available?: boolean; }) { @@ -809,14 +815,10 @@ function MessageAttachmentFile(props: { if (videoType !== null) { return ( - + ); @@ -907,7 +909,6 @@ function UserMessageMedia(props: { ...props.pendingAttachments.map((attachment, index) => { const image = isImageAttachment(attachment); return { - id: attachment.id, image, content: image && attachment.uploadedAttachmentId ? ( @@ -921,30 +922,31 @@ function UserMessageMedia(props: { onImageLoad={(loaded) => rememberSentImage(props.messageId, index, loaded)} onPressPreview={props.onPressPreview} /> - ) : !image && attachment.uploadedAttachmentId ? ( - ) : ( - rememberSentImage(props.messageId, index, image)} onPressPreview={props.onPressPreview} - onPlaybackStart={props.onPlaybackStart} /> ), }; }), ...props.attachments.map((attachment, index) => ({ - id: attachment.id, image: isImageAttachment(attachment), content: isImageAttachment(attachment) ? ( ) : isFileAttachment(attachment) ? ( - ) : null, })), @@ -986,7 +989,8 @@ function UserMessageMedia(props: { media .filter((_, index) => index % 2 === 0) .map((item, index) => ( - + // oxlint-disable-next-line react/no-array-index-key -- delivery re-ids attachments; position is the stable identity + {item.content} {media[index * 2 + 1] ? ( {media[index * 2 + 1]!.content} @@ -998,9 +1002,10 @@ function UserMessageMedia(props: { ) : ( - {media.map((item) => ( + {media.map((item, index) => ( @@ -1015,7 +1020,7 @@ function UserMessageMedia(props: { ); } -function PendingMessageMedia(props: { +function PendingMessageImage(props: { readonly attachment: QueuedThreadMessage["attachments"][number]; readonly className: string; readonly maxWidth?: number; @@ -1023,36 +1028,70 @@ function PendingMessageMedia(props: { readonly handoff?: SentImageHandoff; readonly onImageLoad?: (image: SentImageHandoff) => void; readonly onPressPreview: (source: FilePreviewSource) => void; - readonly onPlaybackStart: () => void; }) { const withGallery = useFilePreviewGallery(); const { attachment, handoff } = props; const fileBacked = isFileBackedComposerAttachment(attachment); const preview = useLocalAttachmentPreview(fileBacked ? attachment : null); - if (isImageAttachment(attachment)) { - // The composer already showed this image; reuse its pixels and shape instead of a blank box. - const uri = - handoff?.uri ?? (fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri)); - return ( - { - if (uri) props.onImageLoad?.({ uri, aspectRatio: size.width / size.height }); - }} - onPress={() => { - const source = composerImageGallery([attachment])[0]; - if (source) props.onPressPreview(withGallery(source)); - }} - /> - ); + // The composer already showed this image; reuse its pixels and shape instead of a blank box. + const uri = + handoff?.uri ?? (fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri)); + return ( + { + if (uri) props.onImageLoad?.({ uri, aspectRatio: size.width / size.height }); + }} + onPress={() => { + const source = composerImageGallery([attachment])[0]; + if (source) props.onPressPreview(withGallery(source)); + }} + /> + ); +} + +/** + * A sent video from queueing through delivery. Every stage renders this one player under a + * thumbnail key of message and position, so swapping the local file for the server copy keeps + * the poster on screen instead of remounting to black and extracting a frame again. + */ +function UserMessageVideo(props: { + readonly environmentId: EnvironmentId; + readonly messageId: string; + readonly index: number; + readonly local: FileBackedComposerAttachment | null; + readonly uploaded: ChatFileAttachment | null; + readonly onPlaybackStart: () => void; +}) { + const sourceIdentifier = useId(); + const preview = useLocalAttachmentPreview(props.local); + const current: MediaVideoPreviewSource | null = + props.local !== null && preview.uri !== null + ? { + type: "media", + name: props.local.name, + mimeType: props.local.mimeType, + uri: preview.uri, + } + : props.uploaded !== null + ? attachmentVideoPreviewSource(props.environmentId, props.uploaded, sourceIdentifier) + : null; + // Each copy of a message reopens its local file; keep the last source while the next one loads. + const [shown, setShown] = useState(current); + if ( + current !== null && + (shown === null || mediaVideoThumbnailKey(current) !== mediaVideoThumbnailKey(shown)) + ) { + setShown(current); } - if (preview.uri === null) { + const source = current ?? shown; + if (source === null) { return ( {preview.error ? ( @@ -1065,12 +1104,8 @@ function PendingMessageMedia(props: { } return ( @@ -2824,6 +2859,10 @@ const THREAD_FEED_MAINTAIN_SCROLL_AT_END = { on: { dataChange: true, itemLayout: true, layout: true }, } as const; +// A thread switch remounts the feed. Starting from the last split pane's size lays rows out once, +// instead of at width 0 and again when the new feed's own layout reports the same width. +let lastSplitViewport: { windowWidth: number; width: number; height: number } | null = null; + export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const formatMessageTime = useMessageTimeFormatter(); const { listRef, onIsAtEndChange, onHeaderMaterialVisibilityChange } = props; @@ -2862,10 +2901,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }); const settledPaneWidth = useWorkspaceSettledContentWidth(); const splitLayout = (props.layoutVariant ?? "compact") !== "compact"; - const [measuredViewportWidth, setViewportWidth] = useState(() => (splitLayout ? 0 : windowWidth)); + const [initialSplitViewport] = useState(() => + splitLayout && lastSplitViewport?.windowWidth === windowWidth ? lastSplitViewport : null, + ); + const [measuredViewportWidth, setViewportWidth] = useState(() => + splitLayout ? (initialSplitViewport?.width ?? 0) : windowWidth, + ); const viewportWidth = settledPaneWidth !== null ? Math.round(settledPaneWidth) : measuredViewportWidth; - const [viewportHeight, setViewportHeight] = useState(0); + const [viewportHeight, setViewportHeight] = useState(() => initialSplitViewport?.height ?? 0); const [disclosureLayout, setDisclosureLayout] = useState(null); const disclosureMotionRef = useRef(null); const disclosureMotionTimer = useRef | null>(null); @@ -3467,14 +3511,26 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }; const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); const [loadedListKey, setLoadedListKey] = useState(null); - // LegendList hides rows until it has scrolled to the end, but not its header. - const settling = props.feed.length > 0 && loadedListKey !== feedThreadKey; - const handleMetricsChange = () => { + const [landedListKey, setLandedListKey] = useState(null); + // LegendList reports ready, and shows its rows, while rows measured during its initial scroll can + // still leave it hundreds of points short of the end; isAtEnd stays true through that. + const settling = props.feed.length > 0 && landedListKey !== feedThreadKey; + const landingFallback = useRef | null>(null); + const reportMetrics = (ready: boolean) => { const state = listRef.current?.getState(); + if (!state) return; + if ( + settling && + ready && + (state.distanceFromEnd <= 2 || !state.isFollowingEnd || props.jumpToMessageId) + ) { + setLandedListKey(feedThreadKey); + } // Offset 0 before the first positioning, and the gaps while rows measure in, are not the // user leaving the end; only a scroll away stops end following. - if (state) onIsAtEndChange?.(settling || state.isAtEnd || state.isFollowingEnd); + onIsAtEndChange?.(settling || state.isAtEnd || state.isFollowingEnd); }; + const handleMetricsChange = () => reportMetrics(loadedListKey === feedThreadKey); const handleScroll = (event: NativeSyntheticEvent) => { reportHeaderMaterialVisibility( event.nativeEvent.contentOffset.y + (usesNativeAutomaticInsets ? barInset : 0) > 6, @@ -3497,6 +3553,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { for (const stop of stops) stop(); }; }, [listRef, handleMetricsChange]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the landing fallback timer when the feed unmounts + useEffect( + () => () => { + if (landingFallback.current !== null) clearTimeout(landingFallback.current); + }, + [], + ); const [workGroupScrollPositions] = useState( () => new Map(), ); @@ -3567,6 +3630,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const handleViewportLayout = (event: LayoutChangeEvent) => { const nextWidth = Math.round(event.nativeEvent.layout.width); const nextHeight = Math.round(event.nativeEvent.layout.height); + if (splitLayout) lastSplitViewport = { windowWidth, width: nextWidth, height: nextHeight }; setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current)); setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current)); }; @@ -3939,7 +4003,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { { setLoadedListKey(feedThreadKey); - handleMetricsChange(); + reportMetrics(true); + // Never leave the feed hidden if end following stalls short of the end. + landingFallback.current = setTimeout(() => setLandedListKey(feedThreadKey), 1000); }} onLayout={handleMetricsChange} onItemSizeChanged={handleItemSizeChanged} onScroll={handleScroll} scrollEventThrottle={16} ListHeaderComponent={ - + <> {usesNativeAutomaticInsets ? null : } {setupAnchorIndex < 0 && props.worktreeSetup ? ( @@ -4008,7 +4074,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { {props.historyControls ? ( ) : null} - + } ListFooterComponent={ props.pendingHandoff ? ( diff --git a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx index 4d6d566f051ac..3e2d5dc05081f 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx @@ -14,6 +14,8 @@ export const ThreadMediaRetainContext = createContext<(retained: boolean) => voi export function ThreadMarkdownVideo(props: { readonly source: MediaVideoPreviewSource; + /** Keeps the player and its poster across source changes that show the same video. */ + readonly thumbnailKey?: string; readonly thumbnailVisible?: boolean; readonly onPlaybackStart?: () => void; readonly borderRadius?: number; @@ -21,7 +23,7 @@ export function ThreadMarkdownVideo(props: { const { source } = props; const feedVisible = useContext(ThreadMediaVisibleContext); const visible = props.thumbnailVisible ?? feedVisible; - const thumbnailKey = mediaVideoThumbnailKey(source); + const thumbnailKey = props.thumbnailKey ?? mediaVideoThumbnailKey(source); const asset = useAssetUrlState( "environmentId" in source ? source.environmentId : null, "resource" in source ? source.resource : null, diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.ts index b16fab3a20a90..99cabea0d5443 100644 --- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts +++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/contracts"; import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; import { + appendAcceptedThreadMessages, appendPendingThreadMessages, createThreadFeedGrouping, isCompactionCommandFeedEntry, @@ -138,6 +139,36 @@ describe("pending timeline messages", () => { expect(result[0]?.acknowledged).toBe(false); }); + it("keeps a new thread's first message attachments after delivery until the server copy loads", () => { + const video = { + id: "video-1", + type: "file" as const, + name: "clip.mp4", + mimeType: "video/mp4", + sizeBytes: 3, + fileUri: "file:///documents/clip.mp4", + }; + const creation = { + ...pending("creation"), + attachments: [video], + creation: { + projectId: ProjectId.make("project"), + workspaceMode: "worktree" as const, + branch: "main", + worktreePath: null, + }, + }; + const synthetic = { + ...appendPendingThreadMessages([], [], [creation])[0]!, + pendingMessage: undefined, + }; + // Delivered and caught up by sequence, but the server's copy is not projected yet. + const result = appendAcceptedThreadMessages([synthetic], [], creation); + expect(result).toHaveLength(1); + expect(result[0]?.pendingMessage?.attachments).toEqual([video]); + expect(result[0]?.acknowledged).toBe(true); + }); + it("retains context records while a message is waiting for delivery", () => { const record = { version: 1 as const, diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.ts index 586f8ff3b8820..940ec12db8604 100644 --- a/apps/mobile/src/features/threads/pending-thread-feed.ts +++ b/apps/mobile/src/features/threads/pending-thread-feed.ts @@ -158,6 +158,23 @@ export function appendPendingThreadMessages( ]; } +/** + * Messages the server accepted but has not projected yet. A new thread's first message stays + * anchored until the server's copy loads, and keeps its local attachments so its media does + * not drop out of the feed in between. + */ +export function appendAcceptedThreadMessages( + feed: ReadonlyArray, + acknowledged: ReadonlyArray, + creation: QueuedThreadMessage | null, +): ReadonlyArray { + const accepted = creation === null ? acknowledged : [...acknowledged, creation]; + if (accepted.length === 0) return feed; + return appendPendingThreadMessages(feed, feed, accepted).map((entry) => + entry.pendingMessage ? { ...entry, acknowledged: true } : entry, + ); +} + export function isCompactionCommandFeedEntry(entry: PendingThreadFeedEntry): boolean { return ( entry.type === "message" && diff --git a/apps/mobile/src/lib/composerAttachmentUploadQueue.ts b/apps/mobile/src/lib/composerAttachmentUploadQueue.ts index 72d3eef9c21a6..0a28fff2231d5 100644 --- a/apps/mobile/src/lib/composerAttachmentUploadQueue.ts +++ b/apps/mobile/src/lib/composerAttachmentUploadQueue.ts @@ -105,6 +105,30 @@ export function composerAttachmentsStillUploading(input: { }); } +/** Changes when an upload starts or settles, not on its progress ticks. */ +export function uploadingComposerAttachmentKeys( + states: Readonly>, +): string { + return Object.keys(states) + .filter((key) => states[key]?.status === "uploading") + .sort() + .join("\n"); +} + +/** A queued message waits for the worker's upload instead of starting a second one. */ +export function queuedAttachmentsStillUploading(input: { + readonly environmentId: EnvironmentId; + readonly attachments: ReadonlyArray; + readonly states: Readonly>; +}): boolean { + return input.attachments.some( + (attachment) => + attachment.uploadedAttachmentId === undefined && + input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)]?.status === + "uploading", + ); +} + export function createComposerAttachmentUploadQueue(options: { readonly upload: ( request: ComposerAttachmentUploadRequest, diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts index 2e1ee64831d08..9d4d7274cfd22 100644 --- a/apps/mobile/src/lib/composerContext.test.ts +++ b/apps/mobile/src/lib/composerContext.test.ts @@ -154,7 +154,7 @@ describe("mobile composer context", () => { expect(restore("deleted", initial)).toBeUndefined(); expect(restore(source)?.records).toEqual(initial.records); expect(restore("deleted")?.records ?? []).toEqual([]); - expect(createComposerContextHistory()(source)?.records).toEqual([]); + expect(createComposerContextHistory()(source)).toBeUndefined(); }); it("chips a model reference only once it is complete and names a known model", () => { const known = new Set(["model:codex/gpt-6.1"]); diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 53494209362af..d96704b9a61c2 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -233,8 +233,8 @@ export function referencedComposerContext(text: string, context?: OrchestrationM } } const records = context.records.filter((record) => ids.has(record.contextId)); - if (records.length === context.records.length) return context; - return records.length ? { version: 1 as const, records } : undefined; + if (records.length === 0) return undefined; + return records.length === context.records.length ? context : { version: 1 as const, records }; } /** Uploads change attachment ids; keep context bindings attached to the same ordered file. */ diff --git a/apps/mobile/src/state/composer-attachment-upload-states.ts b/apps/mobile/src/state/composer-attachment-upload-states.ts new file mode 100644 index 0000000000000..2dafe12ef678a --- /dev/null +++ b/apps/mobile/src/state/composer-attachment-upload-states.ts @@ -0,0 +1,8 @@ +import { Atom } from "effect/reactivity"; + +import type { ComposerAttachmentUploadState } from "../lib/composerAttachmentUploadQueue"; + +/** The upload worker's per-attachment states, apart from the worker so the outbox can read them. */ +export const composerAttachmentUploadsAtom = Atom.make< + Readonly> +>({}).pipe(Atom.keepAlive); diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts index 4a9c0d427276e..81a542a5aca1c 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.test.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts @@ -190,6 +190,7 @@ import { } from "./composer-attachment-uploads"; import { enqueueThreadOutboxMessage, + flattenQueuedThreadMessages, flushThreadOutbox, threadOutboxManager, } from "./thread-outbox"; @@ -216,6 +217,7 @@ const requestsAtom = Atom.make((get) => composerAttachmentUploadRequests({ drafts: get(drafts.composerDraftUploadSourcesAtom), queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + editingQueuedMessageIds: {}, knownEnvironmentIds: [environmentId], connectedEnvironmentIds: new Set([environmentId]), operableEnvironmentIds: new Set([environmentId]), @@ -319,6 +321,31 @@ it.each(["decode", "write"] as const)( }, ); +it("keeps an upload running when its message is sent mid-upload and records it on the message", async () => { + const transferStarted = Promise.withResolvers(); + const finishTransfer = Promise.withResolvers<{ status: number }>(); + native.transfer.mockImplementationOnce(async (uri, url) => { + native.server.set(url.split("/").at(-1)!, native.files.get(uri)!); + transferStarted.resolve(); + return finishTransfer.promise; + }); + const queue = worker(); + await transferStarted.promise; + + // Send enqueues the message, then clears the draft that owned the upload. + await enqueueThreadOutboxMessage(queuedMessage()); + drafts.clearComposerDraftContent(draftKey, { deferAttachmentCleanup: true }); + finishTransfer.resolve({ status: 204 }); + await queue.settled(); + + expect(native.transfer).toHaveBeenCalledOnce(); + expect(native.deleted).toEqual([]); + const [queued] = flattenQueuedThreadMessages( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ); + expect(queued?.attachments[0]?.uploadedAttachmentId).toBe("pending-1"); +}); + it.each(["http", "permission"] as const)( "keeps a real %s upload failure blocking Send", async (failure) => { @@ -355,6 +382,7 @@ it("uploads draft attachments for threads whose ids contain colons", () => { const requests = composerAttachmentUploadRequests({ drafts: Object.fromEntries(keys.map((key) => [key, { attachments: [{ ...image, id: key }] }])), queuedMessagesByThreadKey: {}, + editingQueuedMessageIds: {}, knownEnvironmentIds: [environmentId], connectedEnvironmentIds: new Set([environmentId]), operableEnvironmentIds: new Set([environmentId]), @@ -371,6 +399,7 @@ it("does not upload a disconnected colon environment's draft to its connected pr const requests = composerAttachmentUploadRequests({ drafts: { [`${disconnected}:thread-1`]: { attachments: [image] } }, queuedMessagesByThreadKey: {}, + editingQueuedMessageIds: {}, knownEnvironmentIds: [connected, disconnected], connectedEnvironmentIds: new Set([connected]), operableEnvironmentIds: new Set([connected]), diff --git a/apps/mobile/src/state/composer-attachment-uploads.ts b/apps/mobile/src/state/composer-attachment-uploads.ts index 0749116fa6859..8e2921c5f62d2 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.ts @@ -15,11 +15,18 @@ import { composerDraftEnvironmentId, canUploadComposerAttachment, createComposerAttachmentUploadQueue, - type ComposerAttachmentUploadState, } from "../lib/composerAttachmentUploadQueue"; import { appAtomRegistry } from "./atom-registry"; +import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states"; import { environmentServerConfigsAtom } from "./server"; -import { flattenQueuedThreadMessages, threadOutboxManager } from "./thread-outbox"; +import { + flattenQueuedThreadMessages, + threadOutboxManager, + threadOutboxRevision, + updateThreadOutboxMessage, + type QueuedThreadMessage, +} from "./thread-outbox"; +import { editingQueuedMessageIdsAtom } from "./use-thread-outbox"; import { ComposerDraftPersistenceError, type ComposerDraft, @@ -39,9 +46,7 @@ export { composerAttachmentsStillUploading, } from "../lib/composerAttachmentUploadQueue"; -export const composerAttachmentUploadsAtom = Atom.make< - Readonly> ->({}).pipe(Atom.keepAlive); +export { composerAttachmentUploadsAtom }; const uploadStateAtom = Atom.family((key: string) => Atom.map(composerAttachmentUploadsAtom, (states) => states[key]), ); @@ -69,6 +74,8 @@ type ComposerAttachmentUploadRequest = { export function composerAttachmentUploadRequests(input: { readonly drafts: Readonly>>; readonly queuedMessagesByThreadKey: Parameters[0]; + /** An edited message's attachments upload through its editor draft. */ + readonly editingQueuedMessageIds: Readonly>; /** Every environment the client knows, so a draft key never resolves to a shorter connected prefix. */ readonly knownEnvironmentIds: Iterable; readonly connectedEnvironmentIds: ReadonlySet; @@ -79,20 +86,82 @@ export function composerAttachmentUploadRequests(input: { >; }): ReadonlyArray { const queued = flattenQueuedThreadMessages(input.queuedMessagesByThreadKey); - return Object.entries(input.drafts).flatMap(([key, draft]) => { - const environmentId = composerDraftEnvironmentId(key, input.knownEnvironmentIds, queued, draft); - if ( - environmentId === null || - !input.connectedEnvironmentIds.has(environmentId) || - !input.operableEnvironmentIds.has(environmentId) - ) - return []; - return draft.attachments - .filter((attachment) => - canUploadComposerAttachment(attachment, input.serverConfigs.get(environmentId)), - ) - .map((attachment) => ({ environmentId, attachment })); - }); + const uploadable = ( + environmentId: EnvironmentId | null, + attachments: ReadonlyArray, + ): ReadonlyArray => + environmentId === null || + !input.connectedEnvironmentIds.has(environmentId) || + !input.operableEnvironmentIds.has(environmentId) + ? [] + : attachments + .filter((attachment) => + canUploadComposerAttachment(attachment, input.serverConfigs.get(environmentId)), + ) + .map((attachment) => ({ environmentId, attachment })); + return [ + ...Object.entries(input.drafts).flatMap(([key, draft]) => + uploadable( + composerDraftEnvironmentId(key, input.knownEnvironmentIds, queued, draft), + draft.attachments, + ), + ), + // Sending mid-upload hands the attachment to the outbox; requesting it here keeps that + // upload running instead of aborting it for the outbox to start over. + ...queued.flatMap((message) => + input.editingQueuedMessageIds[message.messageId] + ? [] + : uploadable( + message.environmentId, + message.attachments.filter( + (attachment) => attachment.uploadedAttachmentId === undefined, + ), + ), + ), + ]; +} + +function withUploadedAttachment( + message: QueuedThreadMessage, + uploaded: DraftComposerAttachment, +): QueuedThreadMessage | null { + const awaiting = (attachment: DraftComposerAttachment) => + attachment.id === uploaded.id && attachment.uploadedAttachmentId === undefined; + if (!message.attachments.some(awaiting)) return null; + return { + ...message, + attachments: message.attachments.map((attachment) => + awaiting(attachment) ? uploaded : attachment, + ), + }; +} + +async function recordQueuedAttachmentUpload( + environmentId: EnvironmentId, + uploaded: DraftComposerAttachment, +): Promise { + const awaiting = () => { + const editing = appAtomRegistry.get(editingQueuedMessageIdsAtom); + return flattenQueuedThreadMessages( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ).flatMap((message) => { + if (message.environmentId !== environmentId || editing[message.messageId]) return []; + const updated = withUploadedAttachment(message, uploaded); + return updated === null + ? [] + : [{ updated, revision: threadOutboxRevision(message.messageId) }]; + }); + }; + let recorded = false; + // A sibling attachment finishing at the same time bumps the revision; reread and retry. + for (let attempt = 0; attempt < 3; attempt++) { + const pending = awaiting(); + if (pending.length === 0) break; + for (const { updated, revision } of pending) { + recorded = (await updateThreadOutboxMessage(updated, revision)) || recorded; + } + } + return recorded; } // Each connected environment's session is read here so a granted or revoked @@ -116,6 +185,7 @@ const composerAttachmentUploadRequestsAtom = Atom.make((get) => { return composerAttachmentUploadRequests({ drafts: get(composerDraftUploadSourcesAtom), queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + editingQueuedMessageIds: get(editingQueuedMessageIdsAtom), knownEnvironmentIds: environments.map((environment) => environment.environmentId), connectedEnvironmentIds: new Set(connected.map((environment) => environment.environmentId)), operableEnvironmentIds, @@ -164,6 +234,7 @@ export function createComposerAttachmentUploadWorker( retained = setComposerDraftAttachmentUpload(key, uploaded) || retained; } } + retained = (await recordQueuedAttachmentUpload(environmentId, uploaded)) || retained; if (!retained) return "abandon"; // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads. await flushComposerDrafts().catch((error: unknown) => { diff --git a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts index 0d7bfdc3e8c7a..263c48195d75d 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts @@ -163,6 +163,8 @@ import { appAtomRegistry } from "./atom-registry"; import { environmentSession } from "./session"; import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox"; import { createThreadOutboxDelivery } from "./threadOutboxDelivery"; +import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states"; +import { workspaceConnections } from "./workspace"; const message = (overrides: Partial = {}): QueuedThreadMessage => ({ environmentId: EnvironmentId.make("secondary"), @@ -651,3 +653,69 @@ describe("compaction before a queued send", () => { expect(remaining()).toEqual([queued]); }); }); + +describe("queued delivery timing", () => { + /** Runs `change`, then resolves once the delivery it starts has settled. */ + async function deliveryAfter(change: () => void): Promise { + const settled = Promise.withResolvers(); + const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { + if (id === null) settled.resolve(); + }); + change(); + expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).not.toBeNull(); + await settled.promise.finally(release); + } + + it("waits for the composer's upload of a sent attachment instead of uploading it again", async () => { + setOperateGrant("secondary", true); + const photo = { + id: "photo-1", + type: "image" as const, + name: "photo.png", + mimeType: "image/png", + sizeBytes: 3, + previewUri: "file:///photo.png", + fileUri: "file:///photo.png", + }; + appAtomRegistry.set(composerAttachmentUploadsAtom, { + "secondary:photo-1": { status: "uploading", progress: 0.5 }, + }); + state.cleanups.push(() => appAtomRegistry.set(composerAttachmentUploadsAtom, {})); + await state.manager.enqueue(message({ attachments: [photo] })); + startDelivery(); + expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull(); + + await deliveryAfter(() => + appAtomRegistry.set(composerAttachmentUploadsAtom, { + "secondary:photo-1": { status: "ready" }, + }), + ); + expect(state.prepare).toHaveBeenCalledOnce(); + expect(state.start).toHaveBeenCalledOnce(); + expect(remaining()).toEqual([]); + }); + + it("sends at once when its environment reconnects instead of waiting out the backoff", async () => { + setOperateGrant("secondary", true); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + state.cleanups.push(() => vi.useRealTimers()); + const environments = workspaceConnections.environmentsAtom as unknown as Atom.Writable< + ReadonlyArray<{ environmentId: string; connectionState: string }> + >; + const connected = [{ environmentId: "secondary", connectionState: "connected" }]; + state.cleanups.push(() => appAtomRegistry.set(environments, connected)); + await state.manager.enqueue(message()); + state.start.mockResolvedValueOnce( + AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))), + ); + await runDrain(); + expect(state.start).toHaveBeenCalledOnce(); + + appAtomRegistry.set(environments, [ + { environmentId: "secondary", connectionState: "disconnected" }, + ]); + await deliveryAfter(() => appAtomRegistry.set(environments, connected)); + expect(state.start).toHaveBeenCalledTimes(2); + expect(remaining()).toEqual([]); + }); +}); diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index b3feeae3bb801..74cf7597e0ef7 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -48,6 +48,11 @@ import { } from "./pending-thread-creation"; import { environmentProjects } from "./projects"; import { environmentServerConfigsAtom, serverEnvironment } from "./server"; +import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states"; +import { + queuedAttachmentsStillUploading, + uploadingComposerAttachmentKeys, +} from "../lib/composerAttachmentUploadQueue"; import { gitEnvironment } from "./git"; import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session"; import { @@ -589,6 +594,11 @@ async function preserveUploadedAttachmentsForEditor( // Everything a drain pass decides from. Each queued environment's session is // read here so a granted or revoked operate scope re-runs the drain. +const uploadingComposerAttachmentKeysAtom = Atom.map( + composerAttachmentUploadsAtom, + uploadingComposerAttachmentKeys, +); + const deliveryInputsAtom = Atom.make((get) => { const connectedEnvironments = get(workspaceConnections.environmentsAtom); const operableEnvironments = new Set(); @@ -612,6 +622,8 @@ const deliveryInputsAtom = Atom.make((get) => { serverConfigs: get(environmentServerConfigsAtom), connectedEnvironments, operableEnvironments, + // Wakes a message waiting on the upload worker when that upload settles. + uploadingAttachmentKeys: get(uploadingComposerAttachmentKeysAtom), }; }).pipe(Atom.withLabel("mobile:thread-outbox:delivery-inputs")); @@ -691,6 +703,7 @@ export function createThreadOutboxDelivery(): { } { let disposed = false; const retries = new Map(); + let readyEnvironmentIds = new Set(); // Existing-thread turns the server accepted but whose outbox removal has // not landed; the next pass retries only the removal, never the send. const acknowledgedExistingThreadMessageIds = new Set(); @@ -1192,6 +1205,23 @@ export function createThreadOutboxDelivery(): { connectedEnvironments, operableEnvironments, } = appAtomRegistry.get(deliveryInputsAtom); + // Failures while an environment was unreachable say nothing about it now; a backoff + // started then would hold a message for up to its full delay after reconnecting. + const ready = new Set( + connectedEnvironments + .filter( + (environment) => + environment.connectionState === "connected" && + serverConfigs.has(environment.environmentId), + ) + .map((environment) => environment.environmentId), + ); + for (const message of Object.values(queuedMessagesByThreadKey).flat()) { + if (ready.has(message.environmentId) && !readyEnvironmentIds.has(message.environmentId)) { + clearRetry(message.messageId); + } + } + readyEnvironmentIds = ready; if (dispatchingQueuedMessageId !== null) { return; } @@ -1255,6 +1285,15 @@ export function createThreadOutboxDelivery(): { if (retryNotBefore(messageId) > Date.now()) { continue; } + if ( + queuedAttachmentsStillUploading({ + environmentId: nextQueuedMessage.environmentId, + attachments: nextQueuedMessage.attachments, + states: appAtomRegistry.get(composerAttachmentUploadsAtom), + }) + ) { + continue; + } let thread = findThread(threads, nextQueuedMessage); if (thread && scopedThreadKey(thread.environmentId, thread.id) !== threadKey) { diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 5796535029582..08b9e20b27f60 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -63,7 +63,7 @@ import { pruneCaughtUpAcknowledgedThreadMessages, } from "./acknowledged-thread-messages"; import { - appendPendingThreadMessages, + appendAcceptedThreadMessages, selectPendingAcknowledgedMessages, } from "../features/threads/pending-thread-feed"; import { threadAllowsProviderSwitch } from "./thread-provider-switching"; @@ -294,9 +294,10 @@ export function useThreadComposerState(input: { sequence: selectedThreadSequence, projectedMessages: selectedThreadMessages, }); - if (pendingAcknowledgments.length === 0) return feed; - return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) => - entry.pendingMessage ? { ...entry, acknowledged: true } : entry, + return appendAcceptedThreadMessages( + feed, + pendingAcknowledgments, + pendingCreation.length > 0 ? pendingCreationMessage : null, ); })(); diff --git a/apps/server/src/cloud/ConnectReachability.test.ts b/apps/server/src/cloud/ConnectReachability.test.ts index 91ef5bdc785d5..fccbfa6c4d578 100644 --- a/apps/server/src/cloud/ConnectReachability.test.ts +++ b/apps/server/src/cloud/ConnectReachability.test.ts @@ -47,7 +47,8 @@ describe("classifyReachability", () => { [{ kind: "status", status: 502 }, "origin_unreachable"], [{ kind: "status", status: 530 }, "no_connector"], [{ kind: "status", status: 530, cloudflareError: "1033" }, "no_connector"], - [{ kind: "status", status: 530, cloudflareError: "1016" }, "unexpected_response"], + [{ kind: "status", status: 530, cloudflareError: "1016" }, "dns_failed"], + [{ kind: "status", status: 530, cloudflareError: "1001" }, "unexpected_response"], [{ kind: "network_error" }, "timeout"], ] as const)("maps endpoint result %o to %s", (endpoint, cause) => { expect(classifyReachability(facts({ endpoint, edgeReachable: true }), checkedAt)).toMatchObject( @@ -209,7 +210,7 @@ describe("ConnectReachability stale connector recovery", () => { expect(yield* reachability.check).toMatchObject({ status: "reachable" }); status = 530; body = { cloudflareError: 1016 }; - expect(yield* reachability.check).toMatchObject({ cause: "unexpected_response" }); + expect(yield* reachability.check).toMatchObject({ cause: "dns_failed" }); yield* TestClock.adjust(Duration.minutes(2)); expect(yield* Queue.size(restarts)).toBe(0); diff --git a/apps/server/src/cloud/ConnectReachability.ts b/apps/server/src/cloud/ConnectReachability.ts index 77e18974dff57..c3ed37f01c91d 100644 --- a/apps/server/src/cloud/ConnectReachability.ts +++ b/apps/server/src/cloud/ConnectReachability.ts @@ -151,6 +151,13 @@ export function classifyReachability( restart, ); } + if (status === 530 && cloudflareError === "1016") { + return fail( + "dns_failed", + "The T3 Connect address no longer points to this machine's tunnel (Cloudflare error 1016). T3 Connect may have removed this environment.", + "Link this environment again. Turn T3 Connect off and on in Settings > Sharing & access, or run `t3 connect link` and then restart T3 Code.", + ); + } if (status !== null) { const code = cloudflareError === undefined ? "" : ` (Cloudflare error ${cloudflareError})`; return fail( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 1d549d7f2c18b..cf533de93e4d6 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -9472,6 +9472,20 @@ describe("ClaudeAdapterV2 background wake turns", () => { it.effect.each([ { cooldown: " (reset after 1h2m3s)", seconds: 3723 }, { cooldown: " (reset after 4m 6s) (last error: rate limited)", seconds: 246 }, + { + cooldown: + " (last error: rate_limit_error: This request would exceed your account's rate limit. Please try again later.) (reset after 19h30m2s)", + seconds: 70202, + }, + { + cooldown: + " (last error: All credentials for model upstream are cooling down (reset after 1h)) (reset after 1m)", + seconds: 60, + }, + { + cooldown: " (last error: Request rejected (429) (reset after 1h) (last error: rate limited))", + seconds: 0, + }, { cooldown: "", seconds: 0 }, ])("keeps a gateway's reset on a direct 429 with cooldown '$cooldown'", (input) => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 5dcb77f7abddc..fa8d3684f0f23 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4769,12 +4769,16 @@ function providerFailureFromResult( apiErrorStatus === 429 && message.result.startsWith("API Error:") ? gatewayCooldownResetAt( // CLIProxyAPI nests upstream errors in its message; only its own cooldown counts. - (message.result.startsWith( + message.result.startsWith( "API Error: Request rejected (429) · All credentials for model ", ) - ? /^API Error: Request rejected \(429\) · All credentials for model [^\s()]+ are cooling down \(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/ - : /\(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/ - ).exec(message.result), + ? (/^API Error: Request rejected \(429\) · All credentials for model [^\s()]+ are cooling down \(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/.exec( + message.result, + ) ?? + /^API Error: Request rejected \(429\) · All credentials for model [^\s()]+ are cooling down \(last error: [\s\S]*\) \(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)$/.exec( + message.result, + )) + : /\(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/.exec(message.result), receivedAt, ) : undefined; diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts index 346c711ba6346..857adb2c8e5c3 100644 --- a/apps/server/src/os-jank.test.ts +++ b/apps/server/src/os-jank.test.ts @@ -8,7 +8,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeOS from "node:os"; import { assert, it, vi } from "vite-plus/test"; -import { fixPath, hydratePosixHome } from "./os-jank.ts"; +import { fixPath, hydratePosixHome, refreshWindowsPath } from "./os-jank.ts"; vi.mock("node:child_process", { spy: true }); @@ -204,3 +204,20 @@ effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second assert.deepEqual(env, { PATH: "C:\\Tools;C:\\Windows" }); }), ); + +effectIt.effect("adds a directory an installer wrote to the registry after launch", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { Path: "C:\\Tools;C:\\Windows" }; + const installed = "C:\\Users\\me\\AppData\\Local\\cursor-agent"; + + yield* refreshWindowsPath().pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(WindowsShellEnvironment, () => + Effect.succeed({ PATH: `C:\\Windows;${installed}` }), + ), + ); + + assert.deepEqual(env, { PATH: `C:\\Tools;C:\\Windows;${installed}` }); + }), +); diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index d28d3f80261f4..bc6528f91a5be 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -4,10 +4,12 @@ import { extractEnvironmentValues, listLoginShellCandidates, mergePathEntries, + mergePathValues, readEnvironmentFromLoginShell, readPathFromLaunchctl, resolveWindowsEnvironment, setWindowsPath, + WindowsShellEnvironment, } from "@t3tools/shared/shell"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -217,6 +219,20 @@ export const refreshPathFromLoginShell = Effect.fn("refreshPathFromLoginShell")( } }); +// Installers write PATH to the registry, which the server's launch-time PATH never sees again. +// Returns whether PATH gained a directory. +export const refreshWindowsPath = Effect.fn("refreshWindowsPath")(function* () { + if ((yield* HostProcess.Platform) !== "win32") return false; + const env = yield* HostProcess.Environment; + const readEnvironment = yield* WindowsShellEnvironment; + const { PATH: registryPath } = yield* readEnvironment(["PATH"], { loadProfile: false }); + const currentPath = env.PATH ?? env.Path ?? env.path; + const mergedPath = mergePathValues(currentPath, registryPath, "win32"); + if (!mergedPath || mergedPath === currentPath) return false; + setWindowsPath(env, mergedPath); + return true; +}); + export const expandHomePath = Effect.fn(function* (input: string) { const { join } = yield* Path.Path; const home = yield* HostProcess.HomeDirectory; diff --git a/apps/server/src/policy/ManagedPolicy.test.ts b/apps/server/src/policy/ManagedPolicy.test.ts index d6c7710b57ead..a91cdec613095 100644 --- a/apps/server/src/policy/ManagedPolicy.test.ts +++ b/apps/server/src/policy/ManagedPolicy.test.ts @@ -193,7 +193,11 @@ it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => { ]); // The host variable that replaces Codex's launch arguments is ignored too. const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "-c mcp_servers.x.command=sh" }; - assert.deepEqual(providerHostEnvironment(policy.summary, host), { PATH: "/usr/bin" }); + const managedHost = providerHostEnvironment(policy.summary, host); + assert.deepEqual(managedHost, { PATH: "/usr/bin" }); + // A PATH refresh after launch reaches drivers that hold the managed copy. + host.PATH = "/opt/new/bin:/usr/bin"; + assert.strictEqual(managedHost.PATH, "/opt/new/bin:/usr/bin"); assert.strictEqual(providerHostEnvironment(undefined, host), host); }), ); diff --git a/apps/server/src/policy/managedProviders.ts b/apps/server/src/policy/managedProviders.ts index 059f6aeb4b782..1996aa2e11646 100644 --- a/apps/server/src/policy/managedProviders.ts +++ b/apps/server/src/policy/managedProviders.ts @@ -168,6 +168,23 @@ export const providerHostEnvironment = ( delete next[name]; } } + // Drivers keep this object, so PATH reads through to the host for a refresh after launch to reach them. + const pathKeys = Object.keys(next).filter((name) => name.toUpperCase() === "PATH"); + if (pathKeys.length > 0) { + for (const name of pathKeys) delete next[name]; + Object.defineProperty(next, "PATH", { + enumerable: true, + configurable: true, + get: () => environment.PATH ?? environment.Path ?? environment.path, + set: (value) => + Object.defineProperty(next, "PATH", { + value, + enumerable: true, + writable: true, + configurable: true, + }), + }); + } return next; }; diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index 7dcf9079f82b3..63154f4e99499 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -4,6 +4,7 @@ import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -676,9 +677,31 @@ export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(fu ); const initialize = yield* client.request("initialize", buildCodexInitializeParams()); yield* client.notify("initialized", undefined); - return { client, initialize }; + return { client, initialize, pid: child.pid }; }); +// Codex runs git (ssh for ssh URLs) for plugin marketplaces at launch and exits without waiting +// for it, so stopping a short probe mid-fetch strands ssh in an SSH-agent request. +const CODEX_STARTUP_WORK_GRACE = Duration.minutes(1); + +const codexProcessGroupIsBusy = Effect.fn("codexProcessGroupIsBusy")( + function* (pid: number) { + const { stdout } = yield* spawnAndCollect( + "pgrep", + ChildProcess.make("pgrep", ["-g", `${pid}`]), + ); + return stdout.split("\n").some((line) => line.trim() !== "" && Number(line) !== pid); + }, + Effect.orElseSucceed(() => false), +); + +const stopCodexAfterStartupWork = (pid: number, processScope: Scope.Closeable) => + codexProcessGroupIsBusy(pid).pipe( + Effect.repeat({ schedule: Schedule.spaced("500 millis"), while: (busy) => busy }), + Effect.timeoutOption(CODEX_STARTUP_WORK_GRACE), + Effect.ensuring(Scope.close(processScope, Exit.void)), + ); + // Usage is an enrichment: a failure or a slow answer degrades to "no usage this // probe" rather than costing the account and models. const readCodexRateLimits = ( @@ -713,7 +736,22 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun readonly skipNativeUsage?: boolean; }) { const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now); - const { client, initialize } = yield* withCodexAppServerClient(input); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const processScope = yield* Scope.make(); + let pid: number | undefined; + // Returning the snapshot must not wait for Codex's own startup work. + yield* Effect.addFinalizer(() => + pid === undefined + ? Scope.close(processScope, Exit.void) + : stopCodexAfterStartupWork(pid, processScope).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.forkDetach, + Effect.asVoid, + ), + ); + const opened = yield* withCodexAppServerClient(input).pipe(Scope.provide(processScope)); + pid = opened.pid; + const { client, initialize } = opened; const versionMatch = initialize.userAgent.match(/\/([^\s]+)/); const version = versionMatch ? versionMatch[1] : undefined; diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index ae51e8009645c..9ab3f56aedcd5 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -637,6 +637,15 @@ export const makeProviderInstanceRegistry = Effect.fn( (rawInstanceId) => instanceId === undefined || rawInstanceId === instanceId, undefined, ).pipe(Effect.asVoid); + const rebuild: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["rebuild"] = ( + instanceIds, + ) => + semaphore.withPermits(1)( + Ref.get(configMapRef).pipe( + Effect.flatMap((configMap) => reconcileWithR(configMap, new Set(instanceIds))), + Effect.provideContext(driverContext), + ), + ); const applySecret: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["applySecret"] = (reference, value) => reloadWhere( @@ -697,6 +706,7 @@ export const makeProviderInstanceRegistry = Effect.fn( const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = { reconcile, reloadSecrets, + rebuild, applySecret, }; diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts index 02bc92f4b4504..a9de2878a39c2 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts @@ -165,6 +165,7 @@ describe("layerSettingsWatcher", () => { const mutator = Layer.succeed(ProviderInstanceRegistryMutator, { reconcile: () => Queue.offer(reconciled, undefined), reloadSecrets: () => Effect.sync(() => void reloads++), + rebuild: () => Effect.void, applySecret: () => Effect.succeed([]), }); yield* Layer.build( diff --git a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts index 911a055d79625..a7cb5be09378a 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts @@ -11,6 +11,8 @@ export interface ProviderInstanceRegistryMutatorShape { readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect; /** Re-reads the secrets of every instance, or one, and rebuilds those whose secrets changed. */ readonly reloadSecrets: (instanceId?: ProviderInstanceId) => Effect.Effect; + /** Rebuilds these live instances from their current configuration and the host environment. */ + readonly rebuild: (instanceIds: ReadonlyArray) => Effect.Effect; /** * Rebuilds the instances that read `reference` with `value`, keeping the other secrets a live * instance holds, and returns them. A parked instance reads its other secrets from the resolver. diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 2ea6d98c083c5..021c3ddb57039 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -43,6 +43,7 @@ import { import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { WindowsShellEnvironment } from "@t3tools/shared/shell"; import { deepMerge } from "@t3tools/shared/Struct"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; @@ -2425,6 +2426,92 @@ it.layer( }), ); + it.effect( + "rebuilds only instances missing their CLI when a refresh finds a new Windows PATH", + () => { + const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows" }; + return Effect.gen(function* () { + const driver = ProviderDriverKind.make("codex"); + const makeInstance = (id: string, installed: boolean): ProviderInstance => { + const instanceId = ProviderInstanceId.make(id); + const provider = { + instanceId, + driver, + status: installed ? "ready" : "error", + enabled: true, + installed, + auth: { status: "unknown" }, + checkedAt: "1970-01-01T00:00:00.000Z", + version: null, + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + return { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: `codex:${id}` }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(provider), + refresh: Effect.succeed(provider), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + }; + const instances = [makeInstance("present", true), makeInstance("missing", false)]; + const rebuilt: Array> = []; + const changes = yield* PubSub.unbounded(); + const registry = yield* ProviderRegistry.ProviderRegistry.pipe( + Effect.provide( + ProviderRegistry.layer.pipe( + Layer.provide( + Layer.mock(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator)({ + rebuild: (ids) => Effect.sync(() => void rebuilt.push(ids)), + }), + ), + Layer.provideMerge( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: (id) => Effect.succeed(instances.find((i) => i.instanceId === id)), + listInstances: Effect.succeed(instances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }), + ), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-path-" }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ); + + yield* registry.refresh(); + + assert.strictEqual(env.PATH, "C:\\Windows;C:\\Tools"); + assert.deepStrictEqual(rebuilt, [[ProviderInstanceId.make("missing")]]); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(WindowsShellEnvironment, () => + Effect.succeed({ PATH: "C:\\Windows;C:\\Tools" }), + ), + ); + }, + ); + it.effect("rescans a requested cwd whose snapshot is still current", () => Effect.gen(function* () { const h = yield* makeWorkspaceRescanHarness; diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index f23058f1b88c5..ed51584b070e4 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -11,6 +11,7 @@ import { import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; @@ -30,6 +31,7 @@ import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderL import * as ModelManifest from "./ModelManifest.ts"; import { applyProviderCompatibility } from "./providerCompatibility.ts"; import * as ServerConfig from "../config.ts"; +import { refreshWindowsPath } from "../os-jank.ts"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import { @@ -699,6 +701,25 @@ export const layer = Layer.effect( }); type RefreshAllCompletion = Deferred.Deferred>; + // A refresh is how a user asks T3 to see a CLI installed since launch; a burst shares one probe. + // Drivers copy the environment when built, so instances still missing their CLI are rebuilt + // on the new PATH. They cannot have live sessions, and installed ones keep theirs. + const refreshHostPath = yield* refreshWindowsPath().pipe( + Effect.flatMap((changed) => + changed + ? Ref.get(providersRef).pipe( + Effect.flatMap((providers) => + instanceRegistryMutator.rebuild( + providers + .filter((provider) => provider.enabled && !provider.installed) + .map((provider) => provider.instanceId), + ), + ), + ) + : Effect.void, + ), + Effect.cachedWithTTL(Duration.seconds(10)), + ); const refreshAllInFlightRef = yield* Ref.make>( Option.none(), ); @@ -707,6 +728,7 @@ export const layer = Layer.effect( const probedManifestUpdatedAt = yield* Ref.make(initialManifest.updatedAt); const refreshAll = Effect.fn("refreshAll")(function* () { + yield* refreshHostPath; const claimed = yield* Ref.modify( refreshAllInFlightRef, ( @@ -754,16 +776,13 @@ export const layer = Layer.effect( if (provider === undefined) { return yield* refreshAll(); } - const instance = (yield* Ref.get(liveSubsRef)).get(defaultInstanceIdForDriver(provider)); - if (!instance) { - return yield* Ref.get(providersRef); - } - return yield* refreshOneSource(instance); + return yield* refreshInstance(defaultInstanceIdForDriver(provider)); }); const refreshInstance = Effect.fn("refreshInstance")(function* ( instanceId: ProviderInstanceId, ) { + yield* refreshHostPath; yield* syncLiveSourcesAndContinue; const instance = (yield* Ref.get(liveSubsRef)).get(instanceId); if (!instance) { diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 1ca1d3885b936..827acef899357 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -2419,6 +2419,34 @@ it.effect.each([ }), ); +// regression: #37633 any checkout on the host routes the read, so name the host, not the repository +it.effect("names the host when no project has a checkout on it for a host-routed read", () => + Effect.gen(function* () { + const service = yield* makeService({ + projects: [project({ id: "wrapper", title: "Wrapper", workspaceRoot: "/work" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + getChangeRequestSummary: () => Effect.die("no checkout to read through"), + }), + ], + }); + const error = yield* Effect.flip( + service.summary( + { + projectId: "wrapper" as ProjectId, + host: "gitlab.com", + repository: "acme/web", + number: 7, + }, + { recoverTransientFailure: false }, + ), + ); + assert.strictEqual(error._tag, "PullRequestUnavailableError"); + expect(error.message).not.toContain("acme/web is not a project"); + expect(error.message).toContain("gitlab.com"); + }), +); + it.effect("prefers a matching checkout over a non-repository project's directory", () => Effect.gen(function* () { const seen: string[] = []; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 92671afb75b58..592bfb92ce7cd 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1092,10 +1092,12 @@ export const make = Effect.gen(function* () { !readable.readsPublicHostWithoutCheckout && readable.servesHost?.(host) !== false ) { - return yield* new PullRequestUnavailableError({ - reason: "repository-without-project", - repository, - }); + // Without repository keys, any checkout on the host routes the read. + return yield* new PullRequestUnavailableError( + readable.repositoryKey === undefined + ? { reason: "repository-without-project", host } + : { reason: "repository-without-project", repository }, + ); } return yield* new PullRequestUnavailableError({ reason: "provider-unsupported" }); }); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index ec7393427b901..cd32eeb4a6468 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -19,6 +19,7 @@ import { getNewProjectPublishTarget, getNewProjectPublishTargets, getNewProjectRepository, + getAddProjectInitialQuery, githubIncompleteOwnerRepositoryMessage, normalizePastedCloneUrl, addProjectRemoteSourceLabel, @@ -154,7 +155,6 @@ import { } from "../lib/chatThreadActions"; import { appendBrowsePathSegment, - ensureBrowseDirectoryPath, findProjectByPath, getBrowseDirectoryPath, hasTrailingPathSeparator, @@ -683,12 +683,7 @@ function OpenCommandPaletteDialog(props: { const paletteMode = getCommandPaletteMode({ currentView, isBrowsing }); const getAddProjectInitialQueryForEnvironment = (environmentId: EnvironmentId | null): string => { const environment = environments.find((candidate) => candidate.environmentId === environmentId); - const environmentSettings = environment?.serverConfig?.settings ?? null; - const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? ""; - if (baseDirectory.length === 0) { - return "~/"; - } - return ensureBrowseDirectoryPath(baseDirectory); + return getAddProjectInitialQuery(environment?.serverConfig?.settings.addProjectBaseDirectory); }; const { projectByKey } = useProjectLookups(); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 83bd2f63883e7..be3144efb40b9 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -53,7 +53,7 @@ import * as Schema from "effect/Schema"; import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions"; import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { parseSideChatCommand, serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; +import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { type FolderDropTarget, folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; import { splitTransferredFiles } from "./workspaceFileDrop"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; @@ -253,6 +253,7 @@ import { type ComposerPromptHistoryPosition } from "./composerPromptHistory"; import { usePendingUserInputDraft } from "./usePendingThreadRequests"; import type { PendingApproval, PendingUserInput, TimelineEntry } from "../../session-logic"; import { + composerRunsDraftLocally, resolveComposerDispatchMode, type ComposerDispatchMode, } from "@t3tools/client-runtime/state/composer-dispatch"; @@ -2489,6 +2490,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // An open question owns the space above the composer. Only a machine problem, // which is why an answer could not go through, stays beside it. const replyTo = composerDraft?.replyTo ?? null; + const draftRunsLocally = composerRunsDraftLocally({ + text: prompt, + holdsOnlyText: + composerImages.length + composerFiles.length === 0 && + composerSendState.sendableTerminalContexts.length === 0 && + composerPreviewAnnotations.length === 0 && + composerReviewComments.length === 0 && + composerThreadContexts.length === 0 && + composerEnvironmentContexts.length === 0 && + replyTo === null, + sideChat: props.sideChatAvailable === true || (props.sideChatDisabledReason ?? null) !== null, + usageLimits: props.onUsageLimitsCommand !== undefined, + codexFeedback: selectedProvider === "codex" && multipleModelSelections === null, + freshSession: props.onFreshSession !== undefined, + }); const replyBannerItems: readonly ComposerBannerStackItem[] = replyTo ? [ { @@ -3737,11 +3753,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) compact={isComposerPrimaryActionsCompact} canOperateThread={canOperateThread} pendingAction={pendingPrimaryAction} - // A side-chat command starts a side chat; it never queues or steers the turn. - isRunning={ - (phase === "running" || phase === "connecting") && - !(props.sideChatAvailable === true && parseSideChatCommand(prompt) !== null) - } + isRunning={(phase === "running" || phase === "connecting") && !draftRunsLocally} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} followUpBehavior={followUpBehavior} diff --git a/apps/web/src/components/chat/ThreadFindBar.tsx b/apps/web/src/components/chat/ThreadFindBar.tsx index 466cd929a7580..5ef0485ff4f50 100644 --- a/apps/web/src/components/chat/ThreadFindBar.tsx +++ b/apps/web/src/components/chat/ThreadFindBar.tsx @@ -1,9 +1,13 @@ -import { useEffect, useRef, type KeyboardEvent } from "react"; +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; import { cn } from "~/lib/utils"; -import { formatThreadFindCount } from "./threadFind"; +import { + formatThreadFindCount, + nextThreadFindAnnouncement, + type ThreadFindAnnouncement, +} from "./threadFind"; import { THREAD_DETAILS_CARD_GAP } from "./threadDetailsCardLayout"; interface ThreadFindBarProps { @@ -14,6 +18,10 @@ interface ThreadFindBarProps { readonly status: "loading" | "error" | null; readonly onRetry: () => void; readonly activeIndex: number; + /** Bumped by each user search or step; background refreshes keep it. */ + readonly navigationId: number; + /** Whether the label shows the outcome of `navigationId`: a count or a failure. */ + readonly settled: boolean; readonly focusRequestId: number; readonly onQueryChange: (query: string) => void; readonly onNext: () => void; @@ -37,8 +45,6 @@ export function ThreadFindBar(props: ThreadFindBarProps) { props.open, ]); - if (!props.open) return null; - const hasQuery = props.query.trim().length > 0; const noResults = hasQuery && !props.status && props.matchCount === 0; let label = ""; @@ -47,6 +53,17 @@ export function ThreadFindBar(props: ThreadFindBarProps) { } if (props.status === "loading") label = "Searching…"; if (props.status === "error") label = "Search failed"; + const [storedAnnouncement, setAnnouncement] = useState(null); + const announcement = nextThreadFindAnnouncement(storedAnnouncement, { + navigationId: props.navigationId, + text: label, + settled: props.settled || props.status === "loading", + provisional: props.status !== null, + }); + if (announcement !== storedAnnouncement) setAnnouncement(announcement); + + if (!props.open) return null; + const navigationDisabled = props.matchCount === 0 || props.status === "loading" || props.counting === true; const handleKeyDown = (event: KeyboardEvent) => { @@ -87,8 +104,11 @@ export function ThreadFindBar(props: ThreadFindBarProps) { onKeyDown={handleKeyDown} /> + + {announcement.text} + & { readonly provisional?: boolean }; + +function replay(steps: readonly Step[]) { + let current: ThreadFindAnnouncement | null = null; + const spoken: string[] = []; + for (const step of steps) { + const next = nextThreadFindAnnouncement(current, { provisional: false, ...step }); + if (next.text !== (current?.text ?? "")) spoken.push(next.text); + current = next; + } + return spoken; +} + +describe("nextThreadFindAnnouncement", () => { + it("speaks each settled search or step once and stays silent through streamed refreshes", () => { + expect( + replay([ + { navigationId: 1, text: "Searching…", settled: true, provisional: true }, + { navigationId: 1, text: "1/…", settled: false }, + { navigationId: 1, text: "1/3", settled: true }, + { navigationId: 1, text: "1/…", settled: false }, + { navigationId: 1, text: "1/4", settled: true }, + { navigationId: 2, text: "1/4", settled: false }, + { navigationId: 2, text: "2/4", settled: true }, + { navigationId: 2, text: "2/5", settled: true }, + ]), + ).toEqual(["Searching…", "1/3", "2/4"]); + }); + + it("speaks a failure and the result of retrying it", () => { + expect( + replay([ + { navigationId: 1, text: "Search failed", settled: true, provisional: true }, + { navigationId: 1, text: "1/3", settled: true }, + { navigationId: 1, text: "1/4", settled: true }, + ]), + ).toEqual(["Search failed", "1/3"]); + }); + + it("speaks a new search that ends on the same count as the last one", () => { + expect( + replay([ + { navigationId: 1, text: "Searching…", settled: true, provisional: true }, + { navigationId: 1, text: "0/0", settled: true }, + { navigationId: 2, text: "Searching…", settled: true, provisional: true }, + { navigationId: 2, text: "0/0", settled: true }, + ]), + ).toEqual(["Searching…", "0/0", "Searching…", "0/0"]); + }); +}); diff --git a/apps/web/src/components/chat/threadFind.ts b/apps/web/src/components/chat/threadFind.ts index d0a265ceb13fa..98bff31c95996 100644 --- a/apps/web/src/components/chat/threadFind.ts +++ b/apps/web/src/components/chat/threadFind.ts @@ -23,3 +23,28 @@ export function stepThreadFindIndex(index: number, total: number, delta: number) export function formatThreadFindCount(index: number, total: number): string { return total <= 0 ? "0/0" : `${clampThreadFindIndex(index, total) + 1}/${total}`; } + +export interface ThreadFindAnnouncement { + readonly navigationId: number; + readonly text: string; + /** The label shows the outcome of `navigationId`: a count, a search or a failure. */ + readonly settled: boolean; + /** "Searching…" or a failure: spoken, but a later count for the same navigation is too. */ + readonly provisional: boolean; +} + +/** + * What the find counter's live region says: the settled outcome of each + * user search or step, once. Background refreshes during streaming keep the + * navigation, so they stay silent. A new query passes through "Searching…", + * so its count is spoken even when it equals the last one. + */ +export function nextThreadFindAnnouncement( + previous: ThreadFindAnnouncement | null, + next: ThreadFindAnnouncement, +): ThreadFindAnnouncement { + if (!next.settled) return previous ?? { ...next, text: "" }; + if (previous?.navigationId !== next.navigationId) return next; + if (previous.settled && !previous.provisional) return previous; + return previous.text === next.text ? previous : next; +} diff --git a/apps/web/src/components/chat/useThreadFind.ts b/apps/web/src/components/chat/useThreadFind.ts index b88951e3b6ac3..ada7955e1c2ad 100644 --- a/apps/web/src/components/chat/useThreadFind.ts +++ b/apps/web/src/components/chat/useThreadFind.ts @@ -214,6 +214,9 @@ export function useThreadFind({ counting, activeIndex, status, + navigationId: state.navigationId, + settled: + status === "error" || (status === null && !counting && navigationId === state.navigationId), focusRequestId: state.focusRequestId, onRetry: remote.refresh, onQueryChange: (query: string) => { diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 82fcd5fcbca3a..670154a009f6e 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -223,6 +223,17 @@ describe("source file focus", () => { isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}", ); await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement)); + + const findField = deepActiveElement() as HTMLInputElement; + await userEvent.keyboard("server"); + findField.blur(); + expect(focus.focus("panel", false)).toBe(true); + await vi.waitFor(editorHasFocus); + const editor = deepActiveElement() as HTMLElement; + await userEvent.keyboard("ab"); + await vi.waitFor(() => expect(editor.textContent).toContain("xabconst server")); + expect(findField.value).toBe("server"); + editorHasFocus(); }); it("focuses the editor when a file row is clicked or activated with Enter", async () => { diff --git a/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx b/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx index 2da63f3312c62..38c8e53156ecc 100644 --- a/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx +++ b/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx @@ -63,4 +63,56 @@ describe("installFileEditorDismissal", () => { expect(window.getSelection()?.toString()).toBe("Assistant reply"); }); + + it("lets clicks beside the open search panel reach the file's code", async () => { + let editor: Editor<"file" | "file-diff", undefined, undefined> | undefined; + const createEditor: EditorFactory = (...args) => + (editor = new Editor(...args)); + await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] }); + const contents = Array.from( + { length: 12 }, + (_, index) => `const server${index} = "a line long enough to run under the find bar";\n`, + ).join(""); + await using screen = await render( +
+ + + +
, + ); + const shadowRoot = screen.container.querySelector("diffs-container")?.shadowRoot; + const content = shadowRoot?.querySelector("[data-content]"); + expect(content).toBeTruthy(); + + editor!.setSelections([ + { start: { line: 0, character: 8 }, end: { line: 0, character: 8 }, direction: "none" }, + ]); + const isMac = isMacPlatform(navigator.platform); + content!.dispatchEvent( + new KeyboardEvent("keydown", { + key: "f", + code: "KeyF", + metaKey: isMac, + ctrlKey: !isMac, + bubbles: true, + composed: true, + cancelable: true, + }), + ); + const widget = await vi.waitFor(() => { + const panelHost = [...shadowRoot!.querySelectorAll("*")].find((element) => + element.shadowRoot?.querySelector("[data-search-panel]"), + ); + const found = panelHost?.shadowRoot?.querySelector("[data-editor-widget]"); + expect(found).toBeTruthy(); + return found!; + }); + const widgetBox = widget.getBoundingClientRect(); + const beside = shadowRoot!.elementFromPoint( + widgetBox.left - 100, + widgetBox.top + widgetBox.height / 2, + ); + + expect(content!.contains(beside)).toBe(true); + }); }); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 5b9d0af32a129..21f5c099a54cb 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -8,6 +8,7 @@ import { type PullRequestDiffResult, } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { __setClientSettingsForTests } from "../../hooks/useSettings"; @@ -85,7 +86,12 @@ vi.mock(import("./usePullRequestFilesViewed"), async () => { enabled: viewedPaths !== null, isViewed: (path: string) => viewedPaths?.has(path) === true, isStale: () => false, - setViewed: () => {}, + setViewed: (path: string, viewed: boolean) => { + const next = new Set(mocks.viewedPaths); + if (viewed) next.add(path); + else next.delete(path); + deliverViewedPaths(next); + }, truncated: false, error: null, refresh: () => {}, @@ -207,6 +213,52 @@ it("keeps the diff after a refresh that brings back the same page", async () => await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible(); }); +it("restores saved Viewed folds, follows cleared marks, and allows explicit expansion", async () => { + setup({ paged: false }); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + using _preferences = { + [Symbol.dispose]() { + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }, + }; + mocks.viewedPaths = new Set(["a.ts"]); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render(tab(0), { container }); + await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked(); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); + + await screen.getByRole("button", { name: "Expand diff", exact: true }).click(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + screen.getByRole("checkbox", { name: "Viewed" }).element().focus(); + await userEvent.keyboard(" "); + await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + screen.getByRole("checkbox", { name: "Viewed" }).element().focus(); + await userEvent.keyboard(" "); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); + + deliverViewedPaths(new Set()); + await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + deliverViewedPaths(new Set(["a.ts"])); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); + await screen.getByRole("button", { name: "Expand all files", exact: true }).click(); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + + await screen.rerender(
); + await screen.rerender(tab(1)); + await expect + .element(screen.getByRole("button", { name: "Expand diff", exact: true })) + .toHaveAttribute("aria-expanded", "false"); +}); + // regression: #13279 a Viewed answer that lands after a link reveals a file must not fold it it("keeps a revealed file open when its Viewed mark loads afterwards", async () => { setup({ paged: false }); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index f52f1a064277f..5acc37153d736 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,3 +1,9 @@ +import { + isFileDiffCollapsed, + withFileDiffFold, + type DiffFoldOverride, + type FileDiffFoldChoices, +} from "@t3tools/client-runtime/pull-request-diff-fold"; import { parsePullRequestAnchor, pullRequestDiffPathMatches, @@ -132,14 +138,7 @@ import { toViewerSide, } from "./PullRequestReviewAnnotation"; import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea"; -import { - getFileViewedRange, - isFileDiffCollapsed, - isLineInFileDiff, - withFileDiffFold, - type DiffFoldOverride, - type FileDiffFoldChoices, -} from "./pullRequestDiff.logic"; +import { getFileViewedRange, isLineInFileDiff } from "./pullRequestDiff.logic"; import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation"; import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState"; import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed"; @@ -439,8 +438,7 @@ function PullRequestCodeTab({ const [lastViewedFileKey, setLastViewedFileKey] = useState(null); const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); const [foldOverride, setFoldOverride] = useState(null); - const effectiveFoldOverride = - foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded"); + const effectiveFoldOverride = foldOverride ?? (settings.diffFilesCollapsed ? "folded" : null); const diffLayout = settings.diffLayout; const [wordWrapOverride, setWordWrapOverride] = useState(null); const wordWrap = wordWrapOverride ?? settings.wordWrap; @@ -932,9 +930,8 @@ function PullRequestCodeTab({
); - // A stale mark means the file changed since it was viewed; Fold all and Expand all outrank marks. const foldsAsViewed = (path: string) => - foldOverride === null && filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); + filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); const items: CodeViewDiffItem[] = annotatedFiles.map( ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { const collapsed = isFileDiffCollapsed( @@ -1007,7 +1004,11 @@ function PullRequestCodeTab({ setViewed(file.path, viewed, commit === null ? file.fileDiff.newObjectId : undefined); } setFoldChoices((current) => - range.reduce((next, file) => withFileDiffFold(next, file.fileKey, viewed), current), + range.reduce( + (next, file) => + withFileDiffFold(next, file.fileKey, effectiveFoldOverride === null ? undefined : viewed), + current, + ), ); }; const fileViewedToggle = { diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx index 912e4c6d7ac4d..222afb2b45f27 100644 --- a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx @@ -315,7 +315,7 @@ function PullRequestAuthorChoices({ {option.actor.login} {option.mergedCount > 0 ? ( - {option.mergedCount} merges loaded + {option.mergedCount} {option.mergedCount === 1 ? "merge" : "merges"} loaded ) : null}
diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts index 47f309b3e32c0..ce73f75d2db0c 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts @@ -1,12 +1,7 @@ import type { FileDiffMetadata } from "@pierre/diffs"; import { describe, expect, it } from "vite-plus/test"; -import { - getFileViewedRange, - isFileDiffCollapsed, - isLineInFileDiff, - withFileDiffFold, -} from "./pullRequestDiff.logic"; +import { getFileViewedRange, isLineInFileDiff } from "./pullRequestDiff.logic"; function fileWithHunks( hunks: ReadonlyArray<{ @@ -40,35 +35,6 @@ describe("isLineInFileDiff", () => { }); }); -describe("isFileDiffCollapsed", () => { - // regression: #9174 diffs now expand by default; a reader's fold must survive new slices - it("keeps a file the reader folded closed as the next slice arrives", () => { - const choices = new Map([["b.ts", true]]); - expect(isFileDiffCollapsed("b.ts", "expanded", choices)).toBe(true); - expect(isFileDiffCollapsed("c.ts", "expanded", choices)).toBe(false); - }); - - it("folds a file marked Viewed when the Code tab mounts again with no fold choices", () => { - expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), true)).toBe(true); - expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), false)).toBe(false); - }); - - it("keeps a reader's choice when the file's Viewed mark loads later", () => { - const choices = new Map([["a.ts", false]]); - expect(isFileDiffCollapsed("a.ts", "expanded", choices, false)).toBe(false); - expect(isFileDiffCollapsed("a.ts", "expanded", choices, true)).toBe(false); - }); -}); - -describe("withFileDiffFold", () => { - it("records an absolute choice and keeps the same map when nothing changes", () => { - const folded = withFileDiffFold(new Map(), "a.ts", true); - expect(folded.get("a.ts")).toBe(true); - expect(withFileDiffFold(folded, "a.ts", true)).toBe(folded); - expect(withFileDiffFold(folded, "a.ts", false).get("a.ts")).toBe(false); - }); -}); - describe("getFileViewedRange", () => { const files = ["c.ts", "a.ts", "b.ts", "d.ts"].map((fileKey) => ({ fileKey })); diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts index da3844e90e1bb..f0c01a0611c3b 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts @@ -14,33 +14,6 @@ export function isLineInFileDiff( ); } -export type DiffFoldOverride = "expanded" | "folded" | null; - -/** The reader's own fold choice per file. It is absolute, so a Viewed mark loading later keeps it. */ -export type FileDiffFoldChoices = ReadonlyMap; - -/** - * A reader's own choice wins. Otherwise the toolbar decides, and a file still marked Viewed - * starts folded. Fold all and Expand all clear the choices, so later pages follow the toolbar. - */ -export function isFileDiffCollapsed( - fileKey: string, - foldOverride: DiffFoldOverride, - choices: FileDiffFoldChoices, - viewed = false, -): boolean { - return choices.get(fileKey) ?? (foldOverride === "folded" || viewed); -} - -export function withFileDiffFold( - choices: FileDiffFoldChoices, - fileKey: string, - collapsed: boolean, -): FileDiffFoldChoices { - if (choices.get(fileKey) === collapsed) return choices; - return new Map(choices).set(fileKey, collapsed); -} - export function getFileViewedRange( files: ReadonlyArray, fileKey: string, diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index acaca34e332b6..0cde5b8f1f477 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -65,15 +65,20 @@ describe("ThemeImportDialog", () => { }); }); -const theme = (name: string, accent = "#3b82f6") => ({ +const theme = (name: string, accent = "#3b82f6", css?: string) => ({ version: THEME_FILE_VERSION, name, appearance: "dark", colors: { accent }, + ...(css ? { css } : {}), }); -const themeFile = (name: string, accent?: string) => - new File([JSON.stringify(theme(name, accent))], `${name}.json`, { type: "application/json" }); +const themeFile = (name: string, accent?: string, css?: string) => + new File([JSON.stringify(theme(name, accent, css))], `${name}.json`, { + type: "application/json", + }); + +const DUSK_CSS = ".chat-header { height: 3rem; }"; it.each(["Update existing", "Keep both"])( "keeps batch failures visible after %s", @@ -97,7 +102,7 @@ it.each(["Update existing", "Keep both"])( const input = document.querySelector('input[type="file"]')!; await userEvent.upload(input, [ themeFile("Dawn"), - themeFile("Dusk", "#f97316"), + themeFile("Dusk", "#f97316", DUSK_CSS), new File(["{"], "broken.json", { type: "application/json" }), ]); @@ -107,9 +112,10 @@ it.each(["Update existing", "Keep both"])( await page.getByRole("button", { name: choice }).click(); invalidateCustomThemes(); const label = choice === "Update existing" ? "Dusk" : "Dusk (1)"; - expect(getCustomThemes().find((theme) => theme.label === label)?.colors).toEqual( - parseThemeFile(theme("Dusk", "#f97316")).colors, - ); + expect(getCustomThemes().find((theme) => theme.label === label)).toMatchObject({ + colors: parseThemeFile(theme("Dusk", "#f97316")).colors, + css: DUSK_CSS, + }); await expect.element(page.getByText(/^broken\.json:/)).toBeVisible(); expect(onOpenChange).not.toHaveBeenCalledWith(false); }, diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index dc093d55b65c9..17fb7b43daae0 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -39,6 +39,10 @@ function describeOversizedThemeFile(bytes: number): string | null { return `That file is ${formatBytes(bytes)}. Theme files are only a few KB, so this one was not read (limit ${formatBytes(MAX_THEME_FILE_BYTES)}).`; } +function isThemeIdTaken(themeId: string): boolean { + return getCustomThemes().some((existing) => existing.id === themeId); +} + function escapeJsonHtml(value: string): string { return value.replace( /[&<>"']/g, @@ -264,7 +268,7 @@ function ThemeImportBody({ const installed: ThemeDefinition[] = []; const conflicting: ThemeDefinition[] = []; for (const theme of pairVsCodeThemes(resolveThemeLabelCollisions(parsed))) { - if (getCustomThemes().some((existing) => existing.id === theme.id)) { + if (isThemeIdTaken(theme.id)) { conflicting.push(theme); continue; } @@ -325,28 +329,24 @@ function ThemeImportBody({ theme: ThemeDefinition, preferredName?: string | null, ): ThemeDefinition => { - if (preferredName && preferredName.toLowerCase() !== theme.label.toLowerCase()) { - const candidate = parseThemeFile({ + // The collection stays behind: updating a collection replaces every theme in it. + const copyNamed = (name: string) => + parseThemeFile({ version: THEME_FILE_VERSION, - name: preferredName.slice(0, 48), + name, appearance: theme.appearance, colors: theme.colors, ...(theme.variants ? { variants: theme.variants } : {}), ...(theme.managed ? { managed: true } : {}), + ...(theme.css ? { css: theme.css } : {}), }); - if (!getCustomThemes().some((existing) => existing.id === candidate.id)) return candidate; + if (preferredName && preferredName.toLowerCase() !== theme.label.toLowerCase()) { + const candidate = copyNamed(preferredName.slice(0, 48)); + if (!isThemeIdTaken(candidate.id)) return candidate; } for (let copy = 1; copy < 100; copy += 1) { - const candidate = parseThemeFile({ - version: THEME_FILE_VERSION, - name: `${theme.label.slice(0, 48 - ` (${copy})`.length)} (${copy})`, - appearance: theme.appearance, - colors: theme.colors, - ...(theme.variants ? { variants: theme.variants } : {}), - ...(theme.managed ? { managed: true } : {}), - }); - if (getCustomThemes().some((existing) => existing.id === candidate.id)) continue; - return candidate; + const candidate = copyNamed(`${theme.label.slice(0, 48 - ` (${copy})`.length)} (${copy})`); + if (!isThemeIdTaken(candidate.id)) return candidate; } throw new Error(`Too many copies of "${theme.label}".`); }; @@ -391,7 +391,7 @@ function ThemeImportBody({ } try { const theme = parseThemeImport(json); - if (getCustomThemes().some((existing) => existing.id === theme.id)) { + if (isThemeIdTaken(theme.id)) { setError(null); setConflicts([theme]); return; diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsx index 005654db7bdd7..05baa4b626496 100644 --- a/apps/web/src/components/ui/popover.tsx +++ b/apps/web/src/components/ui/popover.tsx @@ -94,6 +94,8 @@ function PopoverPopup({ className={cn( "relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) rounded-lg text-popover-foreground outline-none transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] has-data-[slot=calendar]:rounded-xl has-data-[slot=calendar]:before:rounded-[calc(var(--radius-xl)-1px)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]", variant !== "panel" && "dropdown-glass", + // Without it, Chromium re-snaps text after the scale-in at fractional zoom, so hovered rows jump a pixel. + "will-change-[scale]", // Electron drag hit-testing ignores z-index; popups over a drag region would swallow hover. "[-webkit-app-region:no-drag]", tooltipStyle && diff --git a/docs/user/t3-connect-troubleshooting.md b/docs/user/t3-connect-troubleshooting.md index 2b3b9deaf5ea4..6dadd78be3032 100644 --- a/docs/user/t3-connect-troubleshooting.md +++ b/docs/user/t3-connect-troubleshooting.md @@ -80,6 +80,10 @@ Fix: 3. If the check fails only on the host, check the host's DNS, VPN, or proxy. If it says the host's network has an old cached answer, wait: it usually clears within about 30 minutes. +4. If it says the address no longer points to this machine's tunnel, the + environment was likely removed from T3 Connect. Link it again: on a desktop + host, turn **T3 Connect** off and on in **Settings > Sharing & access**. On a + command-line host, run `t3 connect link`, then restart T3 Code. ## This device can't reach T3 Connect diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 19989716bc3c6..6fa96cdd493ae 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -3,6 +3,10 @@ "private": true, "type": "module", "exports": { + "./pull-request-diff-fold": { + "types": "./src/pullRequestDiffFold.ts", + "default": "./src/pullRequestDiffFold.ts" + }, "./assembly-highlighting": { "types": "./src/assemblyHighlighting.ts", "default": "./src/assemblyHighlighting.ts" diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.ts index 070ae5fbc53fb..5975f9c0dfdf9 100644 --- a/packages/client-runtime/src/operations/projects.test.ts +++ b/packages/client-runtime/src/operations/projects.test.ts @@ -9,14 +9,25 @@ import { getCloneDirectoryLeafName, getCloneDirectoryName, getCloneDirectoryPath, + getAddProjectInitialQuery, getDefaultCloneUrl, githubIncompleteOwnerRepositoryMessage, normalizePastedCloneUrl, sortAddProjectProviderSources, } from "./projects.ts"; import type { EnvironmentProject } from "../state/models.ts"; +import { isFilesystemBrowseQuery } from "../state/projects.ts"; describe("add project shared logic", () => { + it("starts the Add Project picker on a browsable path for a relative base directory", () => { + expect(isFilesystemBrowseQuery(getAddProjectInitialQuery("Desktop/dev"))).toBe(true); + expect(getAddProjectInitialQuery("Desktop/dev")).toBe("~/Desktop/dev/"); + expect(getAddProjectInitialQuery("/srv/code")).toBe("/srv/code/"); + expect(getAddProjectInitialQuery("~")).toBe("~/"); + expect(getAddProjectInitialQuery("./work")).toBe("./work/"); + expect(getAddProjectInitialQuery("C:\\dev")).toBe("C:\\dev\\"); + }); + it("offers only GitHub until other hosts are turned on", () => { const ready = () => ({ ready: true, hint: null }); expect(sortAddProjectProviderSources(ready, {})).toEqual(["github"]); diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 8f7fcb7d1b424..e207963676521 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -11,7 +11,7 @@ import type { } from "@t3tools/contracts"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl"; -import { newProjectFolderName } from "@t3tools/shared/path"; +import { isExplicitRelativePath, isHostPath, newProjectFolderName } from "@t3tools/shared/path"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; @@ -204,7 +204,10 @@ export function buildAddProjectRemoteSourceReadiness( export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string { const trimmed = baseDirectory?.trim() ?? ""; - return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed); + if (trimmed.length === 0) return "~/"; + // A bare relative setting such as `Desktop/dev` means a folder under home. + const isAnchored = trimmed === "~" || isHostPath(trimmed) || isExplicitRelativePath(trimmed); + return ensureBrowseDirectoryPath(isAnchored ? trimmed : `~/${trimmed}`); } export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string { diff --git a/packages/client-runtime/src/pullRequestDiffFold.test.ts b/packages/client-runtime/src/pullRequestDiffFold.test.ts new file mode 100644 index 0000000000000..34269c2212a05 --- /dev/null +++ b/packages/client-runtime/src/pullRequestDiffFold.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { isFileDiffCollapsed, withFileDiffFold } from "./pullRequestDiffFold.ts"; + +describe("isFileDiffCollapsed", () => { + it("collapses saved viewed files on reopening and when a later read marks them viewed", () => { + const overrides = new Map(); + expect(isFileDiffCollapsed("a.ts", null, overrides, false)).toBe(false); + expect(isFileDiffCollapsed("a.ts", null, overrides, true)).toBe(true); + expect(isFileDiffCollapsed("a.ts", null, overrides, false)).toBe(false); + }); + + it("preserves individual choices while viewed state and loaded pages change", () => { + const overrides = new Map([ + ["a.ts", false], + ["b.ts", true], + ]); + expect(isFileDiffCollapsed("a.ts", null, overrides, true)).toBe(false); + expect(isFileDiffCollapsed("b.ts", null, overrides, false)).toBe(true); + expect(isFileDiffCollapsed("c.ts", null, overrides, true)).toBe(true); + expect(isFileDiffCollapsed("d.ts", null, overrides, false)).toBe(false); + }); + + it("respects expand all and fold all, including later pages and individual exceptions", () => { + const overrides = new Map(); + expect(isFileDiffCollapsed("a.ts", "expanded", overrides, true)).toBe(false); + expect(isFileDiffCollapsed("b.ts", "folded", overrides, false)).toBe(true); + expect(isFileDiffCollapsed("c.ts", "folded", new Map([["c.ts", false]]), true)).toBe(false); + expect(isFileDiffCollapsed("d.ts", "expanded", new Map([["d.ts", true]]), false)).toBe(true); + }); +}); + +describe("withFileDiffFold", () => { + it("records or clears a choice and keeps the same map when nothing changes", () => { + const folded = withFileDiffFold(new Map(), "a.ts", true); + expect(folded.get("a.ts")).toBe(true); + expect(withFileDiffFold(folded, "a.ts", true)).toBe(folded); + expect(withFileDiffFold(folded, "a.ts", false).get("a.ts")).toBe(false); + expect(withFileDiffFold(folded, "a.ts", undefined).has("a.ts")).toBe(false); + }); +}); diff --git a/packages/client-runtime/src/pullRequestDiffFold.ts b/packages/client-runtime/src/pullRequestDiffFold.ts new file mode 100644 index 0000000000000..8083c93c25b09 --- /dev/null +++ b/packages/client-runtime/src/pullRequestDiffFold.ts @@ -0,0 +1,25 @@ +export type DiffFoldOverride = "expanded" | "folded" | null; + +/** The reader's own fold choice per file. It is absolute, so a Viewed mark loading later keeps it. */ +export type FileDiffFoldChoices = ReadonlyMap; + +export function isFileDiffCollapsed( + fileKey: string, + foldOverride: DiffFoldOverride, + choices: FileDiffFoldChoices, + viewed = false, +): boolean { + return choices.get(fileKey) ?? (foldOverride === null ? viewed : foldOverride === "folded"); +} + +export function withFileDiffFold( + choices: FileDiffFoldChoices, + fileKey: string, + collapsed: boolean | undefined, +): FileDiffFoldChoices { + if (choices.get(fileKey) === collapsed) return choices; + const next = new Map(choices); + if (collapsed === undefined) next.delete(fileKey); + else next.set(fileKey, collapsed); + return next; +} diff --git a/packages/client-runtime/src/state/composerDispatch.test.ts b/packages/client-runtime/src/state/composerDispatch.test.ts index 936ae33111ef4..2eb4728012a94 100644 --- a/packages/client-runtime/src/state/composerDispatch.test.ts +++ b/packages/client-runtime/src/state/composerDispatch.test.ts @@ -1,6 +1,6 @@ import { expect, it } from "vite-plus/test"; -import { compactionBlocksSteering } from "./composerDispatch.ts"; +import { compactionBlocksSteering, composerRunsDraftLocally } from "./composerDispatch.ts"; it("blocks steering for explicit compaction, and for automatic compaction unless the provider takes steers then", () => { const during = ( @@ -47,3 +47,27 @@ it("blocks steering for explicit compaction, and for automatic compaction unless }), ).toBe(false); }); + +it("treats only the commands the composer runs itself as local", () => { + const none = { + holdsOnlyText: true, + sideChat: false, + usageLimits: false, + codexFeedback: false, + freshSession: false, + }; + const all = { + ...none, + sideChat: true, + usageLimits: true, + codexFeedback: true, + freshSession: true, + }; + for (const text of ["/btw why?", "/usage-limits", "/feedback slow", "/clear"]) { + expect(composerRunsDraftLocally({ ...all, text })).toBe(true); + expect(composerRunsDraftLocally({ ...none, text })).toBe(false); + } + expect(composerRunsDraftLocally({ ...all, text: "fix the bug" })).toBe(false); + expect(composerRunsDraftLocally({ ...all, holdsOnlyText: false, text: "/clear" })).toBe(false); + expect(composerRunsDraftLocally({ ...all, holdsOnlyText: false, text: "/side why?" })).toBe(true); +}); diff --git a/packages/client-runtime/src/state/composerDispatch.ts b/packages/client-runtime/src/state/composerDispatch.ts index c24bb95628d97..3860bfc529ded 100644 --- a/packages/client-runtime/src/state/composerDispatch.ts +++ b/packages/client-runtime/src/state/composerDispatch.ts @@ -1,3 +1,8 @@ +import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger"; +import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits"; + +import { parseCodexFeedbackCommand } from "./threadFeedback.ts"; + export type ComposerDispatchMode = "auto" | "queue" | "steer" | "restart"; export type ActiveTurnComposerAction = Exclude; @@ -49,3 +54,21 @@ export function alternateComposerDispatchAction( ...(activeTurnDefault === undefined ? {} : { activeTurnDefault }), }) as ActiveTurnComposerAction; } + +/** The composer runs these drafts itself, so they never queue for or steer a running turn. */ +export function composerRunsDraftLocally(input: { + readonly text: string; + readonly holdsOnlyText: boolean; + readonly sideChat: boolean; + readonly usageLimits: boolean; + readonly codexFeedback: boolean; + readonly freshSession: boolean; +}): boolean { + if (input.sideChat && parseSideChatCommand(input.text) !== null) return true; + if (!input.holdsOnlyText) return false; + return ( + (input.usageLimits && isUsageLimitsCommand(input.text)) || + (input.codexFeedback && parseCodexFeedbackCommand(input.text) !== null) || + (input.freshSession && isClearComposerCommand(input.text)) + ); +} diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 4d313c0ceb98d..30517a6960292 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -1002,6 +1002,11 @@ export class PullRequestUnavailableError extends Schema.TaggedError { assert.equal(workspaceLaunch!.options.env?.PI_CODING_AGENT_DIR, "/isolated-pi"); // Discovery processes are stopped as soon as they answer, so neither may start Pi's // network refresh at launch. - for (const cwd of ["/machine", "/first"]) { + assert.isFalse(launches.some((launch) => launch.options.cwd === "/machine")); + for (const isLaunch of [ + (cwd: string | undefined) => cwd?.endsWith("/pi-status-probe") === true, + (cwd: string | undefined) => cwd === "/first", + ]) { const discovery = launches.find( - (launch) => launch.options.cwd === cwd && launch.args.includes("--mode"), + (launch) => isLaunch(launch.options.cwd) && launch.args.includes("--mode"), ); assert.deepEqual( discovery?.args.filter((arg) => arg === "--offline"), diff --git a/packages/provider-pi/src/server/driver.ts b/packages/provider-pi/src/server/driver.ts index 9f32de9d29c4d..325b500a35d94 100644 --- a/packages/provider-pi/src/server/driver.ts +++ b/packages/provider-pi/src/server/driver.ts @@ -97,7 +97,8 @@ export const PiDriver: ProviderDriver = { const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; const host = yield* ProviderHost.ProviderHost; - const { cwd } = host.paths; + // Pi runs extensions' session_start in its cwd; the server's cwd is $HOME on packaged desktop. + const probeCwd = pathService.join(host.paths.providerStatusCacheDir, "pi-status-probe"); const processEnv = yield* mergeProviderInstanceEnvironment(environment); const continuationIdentity = defaultProviderContinuationIdentity({ driverKind: DRIVER_KIND, @@ -141,10 +142,14 @@ export const PiDriver: ProviderDriver = { ); const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv); - const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe( - Effect.map(stampIdentity), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); + const checkProvider = fileSystem + .makeDirectory(probeCwd, { recursive: true }) + .pipe( + Effect.ignore, + Effect.andThen(checkPiProviderStatus(effectiveConfig, processEnv, probeCwd)), + Effect.map(stampIdentity), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const snapshot = yield* makeManagedServerProvider>({ diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 1c2a2c8cf4f25..ac5c59c752379 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -35,6 +35,7 @@ import { resolveSpawnCommand, resolveWindowsEnvironment, runsGitWithoutConsole, + windowsEnvironmentValueCommand, SpawnExecutableResolution, WindowsShellEnvironment, withPathDirectoryListings, @@ -257,6 +258,18 @@ describe("mergePathEntries", () => { }); }); +describe("windowsEnvironmentValueCommand", () => { + it("joins PATH as Process, then Machine, then User so prepends win and User installs still appear", () => { + const command = windowsEnvironmentValueCommand("PATH"); + const processAt = command.indexOf("[Environment]::GetEnvironmentVariable('PATH','Process')"); + const machineAt = command.indexOf("[Environment]::GetEnvironmentVariable('PATH','Machine')"); + const userAt = command.indexOf("[Environment]::GetEnvironmentVariable('PATH','User')"); + expect(processAt).toBeGreaterThan(-1); + expect(processAt).toBeLessThan(machineAt); + expect(machineAt).toBeLessThan(userAt); + }); +}); + describe("readEnvironmentFromWindowsShell", () => { effectIt.effect("yields while the native shell probe is pending", () => Effect.gen(function* () { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index e5833d097029b..fd881c5fcd830 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -278,6 +278,20 @@ export function buildEnvironmentCaptureCommand( : command; } +// Process first so profile prepends win; User and Machine add dirs missing from the launch snapshot. +export function windowsEnvironmentValueCommand(name: string): string { + if (name === "PATH") { + return ( + "$value = (@(" + + "[Environment]::GetEnvironmentVariable('PATH','Process')," + + "[Environment]::GetEnvironmentVariable('PATH','Machine')," + + "[Environment]::GetEnvironmentVariable('PATH','User')" + + ") | Where-Object { $_ }) -join ';'" + ); + } + return `$value = [Environment]::GetEnvironmentVariable('${name}')`; +} + function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray): string { return [ "$ErrorActionPreference = 'Stop'", @@ -288,7 +302,7 @@ function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray): st return [ `Write-Output '${envCaptureStart(name)}'`, - `$value = [Environment]::GetEnvironmentVariable('${name}')`, + windowsEnvironmentValueCommand(name), "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }", `Write-Output '${envCaptureEnd(name)}'`, ]; diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 7c107140e02be..d2cd22f49d654 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -340,14 +340,20 @@ describe("ssh tunnel scripts", () => { }, ); - it("names gzip when a host with tar but no gzip cannot unpack the release archive", () => { + // sha256sum and shasum escape a newline in a file name they print, so the home path has one. + const checksumTools = + NodeChildProcess.spawnSync("sh", ["-c", 'command -v "$1"', "sh", "shasum"]).status === 0 + ? ["sha256sum", "shasum"] + : ["sha256sum"]; + it.each(checksumTools)("names missing gzip after verifying with %s", (checksum) => { const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-ssh-runner-")); try { const bin = NodePath.join(root, "bin"); const release = NodePath.join(root, "release"); + const home = NodePath.join(root, "home\ncache"); const archive = `t3-${ARCHIVE.archiveVersion}-linux-x64.tar.gz`; NodeFS.mkdirSync(bin); - NodeFS.mkdirSync(NodePath.join(root, "home")); + NodeFS.mkdirSync(home); NodeFS.mkdirSync(NodePath.join(release, "t3"), { recursive: true }); NodeFS.writeFileSync(NodePath.join(release, "t3", "t3"), "#!/bin/sh\necho ok\n", { mode: 0o755, @@ -364,7 +370,7 @@ describe("ssh tunnel scripts", () => { "rm", "grep", "cut", - "sha256sum", + checksum, "tar", "mv", ]) { @@ -389,7 +395,7 @@ describe("ssh tunnel scripts", () => { NodeFS.writeFileSync(runner, SshTunnel.buildRemoteT3RunnerScript(ARCHIVE)); const result = NodeChildProcess.spawnSync(NodePath.join(bin, "sh"), [runner, "--version"], { encoding: "utf8", - env: { HOME: NodePath.join(root, "home"), PATH: bin }, + env: { HOME: home, PATH: bin }, }); assert.notEqual(result.status, 0); assert.match(result.stderr, /(missing|needs) gzip/); diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index c3ff20293aa1d..0b27a94acb33d 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -542,9 +542,9 @@ if ! t3_runtime_ready; then t3_fetch "$T3_RELEASE_BASE_URL/v$T3_ARCHIVE_VERSION/$T3_ARCHIVE" "$T3_STAGING/$T3_ARCHIVE" @@T3_ARCHIVE_DOWNLOAD_SECONDS@@ T3_EXPECTED="$(grep " \\*\\{0,1\\}$T3_ARCHIVE$" "$T3_STAGING/SHA256SUMS" | cut -d' ' -f1)" if command -v sha256sum >/dev/null 2>&1; then - T3_ACTUAL="$(sha256sum "$T3_STAGING/$T3_ARCHIVE" | cut -d' ' -f1)" + T3_ACTUAL="$(sha256sum < "$T3_STAGING/$T3_ARCHIVE" | cut -d' ' -f1)" else - T3_ACTUAL="$(shasum -a 256 "$T3_STAGING/$T3_ARCHIVE" | cut -d' ' -f1)" + T3_ACTUAL="$(shasum -a 256 < "$T3_STAGING/$T3_ARCHIVE" | cut -d' ' -f1)" fi if [ -z "$T3_EXPECTED" ] || [ "$T3_ACTUAL" != "$T3_EXPECTED" ]; then printf 'Checksum mismatch for %s.\\n' "$T3_ARCHIVE" >&2; exit 1 diff --git a/patches/@pierre__diffs@1.7.0-beta.4.patch b/patches/@pierre__diffs@1.7.0-beta.4.patch index adfe946dab74e..4eacdc66fb9fe 100644 --- a/patches/@pierre__diffs@1.7.0-beta.4.patch +++ b/patches/@pierre__diffs@1.7.0-beta.4.patch @@ -1,5 +1,5 @@ diff --git a/dist/editor/editor.js b/dist/editor/editor.js -index b4c280390b52434f63fbe7916d81b150d9006fb4..8564980bdfe2ef8e17e8ab0a87627709091101ee 100644 +index b4c280390b52434f63fbe7916d81b150d9006fb4..cb7fb89a22c8adac9ea951b8767b5fd446347746 100644 --- a/dist/editor/editor.js +++ b/dist/editor/editor.js @@ -95,6 +95,7 @@ var Editor = class { @@ -38,7 +38,15 @@ index b4c280390b52434f63fbe7916d81b150d9006fb4..8564980bdfe2ef8e17e8ab0a87627709 const replacementFocusTargetIsContent = (event) => { const target = event.composedPath()[0]; return target instanceof Node && this.#contentElement?.contains(target) === true; -@@ -1397,6 +1412,7 @@ var Editor = class { +@@ -1130,6 +1145,7 @@ var Editor = class { + this.#editorEventDisposes = [ + addEventListener(contentEl, "focus", () => { + this.#contentHasFocus = true; ++ this.#retainSearchPanelFocus = false; + onFocus?.(); + if (!this.#isContentMouseDown && !this.#isComposing && this.#focusRequest == null && this.#selections !== void 0 && this.#selections.length > 0) this.#setWindowSelection(this.#selections.at(-1)); + }, { passive: true }), +@@ -1397,6 +1413,7 @@ var Editor = class { this.#resizeObserver = new ResizeObserver(this.#handleLayoutResize); this.#resizeObserver.observe(contentEl); this.#resizeObserver.observe(contentEl.parentElement); @@ -46,7 +54,7 @@ index b4c280390b52434f63fbe7916d81b150d9006fb4..8564980bdfe2ef8e17e8ab0a87627709 this.#computeContentOffset(contentEl); } #handleCustomPasteEvent = async () => { -@@ -1852,7 +1868,9 @@ var Editor = class { +@@ -1852,7 +1869,9 @@ var Editor = class { const change = textDocument.applyEdits(edits, true, selections, nextSelections, true); if (change !== void 0) this.#applyChange(change, nextSelections); } @@ -57,7 +65,7 @@ index b4c280390b52434f63fbe7916d81b150d9006fb4..8564980bdfe2ef8e17e8ab0a87627709 const lineAnnotations = this.#lineAnnotations?.length ?? 0; const prevGutterWidth = this.#gutterWidthCache; const prevContentWidth = this.#contentWidthCache; -@@ -1860,12 +1878,12 @@ var Editor = class { +@@ -1860,12 +1879,12 @@ var Editor = class { this.#contentWidthCache = void 0; const gutterWidthChanged = this.#getGutterWidth() !== prevGutterWidth; const contentWidthChanged = this.#getContentWidth() !== prevContentWidth; @@ -73,6 +81,15 @@ index b4c280390b52434f63fbe7916d81b150d9006fb4..8564980bdfe2ef8e17e8ab0a87627709 } if (this.#selections !== void 0 || this.#matches !== void 0 || this.#markerRenderer !== void 0) { this.#updateSelections(this.#selections ?? []); +@@ -3369,7 +3388,8 @@ var Editor = class { + }); + this.#searchPanel = searchPanel; + this.#retainSearchPanelFocus = false; + searchPanel.mount(); ++ searchPanel.getHostElement().dataset.searchPanelOverlay = ""; + } + #searchWithNavigationTarget(textDocument, searchParams) { + const viewport = this.#getSearchViewportBounds(); diff --git a/dist/editor/textMeasure.d.ts b/dist/editor/textMeasure.d.ts index 89e938d89eca77d351aeed65f3c5495383effd97..cde1d6ba89a97bbb1614754a48f8994388c186bd 100644 --- a/dist/editor/textMeasure.d.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4b55abacfb80c..985c914406cf7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -372,7 +372,7 @@ patchedDependencies: '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 '@legendapp/list@3.7.2': 3c68607b8bb7a531873bcbe0b197d163ef1fdb4d4cf52a4ddf9d2b3804671658 '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 - '@pierre/diffs@1.7.0-beta.4': dd078a7448ce6727aaaa8b8b6702fe0ff02e85f18efa7c441a768530cabbe0cc + '@pierre/diffs@1.7.0-beta.4': 241563d810c29250e0e92f3eda74214393726d46667fedbf1f91a5f5bea07d1e '@react-native-ai/apple@0.12.0': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d '@react-navigation/native-stack@7.21.0': 990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42 @@ -573,7 +573,7 @@ importers: version: 0.3.0 '@pierre/diffs': specifier: 1.7.0-beta.4 - version: 1.7.0-beta.4(patch_hash=dd078a7448ce6727aaaa8b8b6702fe0ff02e85f18efa7c441a768530cabbe0cc)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + version: 1.7.0-beta.4(patch_hash=241563d810c29250e0e92f3eda74214393726d46667fedbf1f91a5f5bea07d1e)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@pierre/highlights': specifier: 'catalog:' version: 0.5.0 @@ -1094,7 +1094,7 @@ importers: version: 1.8.0 '@pierre/diffs': specifier: 1.7.0-beta.4 - version: 1.7.0-beta.4(patch_hash=dd078a7448ce6727aaaa8b8b6702fe0ff02e85f18efa7c441a768530cabbe0cc)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + version: 1.7.0-beta.4(patch_hash=241563d810c29250e0e92f3eda74214393726d46667fedbf1f91a5f5bea07d1e)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -1510,7 +1510,7 @@ importers: dependencies: '@pierre/diffs': specifier: 1.7.0-beta.4 - version: 1.7.0-beta.4(patch_hash=dd078a7448ce6727aaaa8b8b6702fe0ff02e85f18efa7c441a768530cabbe0cc)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + version: 1.7.0-beta.4(patch_hash=241563d810c29250e0e92f3eda74214393726d46667fedbf1f91a5f5bea07d1e)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -16440,7 +16440,7 @@ snapshots: tslib: 2.8.1 webcrypto-core: 1.9.2 - '@pierre/diffs@1.7.0-beta.4(patch_hash=dd078a7448ce6727aaaa8b8b6702fe0ff02e85f18efa7c441a768530cabbe0cc)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@pierre/diffs@1.7.0-beta.4(patch_hash=241563d810c29250e0e92f3eda74214393726d46667fedbf1f91a5f5bea07d1e)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: '@pierre/highlights': 0.5.1 '@pierre/patches': 0.0.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 7d1064ffc9716..5c66aef02dda2 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -248,8 +248,8 @@ patchedDependencies: # scroll target a Material bottom sheet picks, so sheet content can sit below its header. "@expo/ui@58.0.27": patches/@expo__ui@58.0.27.patch "@ff-labs/fff-node@0.11.0": patches/@ff-labs__fff-node@0.11.0.patch - # Exports the dependency-light subpaths mobile and the web diff parser import, and re-measures - # editor carets when the code font changes. + # Exports the dependency-light subpaths mobile and the web diff parser import, re-measures + # editor carets when the code font changes, and stops the find bar reclaiming focus from the file. "@pierre/diffs@1.7.0-beta.4": patches/@pierre__diffs@1.7.0-beta.4.patch "@react-native-ai/apple@0.12.0": patches/@react-native-ai__apple@0.12.0.patch "@react-native-menu/menu@2.0.0": patches/@react-native-menu__menu@2.0.0.patch diff --git a/scripts/scenarios/theme-keep-both-copy-keeps-css.e2e.ts b/scripts/scenarios/theme-keep-both-copy-keeps-css.e2e.ts new file mode 100644 index 0000000000000..8d921d67433c2 --- /dev/null +++ b/scripts/scenarios/theme-keep-both-copy-keeps-css.e2e.ts @@ -0,0 +1,50 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const themeJson = (css?: string) => + JSON.stringify({ + version: 1, + name: "Nyx", + // The scenario browser is in light mode, and a one-appearance theme only fills that half. + appearance: "light", + colors: { canvas: "#f4f1ff", accent: "#6d5ae6" }, + ...(css ? { css } : {}), + }); + +const NYX_CSS = + ":root { --keep-both-marker: applied; } [data-settings-page-scroll] { outline: 8px solid #ff2d95; outline-offset: -8px; }"; + +test( + "Keep both on a theme import conflict keeps the imported theme's CSS", + WEB, + async ({ t3, app, screen, browser }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + + const importTheme = async (json: string) => { + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + await dialog.getByRole("textbox", "Theme JSON").fill(json); + await dialog.getByRole("button", "Add theme", { exact: true }).tap(); + return dialog; + }; + + await expect(await importTheme(themeJson())).toBeHidden(); + + const dialog = await importTheme(themeJson(NYX_CSS)); + await expect(dialog.getByText("Already installed")).toBeVisible(); + await dialog.getByRole("button", "Keep both").tap(); + await expect(dialog).toBeHidden(); + + await screen.getByRole("button", "Use Nyx (1) theme").tap(); + await app.screenshot("keep-both-copy-selected"); + await expect + .poll(() => + browser.evaluate(() => + getComputedStyle(document.documentElement).getPropertyValue("--keep-both-marker").trim(), + ), + ) + .toBe("applied"); + }, +);