From eea4cd54eff2180c9bd4b6f3614059eb450916d8 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Wed, 21 Oct 2026 10:49:08 -0300 Subject: [PATCH 01/87] feat(chat): collapse Claude insight asides by default - Show each insight as a separate block with a first-point preview - Add an Appearance setting across web and mobile --- .../AppearancePreferencesProvider.tsx | 12 ++ .../sections/TextAppearanceSection.tsx | 19 +++- .../src/features/threads/ThreadFeed.tsx | 72 ++++++++---- .../features/threads/ThreadInsightBlock.tsx | 51 +++++++++ .../src/persistence/mobile-preferences.ts | 4 + .../chat/AssistantCitationSource.tsx | 19 ++++ .../src/components/chat/MarkdownInsight.tsx | 43 +++++++ .../chat/MessagesTimeline.browser.test.tsx | 37 ++++++ .../components/chat/TimelineAssistantRows.tsx | 45 +++++--- .../chat/timelineMinimapItems.test.ts | 17 +++ .../components/chat/timelineMinimapItems.ts | 14 ++- .../settings/AppearanceSettingsPanel.tsx | 26 +++++ .../components/settings/SettingsPanels.tsx | 4 + .../src/components/settings/settingsSearch.ts | 6 + docs/user/providers-claude.md | 9 ++ packages/contracts/src/settings.ts | 2 + packages/shared/package.json | 4 + packages/shared/src/assistantInsights.test.ts | 86 ++++++++++++++ packages/shared/src/assistantInsights.ts | 107 ++++++++++++++++++ packages/shared/src/markdownPipeline.ts | 4 - packages/shared/src/threadFindText.test.ts | 8 ++ packages/shared/src/threadFindText.ts | 12 +- 22 files changed, 552 insertions(+), 49 deletions(-) create mode 100644 apps/mobile/src/features/threads/ThreadInsightBlock.tsx create mode 100644 apps/web/src/components/chat/MarkdownInsight.tsx create mode 100644 apps/web/src/components/chat/timelineMinimapItems.test.ts create mode 100644 packages/shared/src/assistantInsights.test.ts create mode 100644 packages/shared/src/assistantInsights.ts diff --git a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx index 4a142511c39ec..317e2afbbc5fd 100644 --- a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx +++ b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx @@ -70,6 +70,8 @@ interface AppearancePreferencesContextValue { readonly setCodeWordBreak: (value: boolean) => void; readonly mathRenderingEnabled: boolean; readonly setMathRenderingEnabled: (value: boolean) => void; + readonly assistantInsightsCollapsed: boolean; + readonly setAssistantInsightsCollapsed: (value: boolean) => void; } const AppearancePreferencesContext = createContext(null); @@ -272,6 +274,12 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN [updatePreferences], ); + const assistantInsightsCollapsed = storedPreferences?.assistantInsightsCollapsed !== false; + const setAssistantInsightsCollapsed = useCallback( + (value: boolean) => updatePreferences({ assistantInsightsCollapsed: value }), + [updatePreferences], + ); + const value = useMemo( (): AppearancePreferencesContextValue => ({ appearance, @@ -294,6 +302,8 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN setCodeWordBreak, mathRenderingEnabled, setMathRenderingEnabled, + assistantInsightsCollapsed, + setAssistantInsightsCollapsed, }), [ appearance, @@ -315,6 +325,8 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN setCodeWordBreak, mathRenderingEnabled, setMathRenderingEnabled, + assistantInsightsCollapsed, + setAssistantInsightsCollapsed, ], ); diff --git a/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx b/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx index 1a1c61012b7b1..d3e51def8daec 100644 --- a/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx +++ b/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx @@ -13,8 +13,15 @@ import { FontSizeSliderRow } from "../components/FontSizeSliderRow"; import { SettingsSwitchRow } from "../../components/SettingsSwitchRow"; export function TextAppearanceSection() { - const { isReady, appearance, setBaseFontSize, mathRenderingEnabled, setMathRenderingEnabled } = - useAppearancePreferences(); + const { + isReady, + appearance, + setBaseFontSize, + mathRenderingEnabled, + setMathRenderingEnabled, + assistantInsightsCollapsed, + setAssistantInsightsCollapsed, + } = useAppearancePreferences(); return ( @@ -38,6 +45,14 @@ export function TextAppearanceSection() { value={mathRenderingEnabled} onValueChange={setMathRenderingEnabled} /> + ); } diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 77729684a792e..976190a8c0f7f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -74,6 +74,7 @@ import { renderCodexInlineDirectivesAsMarkdown, splitCodexArtifactTemplateMarkdown, } from "@t3tools/shared/codexMarkdownDirectives"; +import { splitAssistantInsights } from "@t3tools/shared/assistantInsights"; import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList"; import { imageMimeType } from "@t3tools/shared/image"; import { videoMimeType } from "@t3tools/shared/video"; @@ -85,6 +86,7 @@ import { useDeviceType } from "../../native/native-layout-metrics"; import { isDuoDevice } from "../../lib/device-type"; import { createContext, + Fragment, memo, useCallback, useContext, @@ -213,6 +215,7 @@ import { ThreadWorkLog, WORK_GROUP_TOGGLE_HEIGHT, } from "./thread-work-log"; +import { ThreadInsightBlock } from "./ThreadInsightBlock"; import { appendPendingThreadMessages, type PendingThreadFeedEntry } from "./pending-thread-feed"; import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size"; @@ -821,6 +824,7 @@ function ArtifactTemplateCard(props: { const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly markdown: string; + readonly streaming?: boolean; readonly environmentId: EnvironmentId; readonly markdownStyles: MarkdownStyleSet; readonly linkHandlers: MarkdownLinkHandlers; @@ -829,32 +833,57 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly skills?: ReadonlyArray | undefined; }) { const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); - const segments = useMemo(() => splitCodexArtifactTemplateMarkdown(liveMarkdown), [liveMarkdown]); + const segments = useMemo( + () => + splitAssistantInsights(liveMarkdown, { streaming: props.streaming === true }).map( + (segment) => ({ ...segment, parts: splitCodexArtifactTemplateMarkdown(segment.markdown) }), + ), + [liveMarkdown, props.streaming], + ); + + const renderParts = ( + parts: (typeof segments)[number]["parts"], + sourceOffset: number, + preserveSoftBreaks: boolean, + ) => + parts.map((segment) => { + const offset = sourceOffset + segment.sourceOffset; + if (segment.kind === "artifact-template") { + return ( + + ); + } + if (segment.markdown.trim().length === 0) return null; - return segments.map((segment) => { - if (segment.kind === "artifact-template") { + const markdown = renderCodexInlineDirectivesAsMarkdown(segment.markdown); return ( - ); - } - if (segment.markdown.trim().length === 0) return null; + }); - const markdown = renderCodexInlineDirectivesAsMarkdown(segment.markdown); - return ( - - ); - }); + return segments.map((segment) => + segment.kind === "insight" ? ( + + {renderParts(segment.parts, segment.sourceOffset, true)} + + ) : ( + + {renderParts(segment.parts, segment.sourceOffset, false)} + + ), + ); }); function useMarkdownStyles(): MarkdownStyleSets { @@ -1415,6 +1444,7 @@ function renderFeedEntry( (null); + const open = openOverride ?? !assistantInsightsCollapsed; + const preview = useMemo( + () => (open ? "" : assistantInsightPreview(props.markdown)), + [open, props.markdown], + ); + + return ( + + setOpenOverride(!open)} + className="min-h-11 flex-row items-center gap-1.5 px-3" + > + + Insight + + {preview} + + + + {open ? {props.children} : null} + + ); +} diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index 7acdd47e4e667..3863d57cea216 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -64,6 +64,7 @@ export interface Preferences { readonly codeFontSize?: number | null; readonly codeWordBreak?: boolean; readonly mathRenderingEnabled?: boolean; + readonly assistantInsightsCollapsed?: boolean; readonly connectOnboardingOptOutAccounts?: ReadonlyArray; readonly collapsedProjectGroups?: readonly string[]; /** Environments whose "reclaim database space" notice was dismissed. */ @@ -139,6 +140,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { codeFontSize?: number | null; codeWordBreak?: boolean; mathRenderingEnabled?: boolean; + assistantInsightsCollapsed?: boolean; connectOnboardingOptOutAccounts?: ReadonlyArray; collapsedProjectGroups?: readonly string[]; dismissedDatabaseStorageNotices?: readonly string[]; @@ -210,6 +212,8 @@ function sanitizePreferences(parsed: Preferences): Preferences { if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak; if (typeof parsed.mathRenderingEnabled === "boolean") preferences.mathRenderingEnabled = parsed.mathRenderingEnabled; + if (typeof parsed.assistantInsightsCollapsed === "boolean") + preferences.assistantInsightsCollapsed = parsed.assistantInsightsCollapsed; if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) { preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter( (account): account is string => typeof account === "string", diff --git a/apps/web/src/components/chat/AssistantCitationSource.tsx b/apps/web/src/components/chat/AssistantCitationSource.tsx index 1b24aac305d43..aa16e5dd9e02e 100644 --- a/apps/web/src/components/chat/AssistantCitationSource.tsx +++ b/apps/web/src/components/chat/AssistantCitationSource.tsx @@ -83,6 +83,23 @@ export function observeAssistantCitationCommentSource({ return dispose; } +/** + * Citation text skips hidden elements, so a quote inside a collapsed insight cannot + * resolve until that block opens. The block listens for `beforematch`, like find. + */ +function revealFoldedQuote(root: HTMLElement, quote: string): boolean { + const compact = (text: string) => text.replace(/\s+/g, ""); + const needle = compact(quote); + if (needle.length === 0) return false; + let revealed = false; + for (const fold of root.querySelectorAll("[hidden]")) { + if (!compact(fold.textContent ?? "").includes(needle)) continue; + fold.dispatchEvent(new Event("beforematch")); + revealed = true; + } + return revealed; +} + export interface AssistantCitationRequest { citation: AssistantCitation; key: string; @@ -164,6 +181,8 @@ export function observeAssistantCitationSource({ const index = state.indexByKey(itemKey); if (index === undefined || !(state.sizeAtIndex(index) > 0)) return; const range = resolveAssistantCitationRange(root, request.citation); + // Opening resizes the row, and the resize observer runs this again. + if (!range && revealFoldedQuote(root, request.citation.text)) return; const rect = (range ?? root).getBoundingClientRect(); if (rect.height <= 0 || scrollNode.clientHeight <= 0) { clear(); diff --git a/apps/web/src/components/chat/MarkdownInsight.tsx b/apps/web/src/components/chat/MarkdownInsight.tsx new file mode 100644 index 0000000000000..e253a871fd986 --- /dev/null +++ b/apps/web/src/components/chat/MarkdownInsight.tsx @@ -0,0 +1,43 @@ +import { assistantInsightPreview } from "@t3tools/shared/assistantInsights"; +import { ChevronRightIcon, StarIcon } from "lucide-react"; +import { useState, type ReactNode } from "react"; + +import { useClientSettings } from "~/hooks/useSettings"; +import { cn } from "~/lib/utils"; +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; +import { findRevealRef } from "./markdownFindContext"; + +export function MarkdownInsight({ markdown, children }: { markdown: string; children: ReactNode }) { + const collapsedByDefault = useClientSettings((settings) => settings.assistantInsightsCollapsed); + // Until the user toggles this block, it follows the setting. + const [openOverride, setOpenOverride] = useState(null); + const open = openOverride ?? !collapsedByDefault; + const revealRef = findRevealRef(() => setOpenOverride(true)); + const preview = open ? "" : assistantInsightPreview(markdown); + + return ( +
+ + + + Insight + {preview} + + + {/* Folded text stays in the DOM so find and citations can reach and reveal it. */} + +
{children}
+
+
+
+ ); +} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index ddf8d87049faa..bab91a2fc8dc6 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -164,6 +164,43 @@ describe("MessagesTimeline messages", () => { }); }); +describe("MessagesTimeline Claude insights", () => { + const response = [ + "Intro", + "", + "`★ Insight ─────────────────────────────────────`", + "- **First** point", + "- Second point", + "`─────────────────────────────────────────────────`", + "Done: the answer continues.", + ].join("\n"); + + it("folds an insight behind its first point and keeps the answer after it outside", async () => { + await using screen = await renderTimeline([message(response, { role: "assistant" })]); + const trigger = screen.button(/^Insight/); + expect(trigger.getAttribute("aria-expanded")).toBe("false"); + expect(trigger.textContent).toContain("First point"); + expect(screen.text()).not.toContain("★ Insight"); + const answer = [...screen.container.querySelectorAll("p")].find( + (paragraph) => paragraph.textContent === "Done: the answer continues.", + ); + expect(answer?.closest("[data-markdown-insight], li")).toBeNull(); + + await click(trigger); + expect(trigger.getAttribute("aria-expanded")).toBe("true"); + expect(trigger.textContent).not.toContain("First point"); + }); + + it("opens a folded insight when find reveals a match inside it", async () => { + await using screen = await renderTimeline([message(response, { role: "assistant" })]); + const panel = screen.container.querySelector("[data-markdown-insight] [hidden]"); + expect(panel?.textContent).toContain("Second point"); + + await act(async () => panel?.dispatchEvent(new Event("beforematch"))); + expect(screen.button(/^Insight/).getAttribute("aria-expanded")).toBe("true"); + }); +}); + describe("compact reasoning math", () => { it("keeps formulas while flattening compact reasoning previews", () => { const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]"); diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 6f99213057f96..7ed333ebb6dd3 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,4 +1,4 @@ -import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; +import { splitAssistantInsights } from "@t3tools/shared/assistantInsights"; import { type RunId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { memo, use, useState } from "react"; @@ -8,6 +8,7 @@ import { GitForkIcon } from "lucide-react"; import { Button } from "../ui/button"; import { ProposedPlanCard } from "./ProposedPlanCard"; import { HtmlRenderFrame } from "./HtmlRenderFrame"; +import { MarkdownInsight } from "./MarkdownInsight"; import { McpAppFrame } from "./McpAppFrame"; import { ChangedFilesCard } from "./ChangedFilesTree"; import { useFileContextMenuHandler } from "../../fileContextMenu"; @@ -25,7 +26,9 @@ import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts" export function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); - const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)"); + const streaming = Boolean(row.message.streaming); + const messageText = row.message.text || (streaming ? "" : "(empty response)"); + const segments = splitAssistantInsights(messageText, { streaming }); return ( <> @@ -39,18 +42,32 @@ export function AssistantTimelineRow({ row }: { row: Extract - + {segments.map((segment, index) => { + const key = `${segment.kind}:${segment.sourceOffset}`; + const markdown = ( + + ); + return segment.kind === "insight" ? ( + + {markdown} + + ) : ( + markdown + ); + })} + resolveTimelineMinimapPreview({ id: "turn", rowIndex: 0, userText: null, assistantText }) + ?.assistantText; + +describe("resolveTimelineMinimapPreview", () => { + it("summarizes the answer without its insight asides", () => { + expect(preview("`★ Insight ─────`\n- Aside\n`─────`\nThe **answer**.")).toBe("The answer."); + }); + + it("falls back to the insight when the reply is only an aside", () => { + expect(preview("`★ Insight ─────`\n- Aside\n`─────`")).toBe("Aside"); + }); +}); diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index faf6af9415405..fecb478489960 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -1,3 +1,4 @@ +import { splitAssistantInsights } from "@t3tools/shared/assistantInsights"; import type { Nodes } from "mdast"; import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; @@ -85,6 +86,15 @@ function markdownNodeText(node: Nodes): string { return node.children.map(markdownNodeText).join(separator); } +/** The preview summarizes the answer, so insight asides are left out unless nothing else remains. */ +function withoutInsights(text: string): string { + const segments = splitAssistantInsights(text); + const answer = segments.filter((segment) => segment.kind === "markdown"); + return (answer.some((segment) => segment.markdown.trim()) ? answer : segments) + .map((segment) => segment.markdown) + .join("\n\n"); +} + function compactMinimapPreview(text: string | null | undefined) { const compact = text?.replace(/\s+/g, " ").trim() ?? ""; return compact.length > 0 ? compact : null; @@ -102,7 +112,9 @@ export function resolveTimelineMinimapPreview( assistantText: compactMinimapPreview( item.assistantText === null ? null - : markdownNodeText(markdownPreviewParser.parse(item.assistantText.slice(0, 1_500))), + : markdownNodeText( + markdownPreviewParser.parse(withoutInsights(item.assistantText).slice(0, 1_500)), + ), ), }; } diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index a13bc93bb9ce8..49c939a5019f9 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -376,6 +376,32 @@ export function AppearanceSettingsPanel() { /> } /> + + updateSettings({ + assistantInsightsCollapsed: DEFAULT_UNIFIED_SETTINGS.assistantInsightsCollapsed, + }) + } + /> + ) : null + } + control={ + + updateSettings({ assistantInsightsCollapsed: Boolean(checked) }) + } + aria-label="Collapse insights" + /> + } + /> diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index cdf7d61839050..6885dcaf4a9b8 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -405,6 +405,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.mathRenderingEnabled !== DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled ? ["Render math"] : []), + ...(settings.assistantInsightsCollapsed !== DEFAULT_UNIFIED_SETTINGS.assistantInsightsCollapsed + ? ["Collapse insights"] + : []), ...(settings.panelAnimationDurationMs !== DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs ? ["Panel animations"] : []), @@ -580,6 +583,7 @@ export function useSettingsRestore(onRestored?: () => void) { diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, + assistantInsightsCollapsed: DEFAULT_UNIFIED_SETTINGS.assistantInsightsCollapsed, timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat, notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode, inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 38737b2627b06..9b4200bbe436a 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -244,6 +244,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/appearance", searchTerms: ["latex tex katex equations formulas markdown"], }, + { + id: "collapse-insights", + title: "Collapse insights", + to: "/settings/appearance", + searchTerms: ["claude explanatory learning output style star aside fold expand messages"], + }, { id: "panel-animations", title: "Panel animations", diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 344cffb478082..47f42670619a9 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -84,6 +84,15 @@ To show Claude task lists in the web and desktop apps, add **Environment** section in **Settings > Providers**. Unfinished tasks stay visible between turns in the same Claude session. +## Insights + +Claude's Explanatory and Learning output styles add `★ Insight` asides to +replies. T3 Code shows each one as a separate block that starts collapsed, with +its first point as a preview. Turn off **Collapse insights** in +**Settings > Appearance** to start them open. The mobile app has the same +setting under **Settings > Appearance > Text**. An aside that Claude never +closes shows as plain text. + ## OpenRouter Create a Claude instance with its own config directory, such as diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 620f659befea2..e4dbdb5659712 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -482,6 +482,7 @@ export const ClientSettingsSchema = Schema.Struct({ // Opt-in TeX typesetting in rendered Markdown. Off keeps math parsing and // KaTeX out of the render path entirely. mathRenderingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + assistantInsightsCollapsed: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), }); export type ClientSettings = typeof ClientSettingsSchema.Type; @@ -1658,5 +1659,6 @@ export const ClientSettingsPatch = Schema.Struct({ snapShotAnimations: Schema.optionalKey(Schema.Boolean), wordWrap: Schema.optionalKey(Schema.Boolean), mathRenderingEnabled: Schema.optionalKey(Schema.Boolean), + assistantInsightsCollapsed: Schema.optionalKey(Schema.Boolean), }); export type ClientSettingsPatch = typeof ClientSettingsPatch.Type; diff --git a/packages/shared/package.json b/packages/shared/package.json index 31828017d81a3..1b38b57a77f58 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -263,6 +263,10 @@ "types": "./src/assistantCitations.ts", "import": "./src/assistantCitations.ts" }, + "./assistantInsights": { + "types": "./src/assistantInsights.ts", + "import": "./src/assistantInsights.ts" + }, "./promptLinks": { "types": "./src/promptLinks.ts", "import": "./src/promptLinks.ts" diff --git a/packages/shared/src/assistantInsights.test.ts b/packages/shared/src/assistantInsights.test.ts new file mode 100644 index 0000000000000..34458b0e2b6ff --- /dev/null +++ b/packages/shared/src/assistantInsights.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { assistantInsightPreview, splitAssistantInsights } from "./assistantInsights.ts"; + +const OPEN = "`★ Insight ─────────────────────────────────────`"; +const CLOSE = "`─────────────────────────────────────────────────`"; + +describe("splitAssistantInsights", () => { + it("cuts at the closer line even when prose follows without a blank line", () => { + const text = `Intro\n\n${OPEN}\n- **First** point\n- Second point\n${CLOSE}\nDone: the commit is pushed.`; + + expect(splitAssistantInsights(text)).toEqual([ + { kind: "markdown", markdown: "Intro\n\n", sourceOffset: 0 }, + { + kind: "insight", + markdown: "- **First** point\n- Second point\n", + sourceOffset: text.indexOf(OPEN), + }, + { + kind: "markdown", + markdown: "Done: the commit is pushed.", + sourceOffset: text.indexOf("Done"), + }, + ]); + }); + + it("splits every insight in a message and accepts the unquoted form", () => { + const text = `${OPEN}\nOne\n${CLOSE}\n\nBetween\n\n★ Insight ─────\nTwo\n─────\n`; + + expect(splitAssistantInsights(text).map(({ kind, markdown }) => ({ kind, markdown }))).toEqual([ + { kind: "insight", markdown: "One\n" }, + { kind: "markdown", markdown: "\nBetween\n\n" }, + { kind: "insight", markdown: "Two\n" }, + ]); + }); + + it.each([ + ["inside fenced code", `\`\`\`md\n${OPEN}\nExample\n${CLOSE}\n\`\`\``], + ["inside a tilde fence", `~~~\n${OPEN}\nExample\n${CLOSE}\n~~~`], + ["mentioned inline", `The \`★ Insight\` blocks look like ${OPEN}\nExample\n${CLOSE}`], + ["nested in a list", `- Item\n\n ${OPEN}\n Example\n ${CLOSE}`], + ["empty", `${OPEN}\n\n${CLOSE}`], + ])("leaves an insight %s as Markdown", (_label, text) => { + expect(splitAssistantInsights(text)).toEqual([ + { kind: "markdown", markdown: text, sourceOffset: 0 }, + ]); + }); + + it("keeps an unclosed insight as Markdown once complete but folds it while streaming", () => { + const text = `Intro\n\n${OPEN}\n- Still writing`; + + expect(splitAssistantInsights(text)).toEqual([ + { kind: "markdown", markdown: text, sourceOffset: 0 }, + ]); + expect(splitAssistantInsights(text, { streaming: true })).toEqual([ + { kind: "markdown", markdown: "Intro\n\n", sourceOffset: 0 }, + { kind: "insight", markdown: "- Still writing", sourceOffset: 7 }, + ]); + }); + + it("lets a later opener replace one that never closed", () => { + const text = `${OPEN}\nOrphan\n\n${OPEN}\nKept\n${CLOSE}`; + + expect(splitAssistantInsights(text)).toEqual([ + { kind: "markdown", markdown: `${OPEN}\nOrphan\n\n`, sourceOffset: 0 }, + { kind: "insight", markdown: "Kept\n", sourceOffset: text.lastIndexOf(OPEN) }, + ]); + }); + + it("reads CRLF line endings", () => { + const text = `${OPEN}\r\nWindows line\r\n${CLOSE}\r\nAfter`; + + expect(splitAssistantInsights(text).map((segment) => segment.kind)).toEqual([ + "insight", + "markdown", + ]); + }); +}); + +describe("assistantInsightPreview", () => { + it("reads the first point as plain text", () => { + expect( + assistantInsightPreview("- **La regla clave** es la `HOST_TIPO`\n concordancia\n- Otra"), + ).toBe("La regla clave es la HOST_TIPO concordancia"); + }); +}); diff --git a/packages/shared/src/assistantInsights.ts b/packages/shared/src/assistantInsights.ts new file mode 100644 index 0000000000000..e6f894681d99f --- /dev/null +++ b/packages/shared/src/assistantInsights.ts @@ -0,0 +1,107 @@ +import type { Nodes } from "mdast"; +import remarkParse from "remark-parse"; +import { unified } from "unified"; + +export type AssistantInsightSegment = + | { readonly kind: "markdown"; readonly markdown: string; readonly sourceOffset: number } + | { readonly kind: "insight"; readonly markdown: string; readonly sourceOffset: number }; + +const INSIGHT_MARKER = "★ Insight"; +const INSIGHT_OPENER = /^ {0,3}(`?)★ Insight[ \t]*─+[ \t]*\1[ \t]*$/u; +const INSIGHT_CLOSER = /^ {0,3}(`?)─{3,}[ \t]*\1[ \t]*$/u; +const FENCE_OPENER = /^ {0,3}(`{3,}|~{3,})(.*)$/; + +/** + * Claude's Explanatory and Learning output styles wrap asides in a + * `` `★ Insight ───` `` line and a `` `───` `` line. Claude rarely leaves a blank + * line before the closer, so CommonMark folds the closer, and any prose right after + * it, into the preceding list item or paragraph. Blocks are therefore found on + * source lines before parsing. Only top-level lines outside fenced code count. + * + * A block with no closer stays Markdown once the message completes, so a forgotten + * closer cannot fold the rest of the answer away. While streaming it runs to the end. + */ +export function splitAssistantInsights( + text: string, + options: { readonly streaming?: boolean } = {}, +): ReadonlyArray { + if (!text.includes(INSIGHT_MARKER)) + return [{ kind: "markdown", markdown: text, sourceOffset: 0 }]; + + const segments: AssistantInsightSegment[] = []; + let cursor = 0; + let fence: { readonly marker: string } | null = null; + let open: { readonly start: number; readonly bodyStart: number } | null = null; + const pushInsight = (start: number, body: string, next: number) => { + if (start > cursor) { + segments.push({ + kind: "markdown", + markdown: text.slice(cursor, start), + sourceOffset: cursor, + }); + } + segments.push({ kind: "insight", markdown: body, sourceOffset: start }); + cursor = next; + }; + + for (let start = 0; start < text.length;) { + const newline = text.indexOf("\n", start); + const next = newline === -1 ? text.length : newline + 1; + const line = text.slice(start, newline === -1 ? text.length : newline).replace(/\r$/, ""); + const lineStart = start; + start = next; + + if (fence) { + const [, marker = "", rest = ""] = FENCE_OPENER.exec(line) ?? []; + if (marker[0] === fence.marker[0] && marker.length >= fence.marker.length && !rest.trim()) { + fence = null; + } + continue; + } + const fenceOpening = FENCE_OPENER.exec(line); + if (fenceOpening?.[1] && !(fenceOpening[1][0] === "`" && fenceOpening[2]?.includes("`"))) { + fence = { marker: fenceOpening[1] }; + continue; + } + if (INSIGHT_OPENER.test(line)) { + open = { start: lineStart, bodyStart: next }; + continue; + } + if (open && INSIGHT_CLOSER.test(line)) { + const body = text.slice(open.bodyStart, lineStart); + if (body.trim()) pushInsight(open.start, body, next); + open = null; + } + } + + if (open && options.streaming) pushInsight(open.start, text.slice(open.bodyStart), text.length); + if (cursor < text.length) { + segments.push({ kind: "markdown", markdown: text.slice(cursor), sourceOffset: cursor }); + } + return segments; +} + +const previewParser = unified().use(remarkParse).freeze(); + +function plainText(node: Nodes): string { + if (node.type === "text" || node.type === "inlineCode") return node.value; + if (node.type === "image") return node.alt ?? ""; + if (node.type === "break") return " "; + return "children" in node ? node.children.map(plainText).join("") : ""; +} + +function firstTextBlock(node: Nodes): Nodes | undefined { + if (node.type === "paragraph" || node.type === "heading") return node; + if (!("children" in node)) return undefined; + for (const child of node.children) { + const block = firstTextBlock(child); + if (block) return block; + } + return undefined; +} + +/** The first paragraph of an insight as plain text, shown while the block is collapsed. */ +export function assistantInsightPreview(markdown: string): string { + const block = firstTextBlock(previewParser.parse(markdown)); + return block ? plainText(block).replace(/\s+/g, " ").trim() : ""; +} diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 767ffdf836545..c3854671e5b20 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -352,7 +352,3 @@ function remarkKeepWindowsPaths(this: Processor) { }, }); } - -export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); -} diff --git a/packages/shared/src/threadFindText.test.ts b/packages/shared/src/threadFindText.test.ts index 0dd6a87ae1dea..c362cb73d7196 100644 --- a/packages/shared/src/threadFindText.test.ts +++ b/packages/shared/src/threadFindText.test.ts @@ -77,6 +77,14 @@ it("keeps fence paths literal and indexes file-chip labels in user messages", () ).toEqual(["file.ts · L42"]); }); +it("indexes insight bodies line by line without their marker lines", () => { + expect( + assistantSegments( + "Before\n\n`★ Insight ─────`\nFirst line\nSecond line\n`─────`\nAfter without a gap", + ), + ).toEqual(["Before", "First line", " Second line", "After without a gap"]); +}); + it("indexes nested disclosure summaries and bodies in rendered order", () => { expect( assistantSegments( diff --git a/packages/shared/src/threadFindText.ts b/packages/shared/src/threadFindText.ts index a2e5b4dbb982d..ceb80895b57cc 100644 --- a/packages/shared/src/threadFindText.ts +++ b/packages/shared/src/threadFindText.ts @@ -25,11 +25,11 @@ import { parseComposerContextHref } from "./composerContextReferences.ts"; import { assistantCitationLabel, parseAssistantCitationHref } from "./assistantCitations.ts"; import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts"; import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts"; +import { splitAssistantInsights } from "./assistantInsights.ts"; import { unified } from "unified"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { - shouldPreserveAssistantLineBreaks, CHAT_MARKDOWN_REHYPE_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, @@ -220,11 +220,9 @@ export function searchableMessageSegments( return markdownThreadFindText(text, true, cwd, skills); } if (message.role !== "assistant") return null; - return markdownThreadFindText( - message.text || (message.streaming ? "" : "(empty response)"), - false, - cwd, - skills, - shouldPreserveAssistantLineBreaks(message.text), + const text = message.text || (message.streaming ? "" : "(empty response)"); + // Insight bodies render with their line breaks kept, and the block header is not indexed. + return splitAssistantInsights(text, { streaming: message.streaming }).flatMap((segment) => + markdownThreadFindText(segment.markdown, false, cwd, skills, segment.kind === "insight"), ); } From 5ad0e23e5f8a46d7a12f2c3595f46aa2fe964c1d Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 13 Nov 2026 16:51:39 -0300 Subject: [PATCH 02/87] feat(web): show thread and subagent tasks and usage --- apps/server/src/auth/RpcAuthorization.test.ts | 7 +- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../src/orchestration-v2/ProjectionStore.ts | 101 +++--- .../ProviderTurnControlService.test.ts | 1 + .../ThreadInsightsQuery.test.ts | 321 ++++++++++++++++++ .../orchestration-v2/ThreadInsightsQuery.ts | 253 ++++++++++++++ apps/server/src/server.ts | 4 +- .../src/telemetry/ProviderUsageAnalytics.ts | 29 +- apps/server/src/usage/UsageService.ts | 27 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 4 + apps/web/src/closedViewStore.ts | 6 + apps/web/src/components/RightPanelTabs.tsx | 4 + .../chat/RightPanelSurfaceContent.tsx | 9 + .../components/chat/ThreadDetailsPanel.tsx | 2 + .../components/chat/ThreadInsightsMenu.tsx | 38 +++ .../components/chat/ThreadInsightsPanel.tsx | 242 +++++++++++++ .../chat/ThreadLineageWorkflowRow.tsx | 16 +- ...hreadRelationshipsControl.browser.test.tsx | 1 + .../chat/ThreadRelationshipsControl.tsx | 10 + .../chat/TimelineUserMessageRow.tsx | 1 + .../src/components/chat/V2LifecycleRow.tsx | 92 +++-- .../components/chat/WorkflowOpeningBlock.tsx | 13 +- .../src/components/threadActionMenu.logic.ts | 11 + .../web/src/hooks/useThreadActionMenu.test.ts | 4 + apps/web/src/hooks/useThreadActionMenu.ts | 18 + apps/web/src/reopenClosedView.ts | 7 + apps/web/src/rightPanelStore.ts | 45 ++- apps/web/src/state/threadInsights.ts | 44 +++ docs/user/usage.md | 18 + packages/client-runtime/package.json | 4 + .../client-runtime/src/state/orchestration.ts | 6 + .../src/state/threadInsights.test.ts | 102 ++++++ .../src/state/threadInsights.ts | 89 +++++ packages/contracts/src/environment.ts | 1 + packages/contracts/src/orchestrationV2.ts | 48 +++ packages/contracts/src/rpc.ts | 10 + packages/contracts/src/server.ts | 1 + packages/shared/package.json | 4 + packages/shared/src/turnTokenUsage.ts | 31 ++ 42 files changed, 1515 insertions(+), 114 deletions(-) create mode 100644 apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts create mode 100644 apps/server/src/orchestration-v2/ThreadInsightsQuery.ts create mode 100644 apps/web/src/components/chat/ThreadInsightsMenu.tsx create mode 100644 apps/web/src/components/chat/ThreadInsightsPanel.tsx create mode 100644 apps/web/src/state/threadInsights.ts create mode 100644 packages/client-runtime/src/state/threadInsights.test.ts create mode 100644 packages/client-runtime/src/state/threadInsights.ts create mode 100644 packages/shared/src/turnTokenUsage.ts diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 88596577db3c6..1cf2eefae4a9e 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -14,6 +14,7 @@ import { AuthSourceControlWriteScope, AuthTerminalReadScope, AuthTerminalOperateScope, + ORCHESTRATION_V2_WS_METHODS, WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; @@ -69,7 +70,11 @@ describe("RPC authorization scopes", () => { }); it("lets thread readers observe and refresh checkout branches", () => { - for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) { + for (const method of [ + WS_METHODS.subscribeVcsBranch, + WS_METHODS.vcsRefreshBranch, + ORCHESTRATION_V2_WS_METHODS.getThreadInsights, + ]) { expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope); } }); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 7823c3a146228..bc1288ebb40b8 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -42,6 +42,7 @@ export const RPC_REQUIRED_SCOPES = { [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.getThreadInsights]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 2c79189878e8a..ff4ae6d343ccd 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -294,6 +294,7 @@ export const make = Effect.gen(function* () { linkFence: true, mcpApprovalCodes: true, mcpHostedApproval: true, + threadInsights: true, shellThreadFamilies: true, shellOlderSettled: true, }, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 3f120a39f1870..2e924f2017644 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -14,6 +14,7 @@ const RPC_AGGREGATES = { [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: "orchestration", + [ORCHESTRATION_V2_WS_METHODS.getThreadInsights]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: "orchestration", diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e90a82786953f..41798c3497d66 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1,3 +1,4 @@ +import { PlanId } from "@t3tools/contracts"; import type { ProjectThreadAwarenessV2Input } from "@t3tools/shared/agentAwareness"; import { applyOrchestrationV2ThreadVisit, pendingGuestMessageCount } from "@t3tools/contracts"; import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts"; @@ -25,7 +26,6 @@ import type { OrchestrationV2ExecutionNode, OrchestrationV2PlanArtifact, OrchestrationV2PendingRuntimeRequestSummary, - PlanId, OrchestrationV2ConversationMessage, OrchestrationV2ContextTransfer, OrchestrationV2DomainEvent, @@ -665,6 +665,9 @@ export interface ProjectionStoreV2Shape { threadId: ThreadId, providerTurnId: ProviderTurnId, ) => Effect.Effect; + readonly getLatestTodoList: ( + threadId: ThreadId, + ) => Effect.Effect; readonly getPlan: ( threadId: ThreadId, planId: PlanId, @@ -3736,46 +3739,7 @@ export const layer: Layer.Layer = (field) => field === "plans" || field === "runs" || field === "providerThreads", )) ? [] - : yield* sql<{ - readonly plan_id: string; - readonly run_id: string; - readonly provider_thread_id: string | null; - readonly last_plan_id: string; - }>` - WITH latest_owner AS MATERIALIZED ( - SELECT plan.plan_id, owner.run_id, owner.provider_thread_id - FROM orchestration_v2_projection_plans AS plan - INNER JOIN orchestration_v2_projection_runs AS owner - ON owner.thread_id = plan.thread_id AND owner.run_id = plan.run_id - WHERE plan.thread_id = ${threadId} - AND plan.kind = 'todo_list' AND plan.status <> 'superseded' - ORDER BY owner.ordinal DESC, plan.plan_id DESC - LIMIT 1 - ) - SELECT COALESCE(CASE WHEN EXISTS ( - SELECT 1 FROM orchestration_v2_projection_plans - WHERE thread_id = ${threadId} AND run_id = owner.run_id - AND kind = 'todo_list' AND status <> 'superseded' - AND plan_id <> owner.plan_id - ) THEN ( - -- Plan UUIDs cannot order replacements within a run. - SELECT plan.plan_id - FROM orchestration_v2_projection_turn_items AS item - CROSS JOIN orchestration_v2_projection_plans AS plan - ON plan.plan_id = json_extract(item.payload_json, '$.planId') - WHERE item.run_id = owner.run_id AND item.thread_id = ${threadId} - AND item.type = 'todo_list' - AND plan.run_id = owner.run_id AND plan.thread_id = ${threadId} - AND plan.kind = 'todo_list' AND plan.status <> 'superseded' - ORDER BY item.ordinal DESC - LIMIT 1 - ) END, owner.plan_id) AS plan_id, owner.run_id, owner.provider_thread_id, - ( - SELECT MAX(plan_id) FROM orchestration_v2_projection_plans - WHERE thread_id = ${threadId} AND run_id = owner.run_id - ) AS last_plan_id - FROM latest_owner AS owner - `; + : yield* latestTodoOwner(threadId); const [ thread, @@ -5584,6 +5548,60 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + const getLatestTodoList: ProjectionStoreV2Shape["getLatestTodoList"] = Effect.fn( + "ProjectionStore.getLatestTodoList", + )( + function* (threadId) { + const owners = yield* latestTodoOwner(threadId); + return owners[0] === undefined + ? undefined + : yield* getPlan(threadId, PlanId.make(owners[0].plan_id)); + }, + (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), + ); + + const latestTodoOwner = (threadId: ThreadId) => sql<{ + readonly plan_id: string; + readonly run_id: string; + readonly provider_thread_id: string | null; + readonly last_plan_id: string; + }>` + WITH latest_owner AS MATERIALIZED ( + SELECT plan.plan_id, owner.run_id, owner.provider_thread_id + FROM orchestration_v2_projection_plans AS plan + INNER JOIN orchestration_v2_projection_runs AS owner + ON owner.thread_id = plan.thread_id AND owner.run_id = plan.run_id + WHERE plan.thread_id = ${threadId} + AND plan.kind = 'todo_list' AND plan.status <> 'superseded' + AND owner.status <> 'rolled_back' + ORDER BY owner.ordinal DESC, plan.plan_id DESC + LIMIT 1 + ) + SELECT COALESCE(CASE WHEN EXISTS ( + SELECT 1 FROM orchestration_v2_projection_plans + WHERE thread_id = ${threadId} AND run_id = owner.run_id + AND kind = 'todo_list' AND status <> 'superseded' + AND plan_id <> owner.plan_id + ) THEN ( + -- Plan UUIDs cannot order replacements within a run. + SELECT plan.plan_id + FROM orchestration_v2_projection_turn_items AS item + CROSS JOIN orchestration_v2_projection_plans AS plan + ON plan.plan_id = json_extract(item.payload_json, '$.planId') + WHERE item.run_id = owner.run_id AND item.thread_id = ${threadId} + AND item.type = 'todo_list' + AND plan.run_id = owner.run_id AND plan.thread_id = ${threadId} + AND plan.kind = 'todo_list' AND plan.status <> 'superseded' + ORDER BY item.ordinal DESC + LIMIT 1 + ) END, owner.plan_id) AS plan_id, owner.run_id, owner.provider_thread_id, + ( + SELECT MAX(plan_id) FROM orchestration_v2_projection_plans + WHERE thread_id = ${threadId} AND run_id = owner.run_id + ) AS last_plan_id + FROM latest_owner AS owner + `; + const getPlan: ProjectionStoreV2Shape["getPlan"] = (threadId, planId) => sql .withTransaction( @@ -9019,6 +9037,7 @@ export const layer: Layer.Layer = getThreadRecords(threadId, fields, filter).pipe(NodeSqliteClient.readOnly), getRuntimeRequest: readOnReader(getRuntimeRequest), getPlan: readOnReader(getPlan), + getLatestTodoList: readOnReader(getLatestTodoList), getProviderControlContext: readOnReader(getProviderControlContext), getLimitRecoveryCandidates: readOnReader(getLimitRecoveryCandidates), getLimitRecoveryWakeAt: readOnReader(getLimitRecoveryWakeAt), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 3ede421ad72ab..cf7a075f7e904 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -232,6 +232,7 @@ it.effect( getTurnStartContext: () => Effect.die("unused"), getTurnStartHistory: () => Effect.die("unused"), getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"), + getLatestTodoList: () => Effect.undefined, getPlan: () => Effect.die("unused"), hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"), getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"), diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts new file mode 100644 index 0000000000000..dc94aaca8b7c2 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -0,0 +1,321 @@ +import { expect, it } from "@effect/vitest"; +import { + EnvironmentId, + EventId, + MessageId, + NodeId, + PlanId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2DomainEvent, + type OrchestrationV2Subagent, + type OrchestrationV2Run, + type TurnTokenUsage, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as UsageService from "../usage/UsageService.ts"; +import * as ThreadInsightsQuery from "./ThreadInsightsQuery.ts"; + +const now = DateTime.makeUnsafe("2026-11-13T12:00:00Z"); +const instance = ProviderInstanceId.make("codex"); +const driver = ProviderDriverKind.make("codex"); +const selection = { instanceId: instance, model: "gpt-6.1-sol" }; +const layerStore = ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)); +const layer = ThreadInsightsQuery.layer.pipe( + Layer.provideMerge(layerStore), + Layer.provide( + Layer.mock(UsageService.UsageService)({ + priceRecords: (records) => Effect.succeed(records.map(() => 0.1)), + }), + ), +); + +const apply = Effect.fn("test.insights.apply")(function* (event: OrchestrationV2DomainEvent) { + yield* (yield* ProjectionStore.ProjectionStoreV2).apply(event); +}); +const thread = Effect.fn("test.insights.thread")(function* ( + name: string, + parent: ThreadId | null = null, + relationship: "fork" | "subagent" | null = null, +) { + const id = ThreadId.make(name); + yield* apply({ + id: EventId.make(`thread:${name}`), + type: "thread.created", + threadId: id, + occurredAt: now, + payload: { + id, + projectId: ProjectId.make("project"), + title: name, + createdBy: "user", + creationSource: "web", + providerInstanceId: instance, + modelSelection: selection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: parent, + relationshipToParent: relationship, + rootThreadId: parent ?? id, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + return id; +}); +const run = Effect.fn("test.insights.run")(function* ( + threadId: ThreadId, + ordinal: number, + status: OrchestrationV2Run["status"] = "completed", +) { + const id = RunId.make(`${threadId}:run:${ordinal}`); + const payload: OrchestrationV2Run = { + id, + threadId, + ordinal, + providerInstanceId: instance, + modelSelection: selection, + providerThreadId: null, + userMessageId: MessageId.make(`${id}:message`), + rootNodeId: NodeId.make(`${id}:node`), + activeAttemptId: null, + status, + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }; + yield* apply({ + id: EventId.make(`${id}:event`), + type: "run.created", + threadId, + occurredAt: now, + payload, + }); + return payload; +}); +const agent = Effect.fn("test.insights.agent")(function* ( + parent: ThreadId, + child: ThreadId, + origin: OrchestrationV2Subagent["origin"] = "app_owned", + remote = false, +) { + const id = NodeId.make(`${parent}:${child}:agent`); + yield* apply({ + id: EventId.make(`${id}:event`), + type: "subagent.updated", + threadId: parent, + occurredAt: now, + payload: { + id, + threadId: parent, + runId: null, + parentNodeId: NodeId.make(`${parent}:node`), + origin, + createdBy: "agent", + driver, + providerInstanceId: instance, + providerThreadId: ProviderThreadId.make(`${child}:provider`), + childThreadId: remote ? null : child, + ...(remote + ? { + remoteChild: { + environmentId: EnvironmentId.make("remote"), + threadId: child, + label: "Remote", + }, + } + : {}), + nativeTaskRef: null, + prompt: "", + title: child, + model: selection.model, + status: "completed", + result: null, + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }); +}); +const usage = (inputTokens: number): TurnTokenUsage => ({ + usageScope: "main_agent", + usageStatus: "complete", + inputTokens, + outputTokens: 10, + cachedInputTokens: 20, + cacheCreationTokens: 0, + hasSubagents: true, + models: [selection.model], + otherUsage: { inputTokens: 9000, outputTokens: 9000 }, +}); +const turn = Effect.fn("test.insights.turn")(function* ( + threadId: ThreadId, + name: string, + owner: ThreadId, + counters?: TurnTokenUsage, +) { + yield* apply({ + id: EventId.make(`${name}:event`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make(name), + providerThreadId: ProviderThreadId.make(`${owner}:provider`), + nodeId: NodeId.make(`${name}:node`), + runAttemptId: null, + nativeTurnRef: null, + ordinal: 1, + status: "completed", + startedAt: now, + completedAt: now, + ...(counters === undefined ? {} : { turnTokenUsage: counters }), + }, + }); +}); +const plan = Effect.fn("test.insights.plan")(function* ( + owner: OrchestrationV2Run, + name: string, + completed: boolean, + status: "active" | "superseded" = "active", +) { + const planId = PlanId.make(name); + const nodeId = NodeId.make(`${name}:node`); + const steps = [ + { id: "step", text: name, status: completed ? ("completed" as const) : ("running" as const) }, + ]; + yield* apply({ + id: EventId.make(`${name}:plan`), + type: "plan.updated", + threadId: owner.threadId, + occurredAt: now, + payload: { + id: planId, + threadId: owner.threadId, + runId: owner.id, + nodeId, + status, + kind: "todo_list", + steps, + }, + }); + yield* apply({ + id: EventId.make(`${name}:item`), + type: "turn-item.updated", + threadId: owner.threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${name}:item`), + threadId: owner.threadId, + runId: owner.id, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + status: "completed", + startedAt: now, + completedAt: now, + parentItemId: null, + ordinal: name === "z-first" ? 1 : 2, + title: name, + updatedAt: now, + type: "todo_list", + planId, + steps, + }, + }); +}); + +it.layer(layer)("ThreadInsightsQuery", (it) => { + it.effect( + "counts spent own turns once, attributes native children, excludes forks, and keeps missing and remote usage explicit", + () => + Effect.gen(function* () { + const root = yield* thread("root"); + const child = yield* thread("child", root, "subagent"); + const native = yield* thread("native", child, "subagent"); + yield* thread("fork", root, "fork"); + yield* run(root, 1, "rolled_back"); + yield* agent(root, child); + yield* agent(child, native, "provider_native"); + yield* agent(native, root); + yield* agent(root, ThreadId.make("remote-child"), "app_owned", true); + yield* agent(root, ThreadId.make("deleted-child")); + yield* turn(root, "root-turn", root, usage(100)); + yield* turn(child, "native-turn", native, usage(50)); + + yield* turn(child, "unreported-turn", child); + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: root, + }); + expect(result.rows.map((row) => row.threadId)).toEqual([root, child, native]); + expect(result.rows.map((row) => row.usage.inputTokens)).toEqual([100, undefined, 50]); + expect(result.rows.map((row) => row.usage.turns)).toEqual([1, 1, 1]); + expect(result.rows[1]?.usage.status).toBe("unavailable"); + expect(result.rows[0]?.usage.hasOtherUsage).toBe(true); + expect(result.remotes[0]?.threadId).toBe("remote-child"); + expect(result.unavailableThreadIds).toEqual(["deleted-child"]); + expect(result.truncated).toBe(false); + const direct = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: native, + }); + expect(direct.rows.find((row) => row.threadId === native)?.usage.inputTokens).toBe(50); + }), + ); + + it.effect("selects todo lists by item order, ignores superseded lists and rolled-back runs", () => + Effect.gen(function* () { + const root = yield* thread("plans"); + const store = yield* ProjectionStore.ProjectionStoreV2; + expect(yield* store.getLatestTodoList(root)).toBeUndefined(); + const initial = yield* run(root, 1); + yield* plan(initial, "z-first", false); + yield* plan(initial, "a-second", true); + yield* plan(initial, "superseded", false, "superseded"); + const rolledBack = yield* run(root, 2, "rolled_back"); + yield* plan(rolledBack, "rolled-back", false); + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: root, + }); + expect(result.rows[0]?.steps?.[0]?.text).toBe("a-second"); + expect(result.rows[0]?.steps?.[0]?.status).toBe("completed"); + }), + ); + it.effect("bounds wide families and reports omitted children", () => + Effect.gen(function* () { + const root = yield* thread("wide"); + for (let index = 0; index < 201; index++) { + const child = yield* thread(`wide-child-${index}`, root, "subagent"); + yield* agent(root, child); + } + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: root, + }); + expect(result.rows).toHaveLength(200); + expect(result.truncated).toBe(true); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts new file mode 100644 index 0000000000000..3c60303b2a8a7 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts @@ -0,0 +1,253 @@ +import { + OrchestrationV2GetThreadProjectionError, + type OrchestrationV2GetThreadInsightsResult, + type OrchestrationV2ThreadInsightsRow, + type OrchestrationV2ProviderTurn, + type ThreadId, +} from "@t3tools/contracts"; +import { combinedStatus, sumOf } from "@t3tools/shared/turnTokenUsage"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as UsageService from "../usage/UsageService.ts"; +import type { PricedRecord } from "../usage/usagePricing.ts"; + +const MAX_THREADS = 200; +const MAX_TURNS = 20_000; + +export class ThreadInsightsQuery extends Context.Service< + ThreadInsightsQuery, + { + readonly read: (input: { + readonly threadId: ThreadId; + }) => Effect.Effect< + OrchestrationV2GetThreadInsightsResult, + OrchestrationV2GetThreadProjectionError + >; + } +>()("t3/orchestration-v2/ThreadInsightsQuery") {} + +const make = Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const pricing = yield* UsageService.UsageService; + const read = Effect.fn("ThreadInsightsQuery.read")( + function* (input: { readonly threadId: ThreadId }) { + const rows: OrchestrationV2ThreadInsightsRow[] = []; + const remotes: OrchestrationV2GetThreadInsightsResult["remotes"][number][] = []; + const unavailableThreadIds: ThreadId[] = []; + const queue = [ + { + threadId: input.threadId, + parentThreadId: null as ThreadId | null, + status: null as string | null, + }, + ]; + const queued = new Set([input.threadId]); + const remoteKeys = new Set(); + const turns = new Map(); + const childOwners = new Map(); + let truncated = false; + for (let index = 0; index < queue.length; index++) { + const target = queue[index]!; + const snapshot = yield* store + .getThreadRecords(target.threadId, [ + "runs", + "subagents", + "providerTurns", + "providerThreads", + ]) + .pipe( + Effect.catch((cause) => + target.threadId === input.threadId ? Effect.fail(cause) : Effect.succeed(null), + ), + ); + if (snapshot === null) { + unavailableThreadIds.push(target.threadId); + continue; + } + const plan = yield* store.getLatestTodoList(target.threadId); + const latestRun = snapshot.runs.reduce<(typeof snapshot.runs)[number] | null>( + (held, run) => (held === null || run.ordinal > held.ordinal ? run : held), + null, + ); + rows.push({ + threadId: target.threadId, + parentThreadId: target.parentThreadId, + title: snapshot.thread.title, + status: target.status ?? latestRun?.status ?? "idle", + providerInstanceIds: [ + ...new Set(snapshot.providerThreads.map((thread) => thread.providerInstanceId)), + ], + steps: plan?.kind === "todo_list" ? plan.steps : null, + usage: { + status: "unavailable", + turns: 0, + measuredTurns: 0, + costUsd: null, + unpricedTurns: 0, + hasOtherUsage: false, + }, + }); + for (const agent of snapshot.subagents) { + if (agent.remoteChild !== undefined) { + const remote = agent.remoteChild; + const key = `${remote.environmentId.length}:${remote.environmentId}${remote.threadId}`; + if (remoteKeys.has(key)) continue; + if (queue.length + remotes.length >= MAX_THREADS) { + truncated = true; + continue; + } + remoteKeys.add(key); + remotes.push({ + environmentId: remote.environmentId, + threadId: remote.threadId, + parentThreadId: target.threadId, + title: remote.title ?? agent.title ?? "Subagent", + status: agent.status, + }); + } else if (agent.childThreadId !== null) { + if (agent.providerThreadId !== null) + childOwners.set(agent.providerThreadId, agent.childThreadId); + if (queued.has(agent.childThreadId)) continue; + if (queue.length + remotes.length >= MAX_THREADS) { + truncated = true; + continue; + } + queued.add(agent.childThreadId); + queue.push({ + threadId: agent.childThreadId, + parentThreadId: target.threadId, + status: agent.status, + }); + } + } + // Some adapters keep native-child turns on the parent projection. Opening the + // child directly must still find those turns without charging the parent's own work. + let inheritedNativeTurns: readonly OrchestrationV2ProviderTurn[] = []; + if ( + target.threadId === input.threadId && + snapshot.thread.lineage.relationshipToParent === "subagent" && + snapshot.thread.lineage.parentThreadId !== null + ) { + const parentId = snapshot.thread.lineage.parentThreadId; + const parent = yield* store + .getThreadRecords(parentId, ["subagents"]) + .pipe(Effect.orElseSucceed(() => null)); + const nativeOwner = parent?.subagents.find( + (agent) => + agent.childThreadId === target.threadId && agent.origin === "provider_native", + ); + if (nativeOwner?.providerThreadId != null) { + const recorded = yield* store + .getThreadRecords(parentId, ["providerTurns"], { + providerTurnThreadIds: [nativeOwner.providerThreadId], + }) + .pipe(Effect.orElseSucceed(() => null)); + if (recorded === null) unavailableThreadIds.push(target.threadId); + else inheritedNativeTurns = recorded.providerTurns; + } + } + for (const turn of [...snapshot.providerTurns, ...inheritedNativeTurns]) { + const held = turns.get(turn.id); + if (held === undefined && turns.size >= MAX_TURNS) { + truncated = true; + continue; + } + // Copies are routed between parent and child projections. Prefer the final counters. + const rank = (value: OrchestrationV2ProviderTurn) => + value.turnTokenUsage?.usageStatus === "complete" + ? 2 + : value.turnTokenUsage === undefined + ? 0 + : 1; + if (held === undefined || rank(turn) > rank(held.turn)) + turns.set(turn.id, { turn, owner: target.threadId }); + } + } + const rowsById = new Map(rows.map((row) => [row.threadId, row])); + const owned = new Map(); + for (const entry of turns.values()) { + const child = childOwners.get(entry.turn.providerThreadId); + const owner = child !== undefined && rowsById.has(child) ? child : entry.owner; + const list = owned.get(owner) ?? []; + list.push(entry.turn); + owned.set(owner, list); + } + const priced: PricedRecord[] = []; + const priceIds: string[] = []; + for (const { turn } of turns.values()) { + const usage = turn.turnTokenUsage; + if (usage?.usageStatus !== "complete" || usage.models?.length !== 1) continue; + priceIds.push(turn.id); + priced.push({ + model: usage.models[0]!, + totals: { + uncachedInputTokens: Math.max( + 0, + usage.inputTokens - (usage.cachedInputTokens ?? 0) - (usage.cacheCreationTokens ?? 0), + ), + cachedInputTokens: usage.cachedInputTokens ?? 0, + cacheCreationTokens: usage.cacheCreationTokens ?? 0, + outputTokens: usage.outputTokens, + reasoningTokens: usage.reasoningTokens ?? 0, + }, + reportedCostUsd: null, + speed: "standard", + }); + } + const costs = yield* pricing.priceRecords(priced); + const byTurn = new Map(priceIds.map((id, index) => [id, costs[index] ?? null])); + const resultRows = rows.map((row) => { + const rowTurns = owned.get(row.threadId) ?? []; + const usages = rowTurns.map((turn) => turn.turnTokenUsage); + const measured = usages.filter((usage) => usage !== undefined); + const costValues = rowTurns.map((turn) => byTurn.get(turn.id) ?? null); + const knownCosts = costValues.filter((cost) => cost !== null); + const usage = { + status: combinedStatus(usages), + turns: rowTurns.length, + measuredTurns: measured.filter((value) => value.usageStatus !== "unavailable").length, + costUsd: knownCosts.length === 0 ? null : knownCosts.reduce((a, b) => a + b, 0), + unpricedTurns: rowTurns.length - knownCosts.length, + hasOtherUsage: measured.some( + (value) => + (value.otherUsage?.inputTokens ?? 0) > 0 || (value.otherUsage?.outputTokens ?? 0) > 0, + ), + }; + const totals: { + inputTokens?: number; + cachedInputTokens?: number; + cacheCreationTokens?: number; + outputTokens?: number; + reasoningTokens?: number; + } = {}; + for (const field of [ + "inputTokens", + "cachedInputTokens", + "cacheCreationTokens", + "outputTokens", + "reasoningTokens", + ] as const) { + const sum = sumOf(measured, field, false); + if (sum !== undefined) totals[field] = sum; + } + return { ...row, usage: { ...usage, ...totals } }; + }); + return { rows: resultRows, remotes, unavailableThreadIds, truncated }; + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: "Failed to read thread tasks and usage.", + cause, + }), + ), + ), + ); + return ThreadInsightsQuery.of({ read }); +}); +export const layer = Layer.effect(ThreadInsightsQuery, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9353fa2f508a8..9530bde09669b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,3 +1,4 @@ +import * as ThreadInsightsQuery from "./orchestration-v2/ThreadInsightsQuery.ts"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay"; import * as Random from "effect/Random"; @@ -588,9 +589,10 @@ const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( ), ); -const layerOrchestrationApplication = Layer.merge( +const layerOrchestrationApplication = Layer.mergeAll( CheckpointDiffQuery.layer, NativeChildWorkQuery.layer, + ThreadInsightsQuery.layer.pipe(Layer.provide(layerUsage), Layer.provide(ProjectionStoreV2.layer)), ).pipe(Layer.provideMerge(layerCheckpointStore), Layer.provideMerge(layerOrchestrationV2Runtime)); const layerThreadSettlementWorker = Layer.effectDiscard( diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index ce7f29ba1f8d5..14fc8dbac2a1d 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -1,3 +1,4 @@ +import { sumOf, combinedStatus } from "@t3tools/shared/turnTokenUsage"; /** * Provider token reporting: one `provider.turn.completed` per provider turn and one * `provider.request.completed` per run, built from the same turns so each counts once. @@ -214,34 +215,6 @@ function requestKind(origin: ProviderTurnOrigin | undefined) { return origin.createdBy; } -function sumOf( - usages: ReadonlyArray, - field: - | "inputTokens" - | "cachedInputTokens" - | "cacheCreationTokens" - | "outputTokens" - | "reasoningTokens", - requireAll: boolean, -): number | undefined { - const values = usages.map((usage) => usage[field]); - const known = values.filter((value) => value !== undefined); - if (known.length === 0 || (requireAll && known.length < values.length)) return undefined; - return known.reduce((sum, value) => sum + value, 0); -} - -/** complete only when every turn is complete; partial when any turn has counts. */ -function combinedStatus(usages: ReadonlyArray) { - if (usages.length > 0 && usages.every((usage) => usage?.usageStatus === "complete")) { - return "complete"; - } - return usages.some( - (usage) => usage?.inputTokens !== undefined || usage?.outputTokens !== undefined, - ) - ? "partial" - : "unavailable"; -} - interface RequestTurn { readonly child: boolean; readonly segment: ProviderTurnSegment | undefined; diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index a55532913c3c6..17254d8610d59 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -40,7 +40,13 @@ import type { UsageRecord, } from "@t3tools/provider-core/server/usage"; import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; -import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts"; +import { + createOverrideRateTable, + parseRateTable, + type RateTable, + priceUsage, + type PricedRecord, +} from "./usagePricing.ts"; import { listTranscriptFiles, readDirectoryVolumeId, @@ -148,6 +154,9 @@ export class UsageService extends Context.Service< { readonly readSummary: (input: UsageSummaryInput) => Effect.Effect; readonly refreshRates: Effect.Effect; + readonly priceRecords: ( + records: readonly PricedRecord[], + ) => Effect.Effect; } >()("t3/usage/UsageService") {} @@ -1140,7 +1149,21 @@ export const make = Effect.gen(function* () { return yield* Deferred.await(deferred); }); - return { readSummary, refreshRates, awaitPersisted } as const; + const priceRecords = Effect.fn("UsageService.priceRecords")(function* ( + records: readonly PricedRecord[], + ) { + if (records.length === 0) return []; + yield* ensureRates(false); + const settings = yield* readSettings; + const overrides = createOverrideRateTable(settings.usagePriceOverrides); + const aliases = resolveModelAliases(settings.usageModelAliases); + return records.map((record) => { + const model = aliases.get(record.model) ?? record.model; + const priced = priceUsage(rates, { ...record, model }, overrides); + return priced.costSource === "unpriced" ? null : priced.costUsd; + }); + }); + return { readSummary, refreshRates, priceRecords, awaitPersisted } as const; }); export const layer = Layer.effect(UsageService, make); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index c4470e0905c8a..b04c560931314 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -1,3 +1,4 @@ +import * as ThreadInsightsQuery from "./orchestration-v2/ThreadInsightsQuery.ts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -814,6 +815,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(BackgroundPolicy.BackgroundPolicy)({}), Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}), Layer.mock(NativeChildWorkQuery.NativeChildWorkQuery)({}), + Layer.mock(ThreadInsightsQuery.ThreadInsightsQuery)({}), Layer.mock(CommandOutputHub.CommandOutputHub)({}), Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }), Layer.mock(DeviceService.DeviceService)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1f2a148734d4e..cc49048d6d072 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,3 +1,4 @@ +import * as ThreadInsightsQuery from "./orchestration-v2/ThreadInsightsQuery.ts"; import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; @@ -1504,6 +1505,7 @@ export const layerWsRpc = ( const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner; const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter; const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const threadInsights = yield* ThreadInsightsQuery.ThreadInsightsQuery; const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery; const keybindings = yield* Keybindings.Keybindings; const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; @@ -1869,6 +1871,7 @@ export const layerWsRpc = ( ? {} : { managedPolicy: serverSettings.managedPolicy }), shellResumeCompletionMarker: true, + threadInsights: true, shellThreadFamilies: true, threadLinkMetadata: true, shellOlderSettled: true, @@ -2001,6 +2004,7 @@ export const layerWsRpc = ( threadManagement.forceStopThread(input), [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) => readWorkflowScript({ scriptPath: input.scriptPath }), + [ORCHESTRATION_V2_WS_METHODS.getThreadInsights]: (input) => threadInsights.read(input), [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: (input) => nativeChildWork.getNativeChildWork(input), [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) => diff --git a/apps/web/src/closedViewStore.ts b/apps/web/src/closedViewStore.ts index b5db7bd741bef..60c88c49c30fc 100644 --- a/apps/web/src/closedViewStore.ts +++ b/apps/web/src/closedViewStore.ts @@ -83,6 +83,12 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => { typeof surface.target.name === "string" && (surface.target.platform === "ios" || surface.target.platform === "android"))) ); + case "thread-insights": + return ( + typeof surface.environmentId === "string" && + typeof surface.threadId === "string" && + (surface.section === "tasks" || surface.section === "usage") + ); case "side-chat": return typeof surface.threadId === "string" && surface.id === `side-chat:${surface.threadId}`; case "pull-request": diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index d220385e28142..32aeb87204bc2 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -594,6 +594,8 @@ function surfaceTitle( return "Pull requests"; case "device": return surface.title ?? surface.target?.name ?? "Device"; + case "thread-insights": + return "Tasks & usage"; case "side-chat": return "Side chat"; case "preview": { @@ -684,6 +686,8 @@ function SurfaceIcon({ ); case "pull-requests": return ; + case "thread-insights": + return ; case "side-chat": return ; case "device": diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 5ba6985e19d21..3346513b912b1 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -1,3 +1,4 @@ +import { ThreadInsightsPanel } from "./ThreadInsightsPanel"; import type { EditorId, EnvironmentId, @@ -173,6 +174,14 @@ export function RightPanelSurfaceContent(props: { } case "pull-requests": return ; + case "thread-insights": + return visible ? ( + + ) : null; case "side-chat": // Not lazy: revealing a suspended tiptap editor tears down its view and crashes the composer. return ( diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 4942080dbb2d2..a11e9940828f7 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -1,3 +1,4 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; import type { EditorId, EnvironmentId, @@ -179,6 +180,7 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { }; return ( <> +
{show.environment || show.openIn || show.scripts ? ( + useRightPanelStore.getState().openThreadInsights(parent, target, section); + return ( + + }> + + + + open("tasks")}> + + View tasks + + open("usage")}> + + View usage + + + + ); +} diff --git a/apps/web/src/components/chat/ThreadInsightsPanel.tsx b/apps/web/src/components/chat/ThreadInsightsPanel.tsx new file mode 100644 index 0000000000000..5d9d8d88200cf --- /dev/null +++ b/apps/web/src/components/chat/ThreadInsightsPanel.tsx @@ -0,0 +1,242 @@ +import type { ScopedThreadRef, UsageLimitSourceSnapshots } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { useAtomValue, RegistryContext } from "@effect/atom-react"; +import { useContext, useEffect, useRef } from "react"; +import { threadInsightsViewAtom } from "../../state/threadInsights"; +import { RefreshCwIcon, ChevronDownIcon } from "lucide-react"; +import { useServerConfigs, useThreadShells } from "../../state/entities"; +import { useEnvironmentProviders } from "../../state/environments"; +import { Button } from "../ui/button"; +import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "../ui/collapsible"; +import { ThreadDetailsUsage } from "./ThreadDetailsUsage"; + +const EMPTY_SOURCES: UsageLimitSourceSnapshots = []; +const number = (value: number | null | undefined) => + value === null || value === undefined ? "Not reported" : value.toLocaleString(); +const dollars = (value: number | null) => + value === null + ? "Unpriced" + : new Intl.NumberFormat(undefined, { + style: "currency", + currency: "USD", + maximumFractionDigits: 4, + }).format(value); + +export function ThreadInsightsPanel({ + target, + section, +}: { + target: ScopedThreadRef; + section: "tasks" | "usage"; +}) { + const merged = useAtomValue(threadInsightsViewAtom(scopedThreadKey(target))); + const registry = useContext(RegistryContext); + const configs = useServerConfigs(); + const providersByEnvironment = useEnvironmentProviders(); + const shells = useThreadShells(); + const keys = new Set( + merged.rows.map((row) => + scopedThreadKey({ environmentId: row.environmentId, threadId: row.threadId }), + ), + ); + const signature = shells + .filter((shell) => + keys.has(scopedThreadKey({ environmentId: shell.environmentId, threadId: shell.id })), + ) + .map((shell) => `${shell.id}:${shell.updatedAt}`) + .join("|"); + const previous = useRef(signature); + const queries = merged.queries; + const refresh = () => { + for (const query of queries) registry.refresh(query); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Debounce shell changes into the mounted RPC query cache; no timer survives panel closure. + useEffect(() => { + if (previous.current === signature) return; + const timer = setTimeout(() => { + previous.current = signature; + for (const query of queries) registry.refresh(query); + }, 500); + return () => clearTimeout(timer); + }, [signature, queries, registry]); + return ( +
+
+

Tasks & usage

+ +
+ {merged.errors.map((error) => ( +

+ {error} +

+ ))} + {merged.pending.map((ref) => ( +

+ {ref.title}:{" "} + {configs.get(ref.environmentId)?.threadInsights === true + ? "Loading or unavailable" + : "Environment unavailable or server update required"}{" "} + · not included +

+ ))} + {merged.truncated ? ( +

Partial view: the family limit was reached.

+ ) : null} + {merged.unavailable > 0 ? ( +

+ {merged.unavailable} thread records unavailable · not included +

+ ) : null} + + + + Tasks ·{" "} + {merged.tasks.lists === 0 + ? "No task lists reported" + : `${merged.tasks.done}/${merged.tasks.total} reported steps`} + + + {merged.tasks.total > 0 ? ( + + ) : null} +

+ Reported steps across this thread and its subagents. Lists may describe overlapping + work. +

+ {merged.rows.map((row) => ( + + + + + {row.title} + + {row.status} ·{" "} + {row.steps === null + ? "No task list reported" + : `${row.steps.filter((step) => step.status === "completed").length}/${row.steps.length} steps`} + + + + + {row.steps === null ? ( +

No task list reported

+ ) : row.steps.length === 0 ? ( +

No steps in this list

+ ) : ( +
    + {row.steps.map((step) => ( +
  • + + {step.status === "completed" + ? "✓" + : step.status === "running" + ? "◉" + : "○"} + + {step.text} +
  • + ))} +
+ )} +
+
+ ))} +
+
+ + + + Usage · {merged.partial ? "Partial recorded usage" : "Recorded usage"} + + +
+
Input (includes cache)
+
{number(merged.inputTokens)}
+
Cache read
+
{number(merged.cachedInputTokens)}
+
Cache write
+
{number(merged.cacheCreationTokens)}
+
Output (includes reasoning)
+
{number(merged.outputTokens)}
+
API-equivalent estimate
+
{dollars(merged.costUsd)}
+
+

+ Standard-rate estimate, not your subscription bill. Unreported cache tokens are priced + as uncached input.{" "} + {merged.unpricedTurns > 0 + ? `${merged.unpricedTurns} turns unpriced or missing a complete breakdown.` + : ""} +

+ {merged.rows.map((row) => ( +
+

{row.title}

+

+ {row.usage.status} · {row.usage.measuredTurns}/{row.usage.turns} turns reported +

+

+ {number(row.usage.inputTokens)} input · {number(row.usage.outputTokens)} output ·{" "} + {dollars(row.usage.costUsd)} +

+ {row.usage.hasOtherUsage ? ( +

+ Provider extra usage is not added: it may overlap subagent usage. +

+ ) : null} +
+ ))} +

Subscription limits

+

+ Account-wide, across all threads and devices. Per-chat quota: not reported by providers. +

+ {[ + ...new Map( + merged.rows.flatMap((row) => + row.providerInstanceIds.map( + (instanceId) => + [ + `${row.environmentId}:${instanceId}`, + { environmentId: row.environmentId, instanceId }, + ] as const, + ), + ), + ).values(), + ].map(({ environmentId, instanceId }) => ( +
+

+ {providersByEnvironment + .get(environmentId) + ?.find((provider) => provider.instanceId === instanceId)?.displayName ?? + instanceId} +

+ +
+ ))} +
+
+
+ ); +} diff --git a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx index 4cfb23350e912..5d28814aa0bb6 100644 --- a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx +++ b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx @@ -1,3 +1,5 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; +import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import { workflowMemberModelSelection, type SubagentWorkflowGroup, @@ -50,6 +52,7 @@ function phaseStatusLabel(phase: SubagentWorkflowGroup["phases"][number]) { } function WorkflowMemberRow({ + parentRef, member, providerInstanceId, provider, @@ -58,6 +61,7 @@ function WorkflowMemberRow({ driver, onOpen, }: { + parentRef: ScopedThreadRef; member: RuntimeSubagent; providerInstanceId: ProviderInstanceId; provider: ServerProvider | undefined; @@ -69,7 +73,13 @@ function WorkflowMemberRow({ const threadId = member.childThreadId; const canOpen = threadId !== null; return ( -
  • +
  • + {threadId !== null ? ( + + ) : null} {phase.members.map((member) => ( ( ({ })); vi.mock(import("../../state/entities"), () => ({ + useServerConfigs: (() => new Map()) as never, useQuietThreadShell: (() => null) as never, useThreadProjection: ((ref: unknown) => ref === null ? null : { projection: state.projection }) as never, diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 49c69ff4fadee..e8187e1cee2b0 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -1,3 +1,5 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; import { useAtomValue } from "@effect/atom-react"; import { threadKey } from "@t3tools/client-runtime/state/entities"; import { ThreadDetailsControl } from "./ThreadDetailsControl"; @@ -261,6 +263,7 @@ function currentSubagent( * the thread there, when this client is connected to that environment. */ function RemoteSubagentRow(props: { + readonly parentRef: ScopedThreadRef; readonly agent: RemoteSubagent; readonly provider: ServerProvider | undefined; }) { @@ -275,6 +278,10 @@ function RemoteSubagentRow(props: { }); return (
  • + + {isMergeTarget ? (
    @@ -1023,6 +1032,7 @@ export function ThreadRelationshipsPanel(props: { visibleRows.map((row) => "remote" in row ? ( ctx.onOpenThread(ThreadId.make(threadId))} diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 40fffaf608412..96e9ffaaf695b 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -1,3 +1,4 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; import { ThreadHoverCardPopup } from "../ThreadHoverCard"; import { AgentElapsed } from "./AgentElapsed"; import { projectedSubagentsToRuntime } from "@t3tools/client-runtime/state/subagentRuntime"; @@ -504,43 +505,62 @@ function SubagentTimelineLink(props: { const className = "group/subagent flex w-full min-w-0 items-center gap-2.5 rounded-md px-2 py-1.5 text-left"; return ( - - - {content} -
    - ) : ( - - ) - } - /> - - : null} - model={agent?.model ?? null} - modelSelection={agent?.modelSelection} - status={liveStatus} - result={agent?.result ?? props.result} - progress={agent?.progress ?? props.progress} +
    +
    + + + {content} +
    + ) : ( + + ) + } + /> + + : null + } + model={agent?.model ?? null} + modelSelection={agent?.modelSelection} + status={liveStatus} + result={agent?.result ?? props.result} + progress={agent?.progress ?? props.progress} + /> + + +
    + {(remote?.threadId ?? threadId) ? ( + -
    -
    + ) : null} +
  • ); } diff --git a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx index 3526bbf931a3a..18ec34c179069 100644 --- a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx +++ b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx @@ -1,3 +1,5 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; +import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { isTerminalSubagentStatus, @@ -36,6 +38,7 @@ function scriptMarkdown(script: string) { } export function WorkflowOpeningBlock(props: { + readonly parentRef?: ScopedThreadRef | null | undefined; readonly opening: WorkflowOpening; readonly environmentId: EnvironmentId; readonly onOpenThread: (threadId: string) => void; @@ -49,6 +52,7 @@ export function WorkflowOpeningBlock(props: { +
  • + {props.parentRef && threadId !== null ? ( + + ) : null} > { const items: ReadonlyArray> = [ + ...(state.canViewInsights + ? [ + { id: "view-tasks" as const, label: "View tasks", icon: "list-todo" }, + { id: "view-usage" as const, label: "View usage", icon: "chart-no-axes-combined" }, + ] + : []), ...(state.canFind ? [{ id: "find" as const, label: "Find in thread", icon: "text-search" }] : []), diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.ts index 3c8255b04c088..e152983e00500 100644 --- a/apps/web/src/hooks/useThreadActionMenu.test.ts +++ b/apps/web/src/hooks/useThreadActionMenu.test.ts @@ -46,7 +46,11 @@ vi.mock("../state/session", () => ({ readEnvironmentScope: (environmentId: string, scope: string) => scope === AuthOrchestrationOperateScope && state.granted.has(environmentId), })); +vi.mock("../rightPanelStore", () => ({ + useRightPanelStore: { getState: () => ({ openThreadInsights: () => {} }) }, +})); vi.mock("../state/entities", () => ({ + useServerConfigs: () => new Map(), readEnvironmentServerConfigLoaded: () => true, readEnvironmentSupportsAutoSettleOptOut: () => true, readThreadShell: () => ({ diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index bf22bd066b9a4..a2b20d923030f 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -1,3 +1,6 @@ +import { buildThreadRouteParams } from "../threadRoutes"; +import { useServerConfigs } from "../state/entities"; +import { useRightPanelStore } from "../rightPanelStore"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { requestCustomSnooze } from "../components/CustomSnoozeDialog"; import { openGuestShareDialog } from "../components/chat/guestShareDialogState"; @@ -10,6 +13,7 @@ import { import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; @@ -67,6 +71,7 @@ export function useThreadActionMenu(input: { readonly canShareWithGuest: boolean; }) { const { threadRef, projectCwd, onStartRename, onFind, canShareWithGuest } = input; + const serverConfigs = useServerConfigs(); const router = useRouter(); const projects = useProjects(); const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -138,6 +143,9 @@ export function useThreadActionMenu(input: { const isRegeneratingTitle = thread.titleRegeneration != null; const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); const items = buildThreadActionMenuItems({ + canViewInsights: + serverConfigs.get(threadRef.environmentId)?.threadInsights === true && + readEnvironmentScope(threadRef.environmentId, AuthOrchestrationReadScope), canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), canFind: onFind !== undefined, branch: thread.branch ?? null, @@ -194,6 +202,16 @@ export function useThreadActionMenu(input: { } }; switch (action) { + case "view-tasks": + case "view-usage": + useRightPanelStore + .getState() + .openThreadInsights(threadRef, threadRef, action === "view-tasks" ? "tasks" : "usage"); + void router.navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }); + return; case "find": onFind?.(threadRef); return; diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index 899a1b223ec71..2368673f4bad7 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -154,6 +154,13 @@ export async function reopenClosedView( case "pull-request": panels.openPullRequest(ref, surface); break; + case "thread-insights": + panels.openThreadInsights( + ref, + { environmentId: surface.environmentId, threadId: surface.threadId }, + surface.section, + ); + break; case "side-chat": panels.openSideChat(ref, surface.threadId); break; diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 7de186174d348..e8b5fc476692f 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -22,6 +22,7 @@ const RIGHT_PANEL_KINDS = [ "pull-request", "pull-requests", "side-chat", + "thread-insights", ] as const; export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number]; @@ -77,6 +78,13 @@ export type RightPanelSurface = revealUrl?: string; detailTab?: PullRequestDetailTab; } + | { + id: `thread-insights:${string}`; + kind: "thread-insights"; + environmentId: EnvironmentId; + threadId: ThreadId; + section: "tasks" | "usage"; + } | { id: "pull-requests"; kind: "pull-requests" } | { id: `side-chat:${string}`; kind: "side-chat"; threadId: ThreadId }; @@ -125,7 +133,15 @@ interface RightPanelStoreState { ) => boolean; open: ( ref: ScopedThreadRef, - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "terminal" | "pull-request" | "side-chat" | "thread-insights" + >, + ) => void; + openThreadInsights: ( + ref: ScopedThreadRef, + target: ScopedThreadRef, + section: "tasks" | "usage", ) => void; openSideChat: (ref: ScopedThreadRef, threadId: ThreadId) => void; openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void; @@ -191,7 +207,10 @@ interface RightPanelStoreState { toggleVisibility: (ref: ScopedThreadRef) => void; toggle: ( ref: ScopedThreadRef, - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "terminal" | "pull-request" | "side-chat" | "thread-insights" + >, ) => void; setThreadPanelOpen: ( ref: ScopedThreadRef, @@ -214,7 +233,10 @@ const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { }; const singletonSurface = ( - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "preview" | "terminal" | "pull-request" | "side-chat" | "thread-insights" + >, ): RightPanelSurface => { switch (kind) { case "diff": @@ -733,6 +755,23 @@ export const useRightPanelStore = create()( ); }), ), + openThreadInsights: (ref, target, section) => + set((state) => + userAction(state, scopedThreadKey(ref), (current) => { + const surface: RightPanelSurface = { + id: `thread-insights:${scopedThreadKey(target)}`, + kind: "thread-insights", + environmentId: target.environmentId, + threadId: target.threadId, + section, + }; + const next = upsertSurface(current, surface); + return { + ...next, + surfaces: next.surfaces.map((entry) => (entry.id === surface.id ? surface : entry)), + }; + }), + ), openSideChat: (ref, threadId) => set((state) => userAction(state, scopedThreadKey(ref), (current) => diff --git a/apps/web/src/state/threadInsights.ts b/apps/web/src/state/threadInsights.ts new file mode 100644 index 0000000000000..0413e8ea64bd8 --- /dev/null +++ b/apps/web/src/state/threadInsights.ts @@ -0,0 +1,44 @@ +import { Atom, AsyncResult } from "effect/reactivity"; +import * as Option from "effect/Option"; +import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { + mergeThreadInsights, + type ThreadInsightsAnswer, +} from "@t3tools/client-runtime/state/thread-insights"; +import { orchestrationEnvironment } from "./orchestration"; +import { environmentPresentations } from "./presentation"; + +export const threadInsightsViewAtom = Atom.family((key: string) => + Atom.make((get) => { + const target = parseScopedThreadKey(key); + if (target === null) throw new Error("Invalid thread insights target"); + const configs = get(environmentPresentations.serverConfigsAtom); + const answers = new Map(); + const queue = [target]; + const visited = new Set(); + const queries: ReturnType[] = []; + const errors = new Set(); + for (let index = 0; index < queue.length && visited.size < 200; index++) { + const ref = queue[index]!; + const nextKey = scopedThreadKey(ref); + if (visited.has(nextKey)) continue; + visited.add(nextKey); + if (configs.get(ref.environmentId)?.threadInsights !== true) continue; + const query = orchestrationEnvironment.threadInsights({ + environmentId: ref.environmentId, + input: { threadId: ref.threadId }, + }); + queries.push(query); + const result = get(query); + if (AsyncResult.isFailure(result)) { + errors.add("An environment could not report tasks and usage."); + continue; + } + const data = Option.getOrNull(AsyncResult.value(result)); + if (data === null) continue; + answers.set(nextKey, { target: ref, data }); + queue.push(...data.remotes); + } + return { ...mergeThreadInsights(target, answers), queries, errors: [...errors] }; + }), +); diff --git a/docs/user/usage.md b/docs/user/usage.md index e6b3a46d5a14e..4336d0690b1dd 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -57,6 +57,24 @@ saved totals first, then updates them when Cursor's API responds. If recent work is missing or a new model shows no cost, refresh to rescan session history and update model pricing. +## Inspect one thread + +On web and desktop, choose **View usage** in a thread's menu, or in the menu beside a +subagent in the work log or Lineage. The **Tasks & usage** side panel combines the thread +and its subagents, including descendants on connected environments. Forks and side chats +are separate. Expand a row to inspect its tasks, or open **View tasks** to start there. +The progress count describes reported steps; different agents' lists can overlap. + +Usage comes from recorded turns. Missing provider reports, unavailable children, and limits on +large families are marked as partial. Input includes cache tokens, and output includes reasoning. +Extra provider usage that may overlap child turns is shown without adding it again. + +Cost is an estimate at standard API rates for turns with one reported model. Missing cache +breakdowns are treated as uncached input; mixed or unknown models stay unpriced. This estimate +can differ from Usage's transcript-based history and does not represent a subscription charge. +Subscription limits are account-wide across threads and devices. Providers do not report how +much of a subscription's quota an individual thread consumed. + ## Set custom model prices On web or desktop, open the environment dropdown on **Usage**, then choose **Model prices** to add, diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d1e74151e53e3..4a6b2f00c68bb 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -566,6 +566,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./state/thread-insights": { + "types": "./src/state/threadInsights.ts", + "import": "./src/state/threadInsights.ts" } }, "scripts": { diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index 657a9cd62dab1..dbf707fd8819b 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -192,6 +192,12 @@ export function createOrchestrationEnvironmentAtoms( idleTtlMs: 300_000, }), // Mounted only while a subagent inspector is open; running children change between opens. + threadInsights: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:orchestration:thread-insights", + tag: ORCHESTRATION_V2_WS_METHODS.getThreadInsights, + staleTimeMs: 0, + idleTtlMs: 0, + }), nativeChildWork: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:native-child-work", tag: ORCHESTRATION_V2_WS_METHODS.getNativeChildWork, diff --git a/packages/client-runtime/src/state/threadInsights.test.ts b/packages/client-runtime/src/state/threadInsights.test.ts new file mode 100644 index 0000000000000..2689734744604 --- /dev/null +++ b/packages/client-runtime/src/state/threadInsights.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + EnvironmentId, + ThreadId, + type OrchestrationV2GetThreadInsightsResult, + type ScopedThreadRef, +} from "@t3tools/contracts"; +import { scopedThreadKey } from "../environment/scoped.ts"; +import { mergeThreadInsights, type ThreadInsightsAnswer } from "./threadInsights.ts"; + +const ref = (environment: string, thread: string): ScopedThreadRef => ({ + environmentId: EnvironmentId.make(environment), + threadId: ThreadId.make(thread), +}); +const row = ( + threadId: string, + inputTokens: number, +): OrchestrationV2GetThreadInsightsResult["rows"][number] => ({ + threadId: ThreadId.make(threadId), + parentThreadId: null, + title: threadId, + status: "completed", + providerInstanceIds: [], + steps: [{ id: "a", text: "Step", status: "completed" }], + usage: { + status: "complete", + turns: 1, + measuredTurns: 1, + inputTokens, + outputTokens: 10, + costUsd: null, + unpricedTurns: 1, + hasOtherUsage: false, + }, +}); +const answer = ( + target: ScopedThreadRef, + overrides: Partial = {}, +): ThreadInsightsAnswer => ({ + target, + data: { rows: [], remotes: [], unavailableThreadIds: [], truncated: false, ...overrides }, +}); + +describe("mergeThreadInsights", () => { + it("keeps missing remote usage partial, scopes duplicate thread IDs by environment, and discards unreachable old answers", () => { + const root = ref("local", "root"); + const remote = ref("remote", "root"); + const stale = ref("stale", "old"); + const localAnswer = answer(root, { + rows: [row("root", 100)], + remotes: [{ ...remote, parentThreadId: root.threadId, title: "Remote", status: "completed" }], + }); + const answers = new Map([ + [scopedThreadKey(root), localAnswer], + [scopedThreadKey(stale), answer(stale, { rows: [row("old", 9000)] })], + ]); + const pending = mergeThreadInsights(root, answers); + expect(pending.inputTokens).toBe(100); + expect(pending.partial).toBe(true); + expect(pending.pending).toEqual([ + { ...remote, parentThreadId: root.threadId, title: "Remote", status: "completed" }, + ]); + answers.set( + scopedThreadKey(remote), + answer(remote, { + rows: [row("root", 300)], + remotes: [ + { ...root, parentThreadId: remote.threadId, title: "Cycle", status: "completed" }, + ], + }), + ); + const complete = mergeThreadInsights(root, answers); + expect(complete.rows).toHaveLength(2); + expect(complete.inputTokens).toBe(400); + expect(complete.tasks).toEqual({ done: 2, total: 2, lists: 2 }); + expect(complete.partial).toBe(false); + answers.set(scopedThreadKey(root), answer(root, { rows: [row("root", 100)] })); + expect(mergeThreadInsights(root, answers).inputTokens).toBe(100); + }); + + it("preserves unreported counters and incomplete local coverage", () => { + const root = ref("local", "root"); + const result = mergeThreadInsights( + root, + new Map([ + [ + scopedThreadKey(root), + answer(root, { + rows: [{ ...row("root", 100), steps: null }], + truncated: true, + unavailableThreadIds: [ThreadId.make("deleted")], + }), + ], + ]), + ); + expect(result.cachedInputTokens).toBeNull(); + expect(result.costUsd).toBeNull(); + expect(result.tasks).toEqual({ done: 0, total: 0, lists: 0 }); + expect(result.partial).toBe(true); + expect(result.unavailable).toBe(1); + }); +}); diff --git a/packages/client-runtime/src/state/threadInsights.ts b/packages/client-runtime/src/state/threadInsights.ts new file mode 100644 index 0000000000000..06d49e722dea6 --- /dev/null +++ b/packages/client-runtime/src/state/threadInsights.ts @@ -0,0 +1,89 @@ +import type { + EnvironmentId, + OrchestrationV2GetThreadInsightsResult, + ScopedThreadRef, +} from "@t3tools/contracts"; +import { scopedThreadKey } from "../environment/scoped.ts"; + +export interface ThreadInsightsAnswer { + readonly target: ScopedThreadRef; + readonly data: OrchestrationV2GetThreadInsightsResult; +} + +/** Only reachable answers contribute; a removed remote child must not leave stale spend behind. */ +export function mergeThreadInsights( + root: ScopedThreadRef, + answers: ReadonlyMap, +) { + const pending: (ScopedThreadRef & { title: string })[] = []; + const rows = new Map< + string, + OrchestrationV2GetThreadInsightsResult["rows"][number] & { environmentId: EnvironmentId } + >(); + const queue = [{ ...root, title: "This thread" }]; + const visited = new Set(); + let truncated = false; + let unavailable = 0; + for (let index = 0; index < queue.length; index++) { + const target = queue[index]!; + const key = scopedThreadKey(target); + if (visited.has(key)) continue; + if (visited.size >= 200) { + truncated = true; + break; + } + visited.add(key); + const answer = answers.get(key)?.data; + if (answer === undefined) { + pending.push(target); + continue; + } + truncated ||= answer.truncated; + unavailable += answer.unavailableThreadIds.length; + for (const row of answer.rows) { + const rowKey = scopedThreadKey({ + environmentId: target.environmentId, + threadId: row.threadId, + }); + if (rows.size >= 200 && !rows.has(rowKey)) { + truncated = true; + continue; + } + rows.set(rowKey, { ...row, environmentId: target.environmentId }); + } + queue.push(...answer.remotes); + } + const values = [...rows.values()]; + const lists = values.flatMap((row) => (row.steps === null ? [] : [row.steps])); + const sum = ( + field: "inputTokens" | "cachedInputTokens" | "cacheCreationTokens" | "outputTokens", + ) => { + const known = values.flatMap((row) => + row.usage[field] === undefined ? [] : [row.usage[field]!], + ); + return known.length === 0 ? null : known.reduce((a, b) => a + b, 0); + }; + const costs = values.flatMap((row) => (row.usage.costUsd === null ? [] : [row.usage.costUsd])); + return { + rows: values, + pending, + truncated, + unavailable, + partial: + truncated || + unavailable > 0 || + pending.length > 0 || + values.some((row) => row.usage.status !== "complete" || row.usage.hasOtherUsage), + tasks: { + lists: lists.length, + done: lists.flat().filter((step) => step.status === "completed").length, + total: lists.flat().length, + }, + inputTokens: sum("inputTokens"), + cachedInputTokens: sum("cachedInputTokens"), + cacheCreationTokens: sum("cacheCreationTokens"), + outputTokens: sum("outputTokens"), + costUsd: costs.length === 0 ? null : costs.reduce((a, b) => a + b, 0), + unpricedTurns: values.reduce((sum, row) => sum + row.usage.unpricedTurns, 0), + }; +} diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index e305efb51f838..757f5e9df52a5 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -201,6 +201,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ * The server config's flags of the same names. A server that names them here lets a client * load the shell snapshot before the socket opens, and answers its `resumeFrom`. */ + threadInsights: Schema.optionalKey(Schema.Boolean), shellThreadFamilies: Schema.optionalKey(Schema.Boolean), shellOlderSettled: Schema.optionalKey(Schema.Boolean), /** Publishes a pull request refresh when linked-thread answers change; older servers need polling. */ diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index bf6b53666f4d7..d01f5ff648c5a 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3767,6 +3767,49 @@ export type OrchestrationV2InternalCommand = typeof OrchestrationV2InternalComma export type OrchestrationV2ServerCommand = OrchestrationV2Command | OrchestrationV2InternalCommand; +export const OrchestrationV2ThreadInsightsUsage = Schema.Struct({ + status: Schema.Literals(["complete", "partial", "unavailable"]), + turns: NonNegativeInt, + measuredTurns: NonNegativeInt, + inputTokens: Schema.optionalKey(NonNegativeInt), + cachedInputTokens: Schema.optionalKey(NonNegativeInt), + cacheCreationTokens: Schema.optionalKey(NonNegativeInt), + outputTokens: Schema.optionalKey(NonNegativeInt), + reasoningTokens: Schema.optionalKey(NonNegativeInt), + costUsd: Schema.NullOr(Schema.Number), + unpricedTurns: NonNegativeInt, + hasOtherUsage: Schema.Boolean, +}); +export type OrchestrationV2ThreadInsightsUsage = typeof OrchestrationV2ThreadInsightsUsage.Type; + +export const OrchestrationV2ThreadInsightsRow = Schema.Struct({ + threadId: ThreadId, + parentThreadId: Schema.NullOr(ThreadId), + title: Schema.String, + status: Schema.String, + providerInstanceIds: Schema.Array(ProviderInstanceId), + steps: Schema.NullOr(Schema.Array(OrchestrationV2PlanStep)), + usage: OrchestrationV2ThreadInsightsUsage, +}); +export type OrchestrationV2ThreadInsightsRow = typeof OrchestrationV2ThreadInsightsRow.Type; + +export const OrchestrationV2GetThreadInsightsResult = Schema.Struct({ + rows: Schema.Array(OrchestrationV2ThreadInsightsRow), + remotes: Schema.Array( + Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + parentThreadId: ThreadId, + title: Schema.String, + status: Schema.String, + }), + ), + unavailableThreadIds: Schema.Array(ThreadId), + truncated: Schema.Boolean, +}); +export type OrchestrationV2GetThreadInsightsResult = + typeof OrchestrationV2GetThreadInsightsResult.Type; + export const ORCHESTRATION_V2_WS_METHODS = { dispatchCommand: "orchestration.dispatchCommand", getTurnDiff: "orchestration.getTurnDiff", @@ -3783,6 +3826,7 @@ export const ORCHESTRATION_V2_WS_METHODS = { getThreadProjection: "orchestration.getThreadProjection", getWorkflowScript: "orchestration.getWorkflowScript", getNativeChildWork: "orchestration.getNativeChildWork", + getThreadInsights: "orchestration.getThreadInsights", stopWorkflow: "orchestration.stopWorkflow", forceStopThread: "orchestration.forceStopThread", getTurnItem: "orchestration.getTurnItem", @@ -4490,6 +4534,10 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2GetWorkflowScriptInput, output: OrchestrationV2GetWorkflowScriptResult, }, + getThreadInsights: { + input: Schema.Struct({ threadId: ThreadId }), + output: OrchestrationV2GetThreadInsightsResult, + }, getNativeChildWork: { input: OrchestrationV2GetNativeChildWorkInput, output: OrchestrationV2GetNativeChildWorkResult, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index adba6dbaca71b..16a3a874342b0 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -1921,6 +1921,15 @@ const WsOrchestrationV2GetWorkflowScriptRpc = Rpc.make( }, ); +const WsOrchestrationV2GetThreadInsightsRpc = Rpc.make( + ORCHESTRATION_V2_WS_METHODS.getThreadInsights, + { + payload: OrchestrationV2RpcSchemas.getThreadInsights.input, + success: OrchestrationV2RpcSchemas.getThreadInsights.output, + error: Schema.Union([OrchestrationV2GetThreadProjectionError, EnvironmentAuthorizationError]), + }, +); + const WsOrchestrationV2GetNativeChildWorkRpc = Rpc.make( ORCHESTRATION_V2_WS_METHODS.getNativeChildWork, { @@ -2303,6 +2312,7 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2DispatchCommandRpc, WsOrchestrationV2GetWorkflowScriptRpc, WsOrchestrationV2GetNativeChildWorkRpc, + WsOrchestrationV2GetThreadInsightsRpc, WsOrchestrationV2StopWorkflowRpc, WsOrchestrationV2ForceStopThreadRpc, WsOrchestrationV2GetTurnItemRpc, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index e8bcda3a76f5d..21fe2422fdf6e 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -698,6 +698,7 @@ export const ServerConfig = Schema.Struct({ * The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and * `getThreadFamily` and `getWorktreeThreadIds` serve the rows it leaves out. */ + threadInsights: Schema.optionalKey(Schema.Boolean), shellThreadFamilies: Schema.optionalKey(Schema.Boolean), threadLinkMetadata: Schema.optionalKey(Schema.Boolean), /** diff --git a/packages/shared/package.json b/packages/shared/package.json index ba0b394f26d0c..b7c4a4637f80f 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -554,6 +554,10 @@ "./speech": { "types": "./src/speech.ts", "import": "./src/speech.ts" + }, + "./turnTokenUsage": { + "types": "./src/turnTokenUsage.ts", + "import": "./src/turnTokenUsage.ts" } }, "scripts": { diff --git a/packages/shared/src/turnTokenUsage.ts b/packages/shared/src/turnTokenUsage.ts new file mode 100644 index 0000000000000..96fad8c8f9c0b --- /dev/null +++ b/packages/shared/src/turnTokenUsage.ts @@ -0,0 +1,31 @@ +import type { TurnTokenUsage } from "@t3tools/contracts"; + +export function sumOf( + usages: ReadonlyArray, + field: + | "inputTokens" + | "cachedInputTokens" + | "cacheCreationTokens" + | "outputTokens" + | "reasoningTokens", + requireAll: boolean, +): number | undefined { + const values = usages.map((usage) => usage[field]); + const known = values.filter((value) => value !== undefined); + if (known.length === 0 || (requireAll && known.length < values.length)) return undefined; + return known.reduce((sum, value) => sum + value, 0); +} + +/** complete only when every turn is complete; partial when any turn has counts. */ +export function combinedStatus( + usages: ReadonlyArray, +): "complete" | "partial" | "unavailable" { + if (usages.length > 0 && usages.every((usage) => usage?.usageStatus === "complete")) { + return "complete"; + } + return usages.some( + (usage) => usage?.inputTokens !== undefined || usage?.outputTokens !== undefined, + ) + ? "partial" + : "unavailable"; +} From a2243dfa885c3c3cf614849bd41ba78d647c4ed8 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 13 Nov 2026 17:08:01 -0300 Subject: [PATCH 03/87] fix(web): correct native tasks and bound thread usage reads --- .../src/orchestration-v2/ProjectionStore.ts | 57 +++++++++++++++++- .../ProviderTurnControlService.test.ts | 1 + .../ThreadInsightsQuery.test.ts | 58 ++++++++++++++++++- .../orchestration-v2/ThreadInsightsQuery.ts | 50 ++++++++++------ apps/server/src/usage/UsageService.ts | 11 ++-- apps/server/src/usage/usagePricing.test.ts | 35 +++++++++++ apps/server/src/usage/usagePricing.ts | 16 +++++ apps/web/src/components/RightPanelTabs.tsx | 10 +++- docs/user/usage.md | 3 +- 9 files changed, 209 insertions(+), 32 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 41798c3497d66..eb1a591dccb6a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -534,6 +534,14 @@ export interface ProjectionStoreV2Shape { filter?: ProjectionRecordFilter, ) => Effect.Effect, ProjectionStoreV2Error>; + readonly getThreadProviderTurns: ( + threadId: ThreadId, + options: { readonly limit: number; readonly providerThreadIds?: readonly ProviderThreadId[] }, + ) => Effect.Effect< + { readonly providerTurns: readonly OrchestrationV2ProviderTurn[]; readonly truncated: boolean }, + ProjectionStoreV2Error + >; + readonly apply: ( event: OrchestrationV2DomainEvent, ) => Effect.Effect; @@ -5553,9 +5561,25 @@ export const layer: Layer.Layer = )( function* (threadId) { const owners = yield* latestTodoOwner(threadId); - return owners[0] === undefined + if (owners[0] !== undefined) + return yield* getPlan(threadId, PlanId.make(owners[0].plan_id)); + // Native children have provider turns and items but no orchestration run. + const runless = yield* sql<{ readonly plan_id: string }>` + SELECT plan.plan_id + FROM orchestration_v2_projection_plans AS plan + INNER JOIN orchestration_v2_projection_turn_items AS item + ON item.thread_id = plan.thread_id + AND json_extract(item.payload_json, '$.planId') = plan.plan_id + WHERE plan.thread_id = ${threadId} AND plan.run_id IS NULL + AND plan.kind = 'todo_list' AND plan.status <> 'superseded' + AND item.type = 'todo_list' AND item.run_id IS NULL + ORDER BY json_extract(item.payload_json, '$.startedAt') DESC, + item.ordinal DESC, plan.plan_id DESC + LIMIT 1 + `; + return runless[0] === undefined ? undefined - : yield* getPlan(threadId, PlanId.make(owners[0].plan_id)); + : yield* getPlan(threadId, PlanId.make(runless[0].plan_id)); }, (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), ); @@ -6324,6 +6348,34 @@ export const layer: Layer.Layer = Effect.mapError(controlReadError(threadId)), ); + const getThreadProviderTurns: ProjectionStoreV2Shape["getThreadProviderTurns"] = Effect.fn( + "ProjectionStore.getThreadProviderTurns", + )( + function* (threadId, options) { + yield* requireThread(threadId); + // Limit IDs before fetching bodies so historical payloads never enter the sort. + const rows = yield* sql` + SELECT payload_json FROM orchestration_v2_projection_provider_turns + WHERE rowid IN ( + SELECT rowid FROM orchestration_v2_projection_provider_turns + WHERE thread_id = ${threadId} + ${options.providerThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(options.providerThreadIds)}))`} + ORDER BY provider_thread_id ASC, ordinal ASC + LIMIT ${options.limit + 1} + ) + ORDER BY provider_thread_id ASC, ordinal ASC + `; + return { + providerTurns: yield* decodeRows( + decodeProviderTurnPayload, + threadId, + )(rows.slice(0, options.limit)), + truncated: rows.length > options.limit, + }; + }, + (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), + ); + const getThreadSnapshot: ProjectionStoreV2Shape["getThreadSnapshot"] = (threadId) => sql .withTransaction( @@ -9033,6 +9085,7 @@ export const layer: Layer.Layer = getNextTurnItemOrdinal: readOnReader(getNextTurnItemOrdinal), getTurnItem: readOnReader(getTurnItem), getMessagesById: readOnReader(getMessagesById), + getThreadProviderTurns: readOnReader(getThreadProviderTurns), getThreadRecords: (threadId, fields, filter) => getThreadRecords(threadId, fields, filter).pipe(NodeSqliteClient.readOnly), getRuntimeRequest: readOnReader(getRuntimeRequest), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index cf7a075f7e904..1d0c723f2d4ad 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -233,6 +233,7 @@ it.effect( getTurnStartHistory: () => Effect.die("unused"), getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"), getLatestTodoList: () => Effect.undefined, + getThreadProviderTurns: () => Effect.succeed({ providerTurns: [], truncated: false }), getPlan: () => Effect.die("unused"), hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"), getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"), diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts index dc94aaca8b7c2..b3e1f83570dcd 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -35,7 +35,7 @@ const layer = ThreadInsightsQuery.layer.pipe( Layer.provideMerge(layerStore), Layer.provide( Layer.mock(UsageService.UsageService)({ - priceRecords: (records) => Effect.succeed(records.map(() => 0.1)), + priceTurnRecords: (records) => Effect.succeed(records.map(() => 0.1)), }), ), ); @@ -197,10 +197,11 @@ const turn = Effect.fn("test.insights.turn")(function* ( }); }); const plan = Effect.fn("test.insights.plan")(function* ( - owner: OrchestrationV2Run, + owner: { readonly threadId: ThreadId; readonly id: RunId | null }, name: string, completed: boolean, status: "active" | "superseded" = "active", + ordinal = name === "z-first" ? 1 : 2, ) { const planId = PlanId.make(name); const nodeId = NodeId.make(`${name}:node`); @@ -239,7 +240,7 @@ const plan = Effect.fn("test.insights.plan")(function* ( startedAt: now, completedAt: now, parentItemId: null, - ordinal: name === "z-first" ? 1 : 2, + ordinal, title: name, updatedAt: now, type: "todo_list", @@ -304,6 +305,57 @@ it.layer(layer)("ThreadInsightsQuery", (it) => { expect(result.rows[0]?.steps?.[0]?.status).toBe("completed"); }), ); + it.effect("includes the latest runless native-child list in direct and family reads", () => + Effect.gen(function* () { + const root = yield* thread("native-plans-root"); + const child = yield* thread("native-plans-child", root, "subagent"); + yield* agent(root, child, "provider_native"); + const owner = { threadId: child, id: null }; + yield* plan(owner, "z-first", false, "active", 1); + yield* plan(owner, "a-latest", true, "active", 2); + yield* plan(owner, "superseded-native", false, "superseded", 3); + const query = yield* ThreadInsightsQuery.ThreadInsightsQuery; + for (const threadId of [root, child]) { + const result = yield* query.read({ threadId }); + expect(result.rows.find((row) => row.threadId === child)?.steps).toEqual([ + { id: "step", text: "a-latest", status: "completed" }, + ]); + } + }), + ); + it.effect("bounds provider-turn reads and exposes omitted rows before decoding", () => + Effect.gen(function* () { + const root = yield* thread("bounded-turns"); + const child = yield* thread("bounded-child", root, "subagent"); + yield* turn(root, "first", root, usage(10)); + yield* turn(root, "second", child, usage(20)); + const store = yield* ProjectionStore.ProjectionStoreV2; + const bounded = yield* store.getThreadProviderTurns(root, { limit: 1 }); + expect(bounded.providerTurns.map((item) => item.id)).toEqual(["second"]); + expect(bounded.truncated).toBe(true); + const filtered = yield* store.getThreadProviderTurns(root, { + limit: 1, + providerThreadIds: [ProviderThreadId.make(`${root}:provider`)], + }); + expect(filtered.providerTurns.map((item) => item.id)).toEqual(["first"]); + expect(filtered.truncated).toBe(false); + const exhausted = yield* store.getThreadProviderTurns(root, { limit: 0 }); + expect(exhausted.providerTurns).toEqual([]); + expect(exhausted.truncated).toBe(true); + }), + ); + it.effect("preserves native-child counters but marks a failed parent lookup partial", () => + Effect.gen(function* () { + const child = yield* thread("orphan-native", ThreadId.make("missing-parent"), "subagent"); + yield* turn(child, "local-native-turn", child, usage(50)); + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: child, + }); + expect(result.rows[0]?.usage.inputTokens).toBe(50); + expect(result.rows[0]?.usage.status).toBe("partial"); + expect(result.unavailableThreadIds).toEqual([child]); + }), + ); it.effect("bounds wide families and reports omitted children", () => Effect.gen(function* () { const root = yield* thread("wide"); diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts index 3c60303b2a8a7..f546ae20652f0 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts @@ -4,6 +4,7 @@ import { type OrchestrationV2ThreadInsightsRow, type OrchestrationV2ProviderTurn, type ThreadId, + type ProviderThreadId, } from "@t3tools/contracts"; import { combinedStatus, sumOf } from "@t3tools/shared/turnTokenUsage"; import * as Context from "effect/Context"; @@ -48,15 +49,26 @@ const make = Effect.gen(function* () { const turns = new Map(); const childOwners = new Map(); let truncated = false; + let remainingTurns = MAX_TURNS; + const readTurns = Effect.fn("ThreadInsightsQuery.readTurns")(function* ( + threadId: ThreadId, + providerThreadIds?: readonly ProviderThreadId[], + ) { + const result = yield* store.getThreadProviderTurns(threadId, { + limit: remainingTurns, + ...(providerThreadIds === undefined ? {} : { providerThreadIds }), + }); + remainingTurns -= result.providerTurns.length; + truncated ||= result.truncated; + return result.providerTurns; + }); for (let index = 0; index < queue.length; index++) { const target = queue[index]!; const snapshot = yield* store - .getThreadRecords(target.threadId, [ - "runs", - "subagents", - "providerTurns", - "providerThreads", - ]) + .getThreadRecords(target.threadId, ["runs", "subagents", "providerThreads"], { + runStatuses: [], + includeLatestRun: true, + }) .pipe( Effect.catch((cause) => target.threadId === input.threadId ? Effect.fail(cause) : Effect.succeed(null), @@ -66,6 +78,7 @@ const make = Effect.gen(function* () { unavailableThreadIds.push(target.threadId); continue; } + const ownTurns = yield* readTurns(target.threadId); const plan = yield* store.getLatestTodoList(target.threadId); const latestRun = snapshot.runs.reduce<(typeof snapshot.runs)[number] | null>( (held, run) => (held === null || run.ordinal > held.ordinal ? run : held), @@ -134,26 +147,21 @@ const make = Effect.gen(function* () { const parent = yield* store .getThreadRecords(parentId, ["subagents"]) .pipe(Effect.orElseSucceed(() => null)); + if (parent === null) unavailableThreadIds.push(target.threadId); const nativeOwner = parent?.subagents.find( (agent) => agent.childThreadId === target.threadId && agent.origin === "provider_native", ); if (nativeOwner?.providerThreadId != null) { - const recorded = yield* store - .getThreadRecords(parentId, ["providerTurns"], { - providerTurnThreadIds: [nativeOwner.providerThreadId], - }) - .pipe(Effect.orElseSucceed(() => null)); + const recorded = yield* readTurns(parentId, [nativeOwner.providerThreadId]).pipe( + Effect.orElseSucceed(() => null), + ); if (recorded === null) unavailableThreadIds.push(target.threadId); - else inheritedNativeTurns = recorded.providerTurns; + else inheritedNativeTurns = recorded; } } - for (const turn of [...snapshot.providerTurns, ...inheritedNativeTurns]) { + for (const turn of [...ownTurns, ...inheritedNativeTurns]) { const held = turns.get(turn.id); - if (held === undefined && turns.size >= MAX_TURNS) { - truncated = true; - continue; - } // Copies are routed between parent and child projections. Prefer the final counters. const rank = (value: OrchestrationV2ProviderTurn) => value.turnTokenUsage?.usageStatus === "complete" @@ -196,7 +204,7 @@ const make = Effect.gen(function* () { speed: "standard", }); } - const costs = yield* pricing.priceRecords(priced); + const costs = yield* pricing.priceTurnRecords(priced); const byTurn = new Map(priceIds.map((id, index) => [id, costs[index] ?? null])); const resultRows = rows.map((row) => { const rowTurns = owned.get(row.threadId) ?? []; @@ -204,8 +212,12 @@ const make = Effect.gen(function* () { const measured = usages.filter((usage) => usage !== undefined); const costValues = rowTurns.map((turn) => byTurn.get(turn.id) ?? null); const knownCosts = costValues.filter((cost) => cost !== null); + const status = combinedStatus(usages); const usage = { - status: combinedStatus(usages), + status: + unavailableThreadIds.includes(row.threadId) && status === "complete" + ? ("partial" as const) + : status, turns: rowTurns.length, measuredTurns: measured.filter((value) => value.usageStatus !== "unavailable").length, costUsd: knownCosts.length === 0 ? null : knownCosts.reduce((a, b) => a + b, 0), diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 17254d8610d59..6945ad74cc7d5 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -44,7 +44,7 @@ import { createOverrideRateTable, parseRateTable, type RateTable, - priceUsage, + priceTurnUsage, type PricedRecord, } from "./usagePricing.ts"; import { @@ -154,7 +154,7 @@ export class UsageService extends Context.Service< { readonly readSummary: (input: UsageSummaryInput) => Effect.Effect; readonly refreshRates: Effect.Effect; - readonly priceRecords: ( + readonly priceTurnRecords: ( records: readonly PricedRecord[], ) => Effect.Effect; } @@ -1149,7 +1149,7 @@ export const make = Effect.gen(function* () { return yield* Deferred.await(deferred); }); - const priceRecords = Effect.fn("UsageService.priceRecords")(function* ( + const priceTurnRecords = Effect.fn("UsageService.priceTurnRecords")(function* ( records: readonly PricedRecord[], ) { if (records.length === 0) return []; @@ -1159,11 +1159,10 @@ export const make = Effect.gen(function* () { const aliases = resolveModelAliases(settings.usageModelAliases); return records.map((record) => { const model = aliases.get(record.model) ?? record.model; - const priced = priceUsage(rates, { ...record, model }, overrides); - return priced.costSource === "unpriced" ? null : priced.costUsd; + return priceTurnUsage(rates, { ...record, model }, overrides); }); }); - return { readSummary, refreshRates, priceRecords, awaitPersisted } as const; + return { readSummary, refreshRates, priceTurnRecords, awaitPersisted } as const; }); export const layer = Layer.effect(UsageService, make); diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index 9aff0eb194766..1752ada0aab26 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -8,6 +8,7 @@ import { lookupRate, parseRateTable, priceUsage, + priceTurnUsage, } from "./usagePricing.ts"; const rate = (input: number, cacheRead?: number) => ({ @@ -269,6 +270,40 @@ describe("usage pricing", () => { ).toBeCloseTo(20_000 * 8e-6 + 280_000 * 8e-7 + 1_000 * 3e-5, 12); }); + it("leaves aggregated turns unpriced when requests may cross a context threshold", () => { + const table = parseRateTable({ + "tiered-model": { + ...rate(1e-6), + input_cost_per_token_above_100k_tokens: 2e-6, + output_cost_per_token_above_100k_tokens: 7.5e-6, + }, + "flat-model": rate(1e-6), + }); + const aggregate = (input: number, model = "tiered-model") => ({ + model, + speed: "standard" as const, + reportedCostUsd: null, + totals: { + uncachedInputTokens: input, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 100, + reasoningTokens: 0, + }, + }); + // Two 60K requests each use the base rate, unlike a single 120K request. + expect(priceTurnUsage(table, aggregate(60_000))).toBeCloseTo(0.0605); + expect(priceTurnUsage(table, aggregate(100_000))).toBeCloseTo(0.1005); + expect(priceTurnUsage(table, aggregate(120_000))).toBeNull(); + expect(priceUsage(table, aggregate(120_000)).costUsd).toBeCloseTo(0.24075); + expect(priceTurnUsage(table, aggregate(120_000, "flat-model"))).toBeCloseTo(0.1205); + expect(priceTurnUsage(table, aggregate(120_000, "unknown-model"))).toBeNull(); + const overrides = createOverrideRateTable({ + "tiered-model": { inputCostPerMillionTokens: 1, outputCostPerMillionTokens: 5 }, + }); + expect(priceTurnUsage(table, aggregate(120_000), overrides)).toBeCloseTo(0.1205); + }); + it("bills the long-context tier only above its threshold, filling missing tier fields from base", () => { const table = parseRateTable({ "gpt-6-sol": { diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 21a1bd02bb178..c4365f44e2953 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -395,6 +395,22 @@ export function priceUsage( }; } +/** Turn totals can combine requests on either side of a context-price threshold. */ +export function priceTurnUsage( + table: RateTable, + record: PricedRecord, + overrides?: RateTable, +): number | null { + const rate = overrides?.get(record.model.trim()) ?? recordRate(table, record); + if ( + rate === null || + rate.contextTiers.some((tier) => promptTokens(record.totals) > tier.thresholdTokens) + ) + return null; + const priced = priceUsage(table, record, overrides); + return priced.costSource === "unpriced" ? null : priced.costUsd; +} + export function cacheSavingsUsd( table: RateTable, record: PricedRecord, diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 32aeb87204bc2..59766d12c6d14 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -911,7 +911,15 @@ function RightPanelTab( ? scopeThreadRef(props.environmentId, surface.threadId) : null, ); - const title = sideChatShell?.title ?? props.title; + const insightsShell = useQuietThreadShell( + surface.kind === "thread-insights" + ? scopeThreadRef(surface.environmentId, surface.threadId) + : null, + ); + const title = + surface.kind === "thread-insights" + ? `Tasks & usage: ${insightsShell?.title ?? surface.threadId}` + : (sideChatShell?.title ?? props.title); const sideChatState = sideChatTabState(sideChatShell); const content = ( <> diff --git a/docs/user/usage.md b/docs/user/usage.md index 4336d0690b1dd..c540e867186ab 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -70,7 +70,8 @@ large families are marked as partial. Input includes cache tokens, and output in Extra provider usage that may overlap child turns is shown without adding it again. Cost is an estimate at standard API rates for turns with one reported model. Missing cache -breakdowns are treated as uncached input; mixed or unknown models stay unpriced. This estimate +breakdowns are treated as uncached input. Mixed or unknown models and turns whose aggregate +cannot establish the context pricing tier stay unpriced. This estimate can differ from Usage's transcript-based history and does not represent a subscription charge. Subscription limits are account-wide across threads and devices. Providers do not report how much of a subscription's quota an individual thread consumed. From 125463f78706d2585822f004582e9d1628b3ee9a Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 13 Nov 2026 17:20:09 -0300 Subject: [PATCH 04/87] fix(server): preserve insights when descendant turn reads fail --- .../ThreadInsightsQuery.test.ts | 30 +++++++++++++++++++ .../orchestration-v2/ThreadInsightsQuery.ts | 8 ++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts index b3e1f83570dcd..e8aeb06907654 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -21,6 +21,7 @@ import { import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as UsageService from "../usage/UsageService.ts"; @@ -356,6 +357,35 @@ it.layer(layer)("ThreadInsightsQuery", (it) => { expect(result.unavailableThreadIds).toEqual([child]); }), ); + it.effect("retains valid family rows when a descendant has a malformed provider turn", () => + Effect.gen(function* () { + const root = yield* thread("failure-root"); + const broken = yield* thread("failure-child", root, "subagent"); + const healthy = yield* thread("healthy-child", root, "subagent"); + yield* agent(root, broken); + yield* agent(root, healthy); + yield* plan(yield* run(root, 1), "root-task", true); + yield* plan(yield* run(broken, 1), "child-task", false); + yield* turn(root, "valid-root-turn", root, usage(100)); + yield* turn(broken, "malformed-turn", broken, usage(50)); + yield* turn(healthy, "valid-child-turn", healthy, usage(25)); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_provider_turns + SET payload_json = '{}' WHERE provider_turn_id = 'malformed-turn'`; + const query = yield* ThreadInsightsQuery.ThreadInsightsQuery; + const result = yield* query.read({ threadId: root }); + expect(result.rows.find((row) => row.threadId === root)?.usage.inputTokens).toBe(100); + expect(result.rows.find((row) => row.threadId === root)?.steps?.[0]?.text).toBe("root-task"); + expect(result.rows.find((row) => row.threadId === healthy)?.usage.inputTokens).toBe(25); + expect(result.rows.find((row) => row.threadId === broken)?.usage.status).toBe("unavailable"); + expect(result.rows.find((row) => row.threadId === broken)?.steps?.[0]?.text).toBe( + "child-task", + ); + expect(result.unavailableThreadIds).toEqual([broken]); + const error = yield* query.read({ threadId: broken }).pipe(Effect.flip); + expect(error._tag).toBe("OrchestrationV2GetThreadProjectionError"); + }), + ); it.effect("bounds wide families and reports omitted children", () => Effect.gen(function* () { const root = yield* thread("wide"); diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts index f546ae20652f0..1283069d16f74 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts @@ -78,7 +78,13 @@ const make = Effect.gen(function* () { unavailableThreadIds.push(target.threadId); continue; } - const ownTurns = yield* readTurns(target.threadId); + const ownTurns = yield* readTurns(target.threadId).pipe( + Effect.catch((cause) => { + if (target.threadId === input.threadId) return Effect.fail(cause); + unavailableThreadIds.push(target.threadId); + return Effect.succeed([]); + }), + ); const plan = yield* store.getLatestTodoList(target.threadId); const latestRun = snapshot.runs.reduce<(typeof snapshot.runs)[number] | null>( (held, run) => (held === null || run.ordinal > held.ordinal ? run : held), From 1b0526563e7121fab02d292b854a8aff1ce7fc93 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sat, 14 Nov 2026 13:56:58 -0300 Subject: [PATCH 05/87] ci(fork): sync upstream and build desktop installers --- .github/workflows/fork-build.yml | 129 +++++++++++++++++++++++++++++++ .github/workflows/fork-sync.yml | 24 ++++++ 2 files changed, 153 insertions(+) create mode 100644 .github/workflows/fork-build.yml create mode 100644 .github/workflows/fork-sync.yml diff --git a/.github/workflows/fork-build.yml b/.github/workflows/fork-build.yml new file mode 100644 index 0000000000000..c97815bd6f6b3 --- /dev/null +++ b/.github/workflows/fork-build.yml @@ -0,0 +1,129 @@ +name: Fork desktop builds +on: + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: fork-desktop-builds + cancel-in-progress: false +jobs: + linux: + if: github.repository == 'LaMarCab76/t3code' + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.meta.outputs.version }} + env: + T3CODE_DESKTOP_UPDATE_REPOSITORY: LaMarCab76/t3code + T3CODE_TELEMETRY_CHANNEL: dev + CSC_IDENTITY_AUTO_DISCOVERY: "false" + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb + with: + node-version-file: package.json + run-install: false + - run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config libfuse2 imagemagick + - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - id: meta + run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" + - run: node scripts/update-release-package-versions.ts "${{ steps.meta.outputs.version }}" + - run: node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64 --build-version "${{ steps.meta.outputs.version }}" --output-dir release + - run: | + node apps/server/scripts/cli.ts build-exe + mkdir -p cli-monitor/linux-x64 + cp native/resource-monitor/target/x86_64-unknown-linux-gnu/release/t3-resource-monitor cli-monitor/linux-x64/ + node scripts/build-cli-archive.ts --platform linux --arch x64 --version "${{ steps.meta.outputs.version }}" --resource-monitor-dir "$PWD/cli-monitor" --output-dir release-cli + node scripts/smoke-cli-archive.ts --archive release-cli/*.tar.gz --expect-version "${{ steps.meta.outputs.version }}" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: wsl-runtime + path: release-cli/*.tar.gz + if-no-files-found: error + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: desktop-linux + path: | + release/*.AppImage + release/*.deb + release/*.yml + if-no-files-found: error + desktop: + needs: linux + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15 + platform: mac + target: dmg + arch: arm64 + - runner: windows-2025 + platform: win + target: nsis + arch: x64 + runs-on: ${{ matrix.runner }} + defaults: + run: + shell: bash + env: + T3CODE_DESKTOP_UPDATE_REPOSITORY: LaMarCab76/t3code + T3CODE_TELEMETRY_CHANNEL: dev + CSC_IDENTITY_AUTO_DISCOVERY: "false" + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb + with: + node-version-file: package.json + run-install: false + - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - run: node scripts/update-release-package-versions.ts "${{ needs.linux.outputs.version }}" + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + if: matrix.platform == 'win' + with: + name: wsl-runtime + path: wsl-runtime + - run: | + args=() + if [[ "${{ matrix.platform }}" == win ]]; then args+=(--wsl-runtime "$PWD"/wsl-runtime/*.tar.gz); fi + node scripts/build-desktop-artifact.ts --platform "${{ matrix.platform }}" --target "${{ matrix.target }}" --arch "${{ matrix.arch }}" --build-version "${{ needs.linux.outputs.version }}" --output-dir release "${args[@]}" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: desktop-${{ matrix.platform }} + path: | + release/*.dmg + release/*.zip + release/*.exe + release/*.yml + release/*.blockmap + if-no-files-found: error + publish: + needs: [linux, desktop] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + path: artifacts + merge-multiple: true + - env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.linux.outputs.version }} + run: | + cd artifacts + sha256sum * > SHA256SUMS + gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code fork $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." diff --git a/.github/workflows/fork-sync.yml b/.github/workflows/fork-sync.yml new file mode 100644 index 0000000000000..9ba5d881e6531 --- /dev/null +++ b/.github/workflows/fork-sync.yml @@ -0,0 +1,24 @@ +name: Fork upstream sync +on: + schedule: + - cron: "23 */6 * * *" + workflow_dispatch: +permissions: + contents: write + actions: write +concurrency: + group: fork-upstream-sync + cancel-in-progress: false +jobs: + sync: + if: github.repository == 'LaMarCab76/t3code' + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd + with: + script: | + const { owner, repo } = context.repo; + const upstream = await github.rest.repos.getBranch({ owner: 'pingdotgg', repo: 't3code', branch: 'main' }); + const result = await github.rest.repos.merge({ owner, repo, base: 'main', head: upstream.data.commit.sha, commit_message: 'chore(fork): sync upstream main' }); + if (result.status === 204) return; + await github.rest.actions.createWorkflowDispatch({ owner, repo, workflow_id: 'fork-build.yml', ref: 'main' }); From 9920fd0634059f39971234b63e1b058655d89e5e Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sat, 14 Nov 2026 16:40:16 -0300 Subject: [PATCH 06/87] feat(threads): optionally snooze a thread until its next scheduled task run When a turn ends in a thread that has an upcoming scheduled task, the thread stays in Active even though nothing needs the user until the task runs. Add an opt-in server setting, snoozeThreadsUntilScheduledTask. A reactor listens for completed runs and, under the thread's dispatch lock, snoozes the thread until the soonest future run of an enabled task bound to it. The task's own run and automatic follow-ups (notifications, delegated completions) never trigger it, and neither does a turn that ends on a pending request or with other work queued. The existing dispatch wake brings the thread back when the task starts. Older servers hide the switch through the scheduledTaskSnooze capability. Co-Authored-By: Claude Opus 5.5 --- .../SettingsServerControlsRouteScreen.tsx | 1 + .../settings/ThreadSettingsSections.tsx | 17 ++ .../src/environment/ServerEnvironment.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 46 ++++ .../scheduledTasks/ScheduledTaskService.ts | 20 ++ .../ScheduledTaskSnoozeReactor.test.ts | 242 ++++++++++++++++++ .../ScheduledTaskSnoozeReactor.ts | 85 ++++++ apps/server/src/server.ts | 7 + .../components/settings/SettingsPanels.tsx | 28 ++ .../src/components/settings/settingsSearch.ts | 8 + docs/user/thread-sidebar.md | 6 + .../src/state/sharedSettings.ts | 1 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/settings.ts | 4 + 14 files changed, 468 insertions(+) create mode 100644 apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts create mode 100644 apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 5026a90e13b9a..08d54ad6e30ea 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -139,6 +139,7 @@ const AUTO_SETTLE_SETTING_KEYS: ReadonlySet = new Set([ "sidebarAutoSettleAfterDays", "autoResumeLimitedThreads", "snoozeLimitedThreads", + "snoozeThreadsUntilScheduledTask", ]); function planServerSettingsWrites( diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 41600619b3a47..a85176ad24ae6 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -101,6 +101,7 @@ export function AutoSettleSettingsRows(props: { patch: Partial & { autoResumeLimitedThreads?: boolean; snoozeLimitedThreads?: boolean; + snoozeThreadsUntilScheduledTask?: boolean; }, ) => props.write(patch); @@ -122,6 +123,10 @@ export function AutoSettleSettingsRows(props: { const disabledFor = (...keys: string[]) => disabled || managedSettingReason(displayTargets, ...keys) !== undefined; const afterDays = referenceSettings.sidebarAutoSettleAfterDays; + const supportsScheduledTaskSnooze = displayTargets.every( + (target) => + target.environment.serverConfig.environment.capabilities.scheduledTaskSnooze === true, + ); return ( @@ -145,6 +150,18 @@ export function AutoSettleSettingsRows(props: { /> ) : null} + {!projectSelected && supportsScheduledTaskSnooze ? ( + + writeToAll({ snoozeThreadsUntilScheduledTask: value })} + /> + + ) : null} Effect.Effect; + /** Snoozes only while `runId` is still the thread's last run and nothing else needs the user. */ + readonly autoSnoozeAfterRun: (input: { + readonly commandId: CommandId; + readonly threadId: ThreadId; + readonly runId: RunId; + readonly snoozedUntil: DateTime.Utc; + }) => Effect.Effect; readonly searchThreadStream: ( input: OrchestrationV2SearchThreadInput, ) => Stream.Stream; @@ -16124,6 +16131,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ); }), + autoSnoozeAfterRun: Effect.fn("OrchestratorV2.autoSnoozeAfterRun")(function (input) { + return threadDispatch.withLock( + input.threadId, + Effect.gen(function* () { + const { thread, runs, runtimeRequests } = yield* projectionStore + .getThreadRecords(input.threadId, ["runs", "runtimeRequests"]) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }), + ), + ); + const now = yield* DateTime.now; + const latest = runs.reduce( + (found, run) => (found === undefined || run.ordinal > found.ordinal ? run : found), + undefined, + ); + // The caller read the thread before this lock; a message sent since then wins. + if ( + latest?.id !== input.runId || + latest.status !== "completed" || + runs.some((run) => run.status === "queued" || isActiveRun(run)) || + runtimeRequests.some((request) => request.status === "pending") || + thread.archivedAt !== null || + thread.deletedAt !== null || + thread.settledOverride === "settled" || + (thread.snoozedUntil != null && + DateTime.toEpochMillis(thread.snoozedUntil) > DateTime.toEpochMillis(now)) || + DateTime.toEpochMillis(input.snoozedUntil) <= DateTime.toEpochMillis(now) + ) + return; + yield* dispatchWithReceiptEffect({ + type: "thread.snooze", + commandId: input.commandId, + threadId: input.threadId, + snoozedUntil: DateTime.formatIso(input.snoozedUntil), + }); + }), + ); + }), searchThreadStream: (input) => projectionStore .searchThreadStream(input) diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 05fdbe8b08992..a771a64e03843 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -425,6 +425,26 @@ const decodeRow = Effect.fnUntraced( ), ); +/** The soonest future run of an enabled task bound to this thread, or null. */ +export const nextRunForThread = Effect.fn("ScheduledTaskService.nextRunForThread")(function* ( + threadId: ThreadId, + now: DateTime.DateTime, +) { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ next_run_at: string }>` + SELECT next_run_at FROM scheduled_tasks + WHERE thread_id = ${threadId} AND enabled = 1 + AND next_run_at IS NOT NULL AND next_run_at > ${iso(now)} + ORDER BY next_run_at ASC + `.pipe(NodeSqliteClient.readOnly); + // next_run_at is freeform; the soonest parseable value wins. + for (const row of rows) { + const parsed = DateTime.make(row.next_run_at); + if (Option.isSome(parsed)) return DateTime.toUtc(parsed.value); + } + return null; +}); + export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(function* ( now: DateTime.DateTime, ) { diff --git a/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts new file mode 100644 index 0000000000000..da1b0e562993d --- /dev/null +++ b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts @@ -0,0 +1,242 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + MessageId, + type OrchestrationV2DomainEvent, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + RuntimeRequestId, + ScheduledTaskId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as ScheduledTaskSnoozeReactor from "./ScheduledTaskSnoozeReactor.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = (snoozeThreadsUntilScheduledTask: boolean) => + ScheduledTaskSnoozeReactor.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + ServerSettings.layerTest({ snoozeThreadsUntilScheduledTask }), + ProviderReplayHarness.layerWithRegistry( + { name: "scheduled-task-snooze" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + ), + ), + ); + +const threadId = ThreadId.make("thread:scheduled-snooze"); +const NEXT_RUN = "2030-01-01T09:00:00.000Z"; + +const insertTask = ( + sql: SqlClient.SqlClient, + task: { id: string; threadId: string; next: string | null; enabled?: number }, +) => + sql`INSERT INTO scheduled_tasks ${sql.insert({ + task_id: task.id, + title: "task", + prompt: "Run task", + enabled: task.enabled ?? 1, + schedule_json: '{"type":"interval","everyMs":60000}', + project_id: "project:scheduled-snooze", + thread_id: task.threadId, + workspace_strategy_json: '{"type":"root"}', + model_selection_json: '{"instanceId":"codex","model":"gpt-5"}', + runtime_mode: "full-access", + interaction_mode: "default", + created_by: "user", + creation_source: "web", + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + next_run_at: task.next, + last_run_at: null, + last_run_status: "never", + last_run_error: null, + run_count: 0, + })}`; + +/** Starts a turn from `message`, writes its completion, and lets the reactor see it. */ +const completeTurn = Effect.fn("test.completeTurn")(function* ( + message: { scheduledTaskId?: ScheduledTaskId } = {}, + options: { queueAnother?: boolean; pendingQuestion?: boolean; sendBeforeHandle?: boolean } = {}, +) { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const eventSink = yield* EventSink.EventSinkV2; + const reactor = yield* ScheduledTaskSnoozeReactor.ScheduledTaskSnoozeReactor; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-scheduled-snooze"), + threadId, + projectId: ProjectId.make("project:scheduled-snooze"), + title: "Scheduled snooze", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-scheduled-snooze"), + threadId, + messageId: MessageId.make("message:scheduled-snooze"), + text: "Schedule a daily check", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + ...message, + }); + if (options.queueAnother === true) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queue-scheduled-snooze"), + threadId, + messageId: MessageId.make("message:scheduled-snooze-queued"), + text: "And another thing", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + } + const { runs } = yield* projections.getThreadRecords(threadId, ["runs"]); + const run = runs.find((candidate) => candidate.ordinal === 1)!; + const now = yield* DateTime.now; + const events: OrchestrationV2DomainEvent[] = []; + if (options.pendingQuestion === true) { + events.push({ + id: EventId.make("event:scheduled-snooze-question"), + type: "runtime-request.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { + id: RuntimeRequestId.make("request:scheduled-snooze"), + nodeId: run.rootNodeId!, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "pending", + responseCapability: { type: "message" }, + createdAt: now, + resolvedAt: null, + }, + }); + } + const completed = { + id: EventId.make("event:scheduled-snooze-completed"), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + } satisfies OrchestrationV2DomainEvent; + events.push(completed); + yield* eventSink.write({ events }); + if (options.sendBeforeHandle === true) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("follow-up-scheduled-snooze"), + threadId, + messageId: MessageId.make("message:scheduled-snooze-follow-up"), + text: "One more thing", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + } + yield* reactor.handle(completed); + return completed; +}); + +const snoozedUntil = Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const thread = yield* projections.getThread(threadId); + return thread.snoozedUntil == null ? null : DateTime.formatIso(thread.snoozedUntil); +}); + +it.effect("snoozes until the soonest future run of an enabled task bound to the thread", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* insertTask(sql, { id: "later", threadId, next: "2030-02-01T00:00:00.000Z" }); + yield* insertTask(sql, { id: "soonest", threadId, next: NEXT_RUN }); + yield* insertTask(sql, { + id: "paused", + threadId, + next: "2029-06-01T00:00:00.000Z", + enabled: 0, + }); + yield* insertTask(sql, { id: "overdue", threadId, next: "1969-01-01T00:00:00.000Z" }); + yield* insertTask(sql, { id: "webhook", threadId, next: null }); + yield* insertTask(sql, { + id: "other", + threadId: "thread:other", + next: "2029-06-01T00:00:00.000Z", + }); + const completed = yield* completeTurn(); + assert.strictEqual(yield* snoozedUntil, NEXT_RUN); + + // A re-emitted completion must not undo a manual wake. + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.unsnooze", + commandId: CommandId.make("wake-scheduled-snooze"), + threadId, + reason: "user", + }); + const reactor = yield* ScheduledTaskSnoozeReactor.ScheduledTaskSnoozeReactor; + yield* reactor.handle(completed); + assert.strictEqual(yield* snoozedUntil, null); + }).pipe(Effect.provide(layerTest(true))), +); + +it.effect.each([ + { name: "the setting is off", setting: false }, + { name: "the run is the task's own", setting: true, fromTask: true }, + { name: "another run is still queued", setting: true, queueAnother: true }, + { name: "the turn ended on a question", setting: true, pendingQuestion: true }, + { name: "a message arrives before the snooze", setting: true, sendBeforeHandle: true }, +])("leaves the thread awake when $name", (scenario) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* insertTask(sql, { id: "soonest", threadId, next: NEXT_RUN }); + yield* completeTurn( + scenario.fromTask === true ? { scheduledTaskId: ScheduledTaskId.make("soonest") } : {}, + scenario, + ); + assert.strictEqual(yield* snoozedUntil, null); + }).pipe(Effect.provide(layerTest(scenario.setting))), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts new file mode 100644 index 0000000000000..cf43273bf1b71 --- /dev/null +++ b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts @@ -0,0 +1,85 @@ +import { CommandId, type OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { nextRunForThread } from "./ScheduledTaskService.ts"; + +export class ScheduledTaskSnoozeReactor extends Context.Service< + ScheduledTaskSnoozeReactor, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/scheduledTasks/ScheduledTaskSnoozeReactor") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const settings = yield* ServerSettings.ServerSettingsService; + const sql = yield* SqlClient.SqlClient; + + // Runs for every domain event; most events return before any work is needed. + const handle: ScheduledTaskSnoozeReactor["Service"]["handle"] = Effect.fnUntraced( + function* (event) { + if (event.type !== "run.updated" || event.payload.status !== "completed") return; + const { snoozeThreadsUntilScheduledTask } = yield* settings.getSettings; + if (!snoozeThreadsUntilScheduledTask) return; + const run = event.payload; + // The task's own run and its automatic follow-ups leave their result visible. + const { messages } = yield* projections.getThreadRecords(event.threadId, ["messages"], { + messageIds: [run.userMessageId], + }); + const message = messages.find((candidate) => candidate.id === run.userMessageId); + if ( + message?.scheduledTaskId !== undefined || + message?.notification !== undefined || + message?.delegatedCompletion !== undefined + ) { + return; + } + const nextRun = yield* nextRunForThread(event.threadId, yield* DateTime.now).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + ); + if (nextRun === null) return; + // Completion is re-emitted (checkpoints, delegated rewrites); one id per run keeps a + // later manual wake from being undone. + yield* engine.autoSnoozeAfterRun({ + commandId: CommandId.make(`server:scheduled-task-snooze:${run.id}`), + threadId: event.threadId, + runId: run.id, + snoozedUntil: nextRun, + }); + }, + (effect, event) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("snoozing a thread until its scheduled task failed", { + threadId: event.threadId, + cause, + }), + ), + ), + ); + + const start: ScheduledTaskSnoozeReactor["Service"]["start"] = () => + forkParked( + Stream.runForEach(engine.streamDomainEvents, handle).pipe( + Effect.catchCause((cause) => + Effect.logWarning("scheduled task snooze event stream failed", { cause }), + ), + ), + ); + + return { start, handle } satisfies ScheduledTaskSnoozeReactor["Service"]; +}); + +export const layer = Layer.effect(ScheduledTaskSnoozeReactor, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 8b1cce579162f..76250b12ffc56 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -8,6 +8,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as ScheduledTaskSnoozeReactor from "./scheduledTasks/ScheduledTaskSnoozeReactor.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -706,6 +707,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* ScheduledTaskSnoozeReactor.ScheduledTaskSnoozeReactor; + yield* service.start(); + }), + ).pipe(Layer.provide(ScheduledTaskSnoozeReactor.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 633e18a567b2f..96deb2b8e66a1 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -515,6 +515,10 @@ export function useSettingsRestore(onRestored?: () => void) { ...(!Equal.equals(settings.snoozePresets, DEFAULT_UNIFIED_SETTINGS.snoozePresets) ? ["Snooze options"] : []), + ...(settings.snoozeThreadsUntilScheduledTask !== + DEFAULT_UNIFIED_SETTINGS.snoozeThreadsUntilScheduledTask + ? ["Snooze until scheduled task runs"] + : []), ...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []), ...(settings.persistComposerContextStrip !== DEFAULT_UNIFIED_SETTINGS.persistComposerContextStrip @@ -683,6 +687,7 @@ export function useSettingsRestore(onRestored?: () => void) { autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, snoozePresets: DEFAULT_UNIFIED_SETTINGS.snoozePresets, + snoozeThreadsUntilScheduledTask: DEFAULT_UNIFIED_SETTINGS.snoozeThreadsUntilScheduledTask, responseStreamingMode: DEFAULT_UNIFIED_SETTINGS.responseStreamingMode, enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate, @@ -1735,6 +1740,11 @@ export function ThreadsSettingsPanel() { const supportsAutoSettlementScope = connectedEnvironments.every( (target) => target.serverConfig?.environment.capabilities.threadAutoSettlementScope === true, ); + const supportsScheduledTaskSnooze = + hasServerTargets && + connectedEnvironments.every( + (target) => target.serverConfig?.environment.capabilities.scheduledTaskSnooze === true, + ); const textGenerationTargets = useTextGenerationTargets({ environmentId, @@ -1843,6 +1853,24 @@ export function ThreadsSettingsPanel() { {!isProjectScope ? ( + {supportsScheduledTaskSnooze ? ( + + updateSettings({ snoozeThreadsUntilScheduledTask: Boolean(checked) }) + } + aria-label="Snooze until scheduled task runs" + /> + } + /> + ) : null} ) : null} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 7d7939e7f21f9..ac6ae7f912ce2 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -453,6 +453,14 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/threads", searchTerms: ["usage quota rate limit reset wake recover continue"], }, + { + id: "snooze-until-scheduled-task", + title: "Snooze until scheduled task runs", + to: "/settings/threads", + searchTerms: ["scheduled task schedule automation recurring wake hide next run"], + environmentOnly: true, + scope: "environment-defaults", + }, { id: "auto-resume-limited-threads", title: "Resume after usage limits", diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 4c02f1c79baee..254eeb7d84f87 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -339,3 +339,9 @@ A snoozed thread keeps working and stays hidden until its wake time, even while its agent wakes itself for background work. It comes back early for an approval, a new question, a failed run, or a message or answer you send. You can snooze an existing question and answer when the thread wakes; the question stays unanswered. + +To hide a thread while it waits for its own scheduled task, turn on **Settings → Threads → +Snooze until scheduled task runs**. When a turn ends and the thread has an enabled scheduled task +coming up, the thread snoozes until that task's next run, then wakes when the task starts. The +task's own turn leaves its result visible. Pausing or rescheduling the task does not move the wake +time; choose **Wake thread** to bring the thread back sooner. diff --git a/packages/client-runtime/src/state/sharedSettings.ts b/packages/client-runtime/src/state/sharedSettings.ts index 77dbddadb6bbb..244353a3ce8e3 100644 --- a/packages/client-runtime/src/state/sharedSettings.ts +++ b/packages/client-runtime/src/state/sharedSettings.ts @@ -11,6 +11,7 @@ const SHARED_SERVER_SETTING_KEYS = [ "autoResumeLimitedThreads", "snoozeLimitedThreads", "snoozePresets", + "snoozeThreadsUntilScheduledTask", "newWorktreesStartFromOrigin", "sourceControlWritingStyle", "textGenerationModelSelection", diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index ad1cfe30b0214..cfd44c6168a3d 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -195,6 +195,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ freshContext: Schema.optionalKey(Schema.Boolean), /** Server saves and runs scheduled task `threadMode`; older servers ignore it. */ scheduledTaskThreadModes: Schema.optionalKey(Schema.Boolean), + /** Server honors `snoozeThreadsUntilScheduledTask`; older servers ignore it. */ + scheduledTaskSnooze: Schema.optionalKey(Schema.Boolean), /** Server can transcribe 16 kHz mono PCM audio on the environment machine. */ voiceTranscription: Schema.optionalKey(Schema.Boolean), cloudVoiceTranscription: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7bbb03595d4bb..35a4eed5350e1 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1452,6 +1452,9 @@ export const ServerSettings = Schema.Struct({ ), idleCompaction: Schema.optionalKey(IdleCompactionMode), snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + snoozeThreadsUntilScheduledTask: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(false)), + ), autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), snoozePresets: SnoozePresetSettings.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNOOZE_PRESETS)), @@ -1901,6 +1904,7 @@ export const ServerSettingsPatch = Schema.Struct({ sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean), snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean), + snoozeThreadsUntilScheduledTask: Schema.optionalKey(Schema.Boolean), snoozePresets: Schema.optionalKey(SnoozePresetSettings), hiddenThreadTags: Schema.optionalKey(Schema.Array(Schema.String)), hideTaggedThreads: Schema.optionalKey(Schema.Boolean), From ee834429e65d67648b9f034d9bfb7e4df915545d Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sat, 14 Nov 2026 16:53:44 -0300 Subject: [PATCH 07/87] ci(fork): build personal releases as T3 Code L with the nightly logo Co-Authored-By: Claude Opus 5.5 --- .github/fork/brand-l.mjs | 54 ++++++++++++++++++++++++++++++++ .github/workflows/fork-build.yml | 4 ++- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 .github/fork/brand-l.mjs diff --git a/.github/fork/brand-l.mjs b/.github/fork/brand-l.mjs new file mode 100644 index 0000000000000..392db37865e68 --- /dev/null +++ b/.github/fork/brand-l.mjs @@ -0,0 +1,54 @@ +// Personal fork branding: "T3 Code L" with the nightly logo, sharing the official app's data +// (~/.t3 and the t3code-v2 Chromium profile). Run from the repo root on a throwaway checkout +// before `scripts/build-desktop-artifact.ts`; it rewrites tracked files and must not be committed. +import * as NodeFS from "node:fs"; + +const NAME = "T3 Code L"; +const APP_ID = "com.lamarcab76.t3code.l"; + +function replaceOnce(path, from, to) { + const text = NodeFS.readFileSync(path, "utf8"); + if (text.split(from).length !== 2) throw new Error(`${path}: expected exactly one "${from}"`); + NodeFS.writeFileSync(path, text.replace(from, to)); +} + +replaceOnce( + "apps/desktop/src/app/DesktopEnvironment.ts", + 'const APP_BASE_NAME = "T3 Code";', + `const APP_BASE_NAME = "${NAME}";`, +); +replaceOnce( + "apps/desktop/src/app/DesktopEnvironment.ts", + "displayName: `${APP_BASE_NAME} (${stageLabel})`,", + "displayName: APP_BASE_NAME,", +); +replaceOnce( + "apps/desktop/src/app/DesktopAppIdentity.ts", + "`${environment.branding.baseName} ${environment.branding.stageLabel}`,", + "environment.displayName,", +); +replaceOnce( + "scripts/build-desktop-artifact.ts", + 'const DESKTOP_APP_ID = "com.t3tools.t3code";', + `const DESKTOP_APP_ID = "${APP_ID}";`, +); +replaceOnce( + "apps/desktop/package.json", + '"productName": "T3 Code (Beta)"', + `"productName": "${NAME}"`, +); + +const icons = [ + ["nightly-macos-1024.png", "black-macos-1024.png"], + ["nightly-universal-1024.png", "black-universal-1024.png"], + ["nightly-windows.ico", "t3-black-windows.ico"], + ["nightly-web-favicon.ico", "t3-black-web-favicon.ico"], + ["nightly-web-favicon-16x16.png", "t3-black-web-favicon-16x16.png"], + ["nightly-web-favicon-32x32.png", "t3-black-web-favicon-32x32.png"], + ["nightly-web-apple-touch-180.png", "t3-black-web-apple-touch-180.png"], + ["nightly-web-icon-192x192.png", "t3-black-web-icon-192x192.png"], + ["nightly-web-icon-512x512.png", "t3-black-web-icon-512x512.png"], +]; +for (const [from, to] of icons) NodeFS.copyFileSync(`assets/nightly/${from}`, `assets/prod/${to}`); + +console.log(`Branded as ${NAME} (${APP_ID}) with the nightly logo.`); diff --git a/.github/workflows/fork-build.yml b/.github/workflows/fork-build.yml index c97815bd6f6b3..615df6610a5bc 100644 --- a/.github/workflows/fork-build.yml +++ b/.github/workflows/fork-build.yml @@ -32,6 +32,7 @@ jobs: run-install: false - run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config libfuse2 imagemagick - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - run: node .github/fork/brand-l.mjs - id: meta run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" - run: node scripts/update-release-package-versions.ts "${{ steps.meta.outputs.version }}" @@ -90,6 +91,7 @@ jobs: node-version-file: package.json run-install: false - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - run: node .github/fork/brand-l.mjs - run: node scripts/update-release-package-versions.ts "${{ needs.linux.outputs.version }}" - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 if: matrix.platform == 'win' @@ -126,4 +128,4 @@ jobs: run: | cd artifacts sha256sum * > SHA256SUMS - gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code fork $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." + gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code L $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." From b24b6382992213e67aced6d65b12c15f220a9129 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 15 Nov 2026 09:55:09 -0300 Subject: [PATCH 08/87] fix(fork): publish increasing versions with updater-compatible tags --- .github/workflows/fork-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/fork-build.yml b/.github/workflows/fork-build.yml index 615df6610a5bc..fb856d4236099 100644 --- a/.github/workflows/fork-build.yml +++ b/.github/workflows/fork-build.yml @@ -34,7 +34,7 @@ jobs: - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... - run: node .github/fork/brand-l.mjs - id: meta - run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" + run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.$(date -u +%Y%m%d).${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" - run: node scripts/update-release-package-versions.ts "${{ steps.meta.outputs.version }}" - run: node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64 --build-version "${{ steps.meta.outputs.version }}" --output-dir release - run: | @@ -128,4 +128,4 @@ jobs: run: | cd artifacts sha256sum * > SHA256SUMS - gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code L $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." + gh release create "v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code L $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." From 75aa7e85a85fb933aa35b9e8a5111e5e80e8603c Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 15 Nov 2026 10:38:50 -0300 Subject: [PATCH 09/87] fix(fork): include update feed in local installer builds [skip ci] --- scripts/build-desktop-artifact.test.ts | 24 ++++++++++++++++++++++++ scripts/build-desktop-artifact.ts | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index c9180ec3d3ae6..6d3fa22c2c92a 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -537,6 +537,30 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { assert.isNull(preview.publish); assert.isNull(previewChannel.publish); + + for (const [platform, target] of [ + ["mac", "dmg"], + ["win", "nsis"], + ["linux", "AppImage"], + ] as const) { + const forkRelease = yield* createBuildConfig( + platform, + target, + "0.1.9-fork.20261115.2", + false, + false, + undefined, + undefined, + ).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))); + assert.deepStrictEqual(forkRelease.publish, [ + { + provider: "github", + owner: "LaMarCab76", + repo: "t3code", + releaseType: "release", + }, + ]); + } assert.deepStrictEqual(release.publish, [ { provider: "github", diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 9d34e2412b327..05df5454b6eac 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -2706,7 +2706,7 @@ export const resolveGitHubPublishConfig = Effect.fn("resolveGitHubPublishConfig" const rawRepo = ( Option.getOrUndefined(env.updateRepository)?.trim() || Option.getOrUndefined(env.githubRepository)?.trim() || - "" + "LaMarCab76/t3code" ).trim(); if (!rawRepo) return undefined; From c016bd75dee3a20e703776c9aed75dd550d350f0 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 15 Nov 2026 22:17:29 -0300 Subject: [PATCH 10/87] feat(web): command progress, thread details in the sidebar, and wallpapers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Running commands gave no sense of how far along they were, thread details covered part of the chat, and the app had no way to show a picture behind it. - Command progress: the output hub reads the count a running command last printed (`24/31`, `[3/10]`, `42%`) from the tail it already keeps, and a new `subscribeCommandProgress` stream sends just those counts for the open thread, so no output crosses the wire. Command rows, the live work row, and the Scroll to end button show it. - Thread details in the sidebar: the existing details card renders through a portal under the open thread's sidebar row, on by default. It moves back over the chat while the sidebar is hidden, and Settings → Appearance turns it off. - Wallpaper: Settings → Appearance can show an F1 race picture behind the sidebar and chat, with blur and dimming sliders. The blur is a filter on one fixed layer, not a backdrop-filter, so scrolling never re-blurs it. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../orchestration-v2/CommandOutputHub.test.ts | 28 ++++ .../src/orchestration-v2/CommandOutputHub.ts | 90 +++++++++- .../commandOutputProgress.test.ts | 45 +++++ .../orchestration-v2/commandOutputProgress.ts | 56 +++++++ apps/server/src/ws.ts | 6 + apps/web/src/appInit.tsx | 8 + apps/web/src/appearanceWallpaper.ts | 24 +++ apps/web/src/assets/wallpapers/f1-race.svg | 88 ++++++++++ apps/web/src/components/ChatView.tsx | 34 +++- apps/web/src/components/Sidebar.tsx | 18 +- apps/web/src/components/chat/ChatCanvas.tsx | 14 +- .../components/chat/CommandProgressMeter.tsx | 24 +++ .../src/components/chat/ThreadDetailsCard.tsx | 21 ++- .../chat/ThreadDetailsItemsMenu.tsx | 10 ++ .../components/chat/TimelineWorkEntryRow.tsx | 12 ++ .../components/chat/TimelineWorkGroupRows.tsx | 26 ++- .../chat/threadDetailsSidebarSlot.ts | 42 +++++ .../src/components/chat/useCommandProgress.ts | 40 +++++ .../settings/AppearanceSettingsPanel.tsx | 6 +- .../components/settings/SettingsPanels.tsx | 14 ++ .../settings/ThreadDetailsItemsRow.tsx | 33 ++++ .../settings/WallpaperSettingsRows.tsx | 158 ++++++++++++++++++ .../src/components/settings/settingsSearch.ts | 26 +++ .../sidebar/ThreadDetailsSidebarSlot.tsx | 39 +++++ apps/web/src/index.css | 31 ++++ docs/user/activity-log.md | 5 + docs/user/appearance.md | 7 + docs/user/thread-sidebar.md | 5 + packages/client-runtime/src/rpc/client.ts | 1 + .../client-runtime/src/state/orchestration.ts | 6 + packages/contracts/src/orchestrationV2.ts | 25 +++ packages/contracts/src/rpc.ts | 11 ++ packages/contracts/src/settings.ts | 27 +++ 35 files changed, 960 insertions(+), 22 deletions(-) create mode 100644 apps/server/src/orchestration-v2/commandOutputProgress.test.ts create mode 100644 apps/server/src/orchestration-v2/commandOutputProgress.ts create mode 100644 apps/web/src/appearanceWallpaper.ts create mode 100644 apps/web/src/assets/wallpapers/f1-race.svg create mode 100644 apps/web/src/components/chat/CommandProgressMeter.tsx create mode 100644 apps/web/src/components/chat/threadDetailsSidebarSlot.ts create mode 100644 apps/web/src/components/chat/useCommandProgress.ts create mode 100644 apps/web/src/components/settings/WallpaperSettingsRows.tsx create mode 100644 apps/web/src/components/sidebar/ThreadDetailsSidebarSlot.tsx diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 9c2d16c25c807..ca15e58b89cad 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -62,6 +62,7 @@ export const RPC_REQUIRED_SCOPES = { [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: AuthOrchestrationReadScope, [WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope, [WS_METHODS.serverProbe]: AuthOrchestrationReadScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 5e7e9dd709fca..cf9a94580553a 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -35,6 +35,7 @@ const RPC_AGGREGATES = { [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: "orchestrationV2", + [ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: "orchestrationV2", [WS_METHODS.projectsMutate]: "orchestration", [WS_METHODS.serverProbe]: "server", diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts index 442726379df5c..f77283e179a3f 100644 --- a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts +++ b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts @@ -3,6 +3,7 @@ import { type ModelSelection, type OrchestrationV2AppThread, type OrchestrationV2CommandOutputFrame, + type OrchestrationV2CommandProgressFrame, type OrchestrationV2TurnItem, ProviderDriverKind, ProviderInstanceId, @@ -264,6 +265,33 @@ layer("CommandOutputHub", (it) => { }), ); + it.effect("a thread's progress follows the counts its running commands print", () => + Effect.gen(function* () { + const hub = yield* CommandOutputHub.CommandOutputHub; + const threadId = yield* seedThread; + const frames = yield* Queue.unbounded(); + yield* hub.subscribeProgress(threadId).pipe( + Stream.runForEach((frame) => Queue.offer(frames, frame)), + Effect.forkScoped, + ); + assert.deepStrictEqual(yield* Queue.take(frames), { items: [] }); + + yield* TestClock.adjust("1 second"); + yield* hub.append({ + threadId, + itemId: ITEM_ID, + chunk: " ✓ guard.spec.ts (4)\n❯ refresh.spec.ts 24/31", + }); + assert.deepStrictEqual(yield* Queue.take(frames), { + items: [{ itemId: ITEM_ID, completed: 24, total: 31 }], + }); + + yield* TestClock.adjust("1 second"); + yield* hub.finish({ threadId, itemId: ITEM_ID }); + assert.deepStrictEqual(yield* Queue.take(frames), { items: [] }); + }), + ); + it.effect("a finished command sends only its bounded final output", () => Effect.gen(function* () { const threadId = yield* seedThread; diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.ts b/apps/server/src/orchestration-v2/CommandOutputHub.ts index b6b5b634c179c..cf2dfaf22d16e 100644 --- a/apps/server/src/orchestration-v2/CommandOutputHub.ts +++ b/apps/server/src/orchestration-v2/CommandOutputHub.ts @@ -2,8 +2,12 @@ import { isOrchestrationV2WorkActive, OrchestrationV2CommandOutputError, type OrchestrationV2CommandOutputFrame, + type OrchestrationV2CommandProgress, + type OrchestrationV2CommandProgressFrame, type OrchestrationV2SubscribeCommandOutputInput, type OrchestrationV2TurnItem, + type ThreadId, + TurnItemId, } from "@t3tools/contracts"; import { appendTerminalOutput, @@ -25,9 +29,12 @@ import * as Stream from "effect/Stream"; import * as EventSink from "./EventSink.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { commandOutputProgress } from "./commandOutputProgress.ts"; /** Output bypasses orchestration events; expanded rows receive tails, coalesced appends, then persisted output. */ +/** Fastest a thread's progress subscriber re-reads its commands' tails. */ +const COMMAND_PROGRESS_FRAME_INTERVAL_MS = 250; /** Fastest a subscriber receives frames while output flows. */ const COMMAND_OUTPUT_FRAME_INTERVAL_MS = 100; /** After a subscriber falls behind and is sent the whole tail, it waits this long. */ @@ -57,6 +64,10 @@ export interface CommandOutputHubShape { readonly subscribe: ( input: CommandOutputTarget, ) => Stream.Stream; + /** Counts the thread's running commands print, read from the same tails, so no output crosses the wire. */ + readonly subscribeProgress: ( + threadId: ThreadId, + ) => Stream.Stream; } export class CommandOutputHub extends Context.Service()( @@ -65,8 +76,12 @@ export class CommandOutputHub extends Context.Service(); const finished = new Map(); const subscribers = new Map>(); + const progressSubscribers = new Map>>(); + + const wakeProgress = (threadId: ThreadId) => + Effect.forEach( + progressSubscribers.get(threadId) ?? [], + (wake) => Queue.offer(wake, undefined), + { + discard: true, + }, + ); + + const threadProgress = (threadId: ThreadId): Array => { + const prefix = threadKeyPrefix(threadId); + const items: Array = []; + for (const [key, tail] of tails) { + if (!key.startsWith(prefix)) continue; + const progress = commandOutputProgress(tail.text); + if (progress) items.push({ itemId: TurnItemId.make(key.slice(prefix.length)), ...progress }); + } + return items; + }; const wakeAll = (key: string, chunk: string) => Effect.forEach( @@ -139,18 +175,62 @@ export const make = Effect.gen(function* () { subscriber.pendingAppend = ""; } }); - return wakeAll(key, chunk); + return wakeAll(key, chunk).pipe(Effect.andThen(wakeProgress(target.threadId))); }); const finish: CommandOutputHubShape["finish"] = (target) => - Effect.sync(() => { + Effect.suspend(() => { const key = commandKey(target); const tail = tails.get(key); - if (tail === undefined) return; + if (tail === undefined) return Effect.void; tails.delete(key); setBounded(finished, key, tail, MAX_FINISHED_COMMANDS); + return wakeProgress(target.threadId); }); + const subscribeProgress: CommandOutputHubShape["subscribeProgress"] = (threadId) => + Stream.unwrap( + Effect.gen(function* () { + const wake = yield* Queue.sliding(1); + const threadSubscribers = progressSubscribers.get(threadId) ?? new Set>(); + threadSubscribers.add(wake); + progressSubscribers.set(threadId, threadSubscribers); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + threadSubscribers.delete(wake); + if ( + threadSubscribers.size === 0 && + progressSubscribers.get(threadId) === threadSubscribers + ) { + progressSubscribers.delete(threadId); + } + }), + ); + yield* Queue.offer(wake, undefined); + let sent: string | undefined; + let lastReadAt: number | undefined; + const nextFrame = Effect.gen(function* () { + while (true) { + yield* Queue.take(wake); + const now = yield* Clock.currentTimeMillis; + if (lastReadAt !== undefined && now - lastReadAt < COMMAND_PROGRESS_FRAME_INTERVAL_MS) { + yield* Effect.sleep(COMMAND_PROGRESS_FRAME_INTERVAL_MS - (now - lastReadAt)); + } + lastReadAt = yield* Clock.currentTimeMillis; + const items = threadProgress(threadId); + const signature = items + .map((item) => `${item.itemId}:${item.completed}/${item.total}`) + .join("\n"); + if (signature !== sent) { + sent = signature; + return { items } satisfies OrchestrationV2CommandProgressFrame; + } + } + }); + return Stream.fromEffectRepeat(nextFrame); + }), + ); + const subscribe: CommandOutputHubShape["subscribe"] = (target) => Stream.unwrap( Effect.gen(function* () { @@ -297,7 +377,7 @@ export const make = Effect.gen(function* () { ), ); - return CommandOutputHub.of({ append, finish, subscribe }); + return CommandOutputHub.of({ append, finish, subscribe, subscribeProgress }); }); export const layer: Layer.Layer< diff --git a/apps/server/src/orchestration-v2/commandOutputProgress.test.ts b/apps/server/src/orchestration-v2/commandOutputProgress.test.ts new file mode 100644 index 0000000000000..f8b4feac1eba6 --- /dev/null +++ b/apps/server/src/orchestration-v2/commandOutputProgress.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { commandOutputProgress } from "./commandOutputProgress.ts"; + +describe("commandOutputProgress", () => { + it.each([ + [ + "a test runner count", + " ✓ guard.spec.ts (4)\n❯ refresh.spec.ts 24/31", + { completed: 24, total: 31 }, + ], + ["a bracketed step", "[3/10] RUN pnpm install\n", { completed: 3, total: 10 }], + ["a spaced count", "Building (120 / 300) crates", { completed: 120, total: 300 }], + ["a percentage", "webpack 42% building modules", { completed: 42, total: 100 }], + ["a pytest percentage", "tests/test_auth.py .... [ 87%]", { completed: 87, total: 100 }], + [ + "the last redraw of a carriage-return progress bar", + "Downloading 10%\rDownloading 55%\rDownloading 73%\r\n", + { completed: 73, total: 100 }, + ], + [ + "colored output", + "\u001b[32m✓\u001b[0m \u001b[1m17/40\u001b[0m tests", + { completed: 17, total: 40 }, + ], + [ + "the newest of several lines", + "1/10 setup\n2/10 build\n7/10 test\n", + { completed: 7, total: 10 }, + ], + ])("reads %s", (_name, output, expected) => { + expect(commandOutputProgress(output)).toEqual(expected); + }); + + it.each([ + ["no output", undefined], + ["a path", "wrote dist/assets/12/34.js"], + ["a date", "Released 2024/11/05"], + ["a version range", "react 18.3/19.0 compatible"], + ["a count past its total", "retry 5/3"], + ["a count that scrolled out of the tail", "3/10 build\n" + "log line\n".repeat(10)], + ])("ignores %s", (_name, output) => { + expect(commandOutputProgress(output)).toBeUndefined(); + }); +}); diff --git a/apps/server/src/orchestration-v2/commandOutputProgress.ts b/apps/server/src/orchestration-v2/commandOutputProgress.ts new file mode 100644 index 0000000000000..efad1e9f28858 --- /dev/null +++ b/apps/server/src/orchestration-v2/commandOutputProgress.ts @@ -0,0 +1,56 @@ +import type { OrchestrationV2CommandProgress } from "@t3tools/contracts"; + +type CommandProgressCount = Omit; + +const TAIL_CHARS = 4096; +const TAIL_LINES = 6; +const ANSI_ESCAPE = /\u001b\[[0-9;?]*[ -/]*[@-~]/g; +// A slash count that is not part of a path, a date, or a version: `24/31`, `[3/10]`, `(120 / 300)`. +const FRACTION = /(?= 0; index -= 1) { + const completed = Number(fractions[index]![1]); + const total = Number(fractions[index]![2]); + if (total >= 2 && completed <= total) return { completed, total }; + } + const percents = [...line.matchAll(PERCENT)]; + for (let index = percents.length - 1; index >= 0; index -= 1) { + const value = Number(percents[index]![1]); + if (value <= 100) return { completed: Math.floor(value), total: 100 }; + } + return undefined; +} + +/** + * Reads the count a running command last printed, such as a test runner's `24/31` or a + * build's `42%`. Progress bars redraw with carriage returns, so only each line's last + * redraw counts. + */ +export function commandOutputProgress( + output: string | undefined, +): CommandProgressCount | undefined { + if (!output) return undefined; + const lines = output + .slice(-TAIL_CHARS) + .split("\n") + .map((line) => + ( + line + .split("\r") + .filter((redraw) => redraw.trim().length > 0) + .at(-1) ?? "" + ) + .replace(ANSI_ESCAPE, "") + .trim(), + ) + .filter((line) => line.length > 0) + .slice(-TAIL_LINES); + for (let index = lines.length - 1; index >= 0; index -= 1) { + const progress = lineProgress(lines[index]!); + if (progress) return progress; + } + return undefined; +} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 63c2b9c999453..b41edb8bf16c7 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2295,6 +2295,12 @@ export const layerWsRpc = ( Effect.as(commandOutputHub.subscribe(input)), ), ), + [ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress]: (input) => + Stream.unwrap( + Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( + Effect.as(commandOutputHub.subscribeProgress(input.threadId)), + ), + ), [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => providerSessionManager.subscribePromptSuggestion(input.threadId), [WS_METHODS.scheduledTasksSubscribe]: (_input) => diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index faa71137db049..75876a805521a 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -9,6 +9,7 @@ import { createBrowserHistory, createHashHistory } from "@tanstack/react-router" import * as Schema from "effect/Schema"; import { applyAppearanceContrast } from "./appearanceContrast"; +import { applyWallpaper } from "./appearanceWallpaper"; import { applyAppearanceFontVariables, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "./appearanceFonts"; import { startElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter"; @@ -98,6 +99,13 @@ function startClientAppearance(): void { root.style.removeProperty("--glass-blur"); } } + if ( + previous?.wallpaper !== settings.wallpaper || + previous.wallpaperBlur !== settings.wallpaperBlur || + previous.wallpaperDim !== settings.wallpaperDim + ) { + applyWallpaper(root, settings); + } if ( previous?.fontFamilySans !== settings.fontFamilySans || previous.fontFamilyCode !== settings.fontFamilyCode || diff --git a/apps/web/src/appearanceWallpaper.ts b/apps/web/src/appearanceWallpaper.ts new file mode 100644 index 0000000000000..bb2170ddeab43 --- /dev/null +++ b/apps/web/src/appearanceWallpaper.ts @@ -0,0 +1,24 @@ +import type { ClientSettings } from "@t3tools/contracts/settings"; + +import f1RaceWallpaperUrl from "./assets/wallpapers/f1-race.svg"; + +type WallpaperSettings = Pick; + +const WALLPAPER_URLS: Record, string> = { + "f1-race": f1RaceWallpaperUrl, +}; + +/** index.css paints the wallpaper from these variables while `data-wallpaper` is set. */ +export function applyWallpaper(root: HTMLElement, settings: WallpaperSettings): void { + if (settings.wallpaper === "none") { + delete root.dataset.wallpaper; + root.style.removeProperty("--wallpaper-image"); + root.style.removeProperty("--wallpaper-blur"); + root.style.removeProperty("--wallpaper-dim"); + return; + } + root.dataset.wallpaper = settings.wallpaper; + root.style.setProperty("--wallpaper-image", `url("${WALLPAPER_URLS[settings.wallpaper]}")`); + root.style.setProperty("--wallpaper-blur", `${settings.wallpaperBlur}px`); + root.style.setProperty("--wallpaper-dim", `${settings.wallpaperDim}%`); +} diff --git a/apps/web/src/assets/wallpapers/f1-race.svg b/apps/web/src/assets/wallpapers/f1-race.svg new file mode 100644 index 0000000000000..e0c7adb3309e8 --- /dev/null +++ b/apps/web/src/assets/wallpapers/f1-race.svg @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 67638fc4e63ca..b9b2aed21d731 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -314,6 +314,12 @@ import { } from "./chat/PanelLayoutControls"; import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel"; +import { useThreadDetailsSidebarSlot } from "./chat/threadDetailsSidebarSlot"; +import { + formatCommandProgress, + truncateCommandLabel, + useCommandProgress, +} from "./chat/useCommandProgress"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { resolveEffectiveEnvMode, @@ -1976,9 +1982,10 @@ export default function ChatView(props: ChatViewProps) { const threadPanelInlineOpen = useRightPanelStore((state) => selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"), ); + const threadDetailsSidebarSlot = useThreadDetailsSidebarSlot(activeThreadRef); // Selects only the mode, so canvas resizes rerender the chat view only when the // card switches presentation. - const threadPanelPresentation = useStore( + const threadPanelCanvasPresentation = useStore( chatCanvasStore, (state) => resolveChatCanvasModel({ @@ -1986,9 +1993,12 @@ export default function ChatView(props: ChatViewProps) { detailsCardMeasurement: state.detailsCardMeasurement, threadRef: activeThreadRef, preview: canvasPreview, - detailsCardInlineOpen: threadPanelInlineOpen, + detailsCardInlineOpen: threadPanelInlineOpen && threadDetailsSidebarSlot === null, }).detailsCardMode, ); + // Details in the sidebar open and close with the inline flag, whatever room the canvas has. + const threadPanelPresentation = + threadDetailsSidebarSlot === null ? threadPanelCanvasPresentation : "inline"; const threadPanelOpen = useRightPanelStore((state) => selectThreadPanelOpen( state.threadPanelVisibilityByThreadKey, @@ -3137,8 +3147,24 @@ export default function ChatView(props: ChatViewProps) { message.inputIntent === "queued_turn" && !serverProjection?.messages.some((committed) => committed.id === message.id), ); + const runningCommands = (serverProjection?.turnItems ?? []).filter( + (item) => item.type === "command_execution" && item.status === "running", + ); + const runningCommandProgress = useCommandProgress( + activeThreadRef, + isServerThread && runningCommands.length > 0, + ).find((progress) => runningCommands.some((item) => item.id === progress.itemId)); + const runningCommand = runningCommands.find((item) => item.id === runningCommandProgress?.itemId); + const commandProgressSummary = + runningCommand?.type === "command_execution" && runningCommandProgress + ? `${truncateCommandLabel(runningCommand.input)} ${formatCommandProgress(runningCommandProgress)}` + : null; const scrollToEndSummary = - [childInputNow?.waitingLabel ?? null, queuedRunCount === 0 ? null : `${queuedRunCount} queued`] + [ + commandProgressSummary, + childInputNow?.waitingLabel ?? null, + queuedRunCount === 0 ? null : `${queuedRunCount} queued`, + ] .filter((part) => part !== null) .join(" · ") || null; // The end of the timeline holds the thread's present and next turns: what it is doing now, @@ -3326,6 +3352,7 @@ export default function ChatView(props: ChatViewProps) {
    {embedded ? null : ( s.confirmThreadDelete); const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive); const timestampFormat = useClientSettings((s) => s.timestampFormat); + const sidebarVisible = useSidebarVisibility(); + const showDetailsInSidebar = useClientSettings((s) => s.threadDetailsInSidebar) && sidebarVisible; const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); const { settleThread, @@ -3368,7 +3372,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : isCard ? "card" : "slim"; - return ( + const row = ( ); + return showDetailsInSidebar && routeThreadKey === threadKey ? ( + + {row} + + + ) : ( + row + ); }; const from = isContextDrag ? null : (dragState?.activeSection ?? null); const items: ReactNode[] = [ diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index 7848009308750..aac168f12b5ef 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -6,6 +6,7 @@ import { resolveChatCanvasModel, type ChatCanvasStore } from "./canvasStore"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; import { observeResize } from "../../lib/observeResize"; import type { ScopedThreadRef } from "@t3tools/contracts"; +import { useThreadDetailsSidebarSlot } from "./threadDetailsSidebarSlot"; function panelWidthTransitions(element: HTMLElement) { const panels = element @@ -134,11 +135,14 @@ export function ChatCanvas({ stopObserving(); }; }, [store, composerOverlayElement, timelineElement, detailsCardTopInset]); - const detailsCardInlineOpen = useRightPanelStore((state) => - threadRef === null - ? false - : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), - ); + const detailsSidebarSlot = useThreadDetailsSidebarSlot(threadRef); + // Details shown in the sidebar take no room in the canvas. + const detailsCardInlineOpen = + useRightPanelStore((state) => + threadRef === null + ? false + : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), + ) && detailsSidebarSlot === null; const model = resolveChatCanvasModel({ measurements, detailsCardMeasurement, diff --git a/apps/web/src/components/chat/CommandProgressMeter.tsx b/apps/web/src/components/chat/CommandProgressMeter.tsx new file mode 100644 index 0000000000000..e0b8559edff5c --- /dev/null +++ b/apps/web/src/components/chat/CommandProgressMeter.tsx @@ -0,0 +1,24 @@ +import type { OrchestrationV2CommandProgress } from "@t3tools/contracts"; + +import { formatCommandProgress } from "./useCommandProgress"; + +export function CommandProgressMeter({ progress }: { progress: OrchestrationV2CommandProgress }) { + return ( + + + + + {formatCommandProgress(progress)} + + ); +} diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 4e8a47a39791a..d8f8f60a94633 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -17,6 +17,8 @@ import { resolveThreadDetailsCardDensity, } from "./threadDetailsCardLayout"; import { observeResize } from "../../lib/observeResize"; +import { createPortal } from "react-dom"; +import { useThreadDetailsSidebarSlot } from "./threadDetailsSidebarSlot"; import { requestWorkspaceFocus } from "../../lib/workspaceFocus"; export function ThreadDetailsCard({ @@ -47,6 +49,7 @@ export function ThreadDetailsCard({ const popoverOpen = useRightPanelStore((state) => selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "popover"), ); + const sidebarSlot = useThreadDetailsSidebarSlot(threadRef); const measurementKey = `${threadRef.environmentId}:${threadRef.threadId}:${preferredPlacement?.width ?? "popup"}:${contentKey}`; const [measurements, setMeasurements] = useState({ key: measurementKey, @@ -131,7 +134,7 @@ export function ThreadDetailsCard({ return ( { const target = details.reason === "focus-out" @@ -146,7 +149,21 @@ export function ThreadDetailsCard({ useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", open); }} > - {placement && inlineOpen ? ( + {sidebarSlot && inlineOpen + ? createPortal( +
    + {children("full")} +
    , + sidebarSlot, + ) + : null} + {placement && inlineOpen && sidebarSlot === null ? (
    {merged.errors.map((error) => (

    - {error} + {messages(error)}

    ))} {merged.pending.map((ref) => ( diff --git a/apps/web/src/components/chat/composerContextUndo.test.ts b/apps/web/src/components/chat/composerContextUndo.test.ts index c493aa2dfc8fd..f6e5e602ad4ac 100644 --- a/apps/web/src/components/chat/composerContextUndo.test.ts +++ b/apps/web/src/components/chat/composerContextUndo.test.ts @@ -152,5 +152,20 @@ describe("reconcileAttachmentContextReferences", () => { queuedAttachments: [queuedImage], }); expect(backspaced.queuedAttachmentIdsToRemove).toEqual([]); + + reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["image_local"]), + queuedAttachments: [queuedImage], + fromHistory: true, + }); + expect( + reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [queuedImage], + fromHistory: true, + }).queuedAttachmentIdsToRemove, + ).toEqual([queuedImage.attachment.id]); }); }); diff --git a/apps/web/src/components/chat/composerContextUndo.ts b/apps/web/src/components/chat/composerContextUndo.ts index 4c96ec12b70fc..60e6a81ec8adb 100644 --- a/apps/web/src/components/chat/composerContextUndo.ts +++ b/apps/web/src/components/chat/composerContextUndo.ts @@ -112,8 +112,9 @@ export function reconcileAttachmentContextReferences(input: { if (isQueuedFileAttachment(entry.attachment)) return [entry.attachment.id]; // Like draft images, a queued image outlives its deleted chip, unless undo or redo // takes away a chip whose return had brought the image back. - const wasRestored = restoredImageIds.delete(entry.attachment.id); - return wasRestored && input.fromHistory ? [entry.attachment.id] : []; + return input.fromHistory && restoredImageIds.delete(entry.attachment.id) + ? [entry.attachment.id] + : []; }); const queuedAttachmentsToRestore = (input.removedQueuedAttachments ?? []).flatMap((entry) => { if (!isReferenced(entry)) return []; diff --git a/apps/web/src/state/threadInsights.ts b/apps/web/src/state/threadInsights.ts index f87d2b7afceca..9477b87ddfecf 100644 --- a/apps/web/src/state/threadInsights.ts +++ b/apps/web/src/state/threadInsights.ts @@ -12,6 +12,8 @@ import { environmentPresentations } from "./presentation"; import { environmentThreadShells } from "./threads"; import { createThreadInsightsRefreshAtom } from "./threadInsightsRefresh"; +const environmentFailure = msg("An environment could not report tasks and usage."); + export const threadInsightsViewAtom = Atom.family((key: string) => { const target = parseScopedThreadKey(key); if (target === null) throw new Error("Invalid thread insights target"); @@ -22,7 +24,7 @@ export const threadInsightsViewAtom = Atom.family((key: string) => { const visited = new Set(); const rowKeys = new Set(); const queries: ReturnType[] = []; - const errors = new Set(); + let environmentFailed = false; let loading = false; for (let index = 0; index < queue.length && visited.size < 200 && rowKeys.size < 200; index++) { const ref = queue[index]!; @@ -38,9 +40,7 @@ export const threadInsightsViewAtom = Atom.family((key: string) => { rowKeys.add(nextKey); const result = get(query); loading ||= AsyncResult.isInitial(result) || result.waiting; - if (AsyncResult.isFailure(result)) { - errors.add(m(msg("An environment could not report tasks and usage."))); - } + environmentFailed ||= AsyncResult.isFailure(result); const data = Option.getOrNull(AsyncResult.value(result)); if (data === null) continue; answers.set(nextKey, { target: ref, data }); @@ -53,7 +53,7 @@ export const threadInsightsViewAtom = Atom.family((key: string) => { return { ...mergeThreadInsights(target, answers, m, omitted), queries, - errors: [...errors], + errors: environmentFailed ? [environmentFailure] : [], loading, }; }); diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md index 2b8685ecf2281..2f02cd61b9466 100644 --- a/docs/internals/product-analytics.md +++ b/docs/internals/product-analytics.md @@ -148,8 +148,9 @@ Keep analytics payloads to product metadata and normalized measurements. The one exception is `agent.feedback`, sent only while the user has turned on agent feedback: its `expected`, `actual`, and `workaround` fields are agent-written text, which [FeedbackService](../../apps/server/src/feedback/FeedbackService.ts) scrubs of -file paths, values the server knows are private to the caller, and secret-shaped -strings, and caps at 300 characters each. `userRequested: true` means the user saw the +absolute file paths with at least two segments, known private values of at least three +characters, and secret-shaped strings. It caps each field at 300 characters. Relative +paths and single-segment absolute paths can remain unless they match a known private value. `userRequested: true` means the user saw the report in its preview card and pressed Send; only such a report carries `trace`, which the server builds from the thread when the card is shown: an outline of at least the last 5 turns with no text, plus the scrubbed message text of the turns the diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 4c6b3f20eaad5..60efa4aa85548 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -48,10 +48,11 @@ and you can decline the old one. Tool inputs and outputs, files, and attachments show you at most 3 report cards and send 3 reports on its own per turn, and `t3 feedback` can send at most 10 an hour. -Before anything is saved, T3 Code removes file paths (when text mentions one, the rest of that line -goes with it), your user name, machine name, project title, branch, and git remote, and anything -that looks like a key, token, email address, or URL with a password. It cannot recognise your code -or a name written in a sentence, so only include the conversation when it holds nothing you would +Before saving a report, T3 Code makes a best-effort attempt to remove absolute paths with at least +two segments, known private values such as your user name, machine name, project title, branch, and +git remote, and text that looks like a key, token, email address, or URL with a password. Relative +paths, single-segment absolute paths, values shorter than three characters, source code, and names +in sentences can remain, so only include the conversation when it holds nothing you would not send. Reports from agents also name the provider, and the model when it is from the provider's public model list. No thread IDs or project IDs are sent. diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 2a6c0dc43d50c..0561e72704077 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -731,6 +731,7 @@ class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth") HttpApiEndpoint.post("revoke", "/oauth/mcp/revoke", { payload: AuthMcpRevokeRequest, success: HttpApiSchema.Empty(200), + error: AuthMcpTokenError, }), ) {} From 620120decbdc609cd74097776dc3420a0a5a7efc Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:06:15 -0300 Subject: [PATCH 61/87] fix(web): replay unsaved browser history changes after storage recovers --- .../src/browserHistoryStore.browser.test.ts | 60 +++++++++++++++++++ apps/web/src/browserHistoryStore.ts | 60 ++++++++++++------- 2 files changed, 98 insertions(+), 22 deletions(-) diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index 1f29cbfd17ddf..b06eb3541669f 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -341,3 +341,63 @@ it("keeps visits saved while IndexedDB could not open", async () => { await resetHistoryFixture(); } }); + +it.each(["localStorage", "IndexedDB"] as const)( + "keeps unsaved changes when %s recovers", + async (recoveredStorage) => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + const store = useBrowserHistoryStore.getState(); + store.recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey.a).toEqual([oldEntry]), + ); + + using transaction = vi.spyOn(IDBDatabase.prototype, "transaction").mockImplementation(() => { + throw new DOMException("Storage unavailable", "SecurityError"); + }); + { + using _write = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw new DOMException("Storage unavailable", "QuotaExceededError"); + }); + store.recordVisit("a", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey.a).toEqual([otherEntry, oldEntry]), + ); + store.removeUrl("a", oldEntry.url); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey.a).toEqual([otherEntry]), + ); + } + + const expected = { + a: [{ url: page.url, lastVisitedAt: page.lastVisitedAt }, otherEntry], + }; + if (recoveredStorage === "IndexedDB") { + transaction.mockRestore(); + } else { + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [oldEntry] } }, version: 1 }), + ); + } + store.recordVisit("a", page.url, page.lastVisitedAt); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual(expected), + ); + if (recoveredStorage === "IndexedDB") { + expect(await readHistoryFixture(db)).toMatchObject({ byProjectKey: expected }); + } else { + const keys = fallbackKeys(); + expect(keys).toHaveLength(1); + expect(JSON.parse(localStorage.getItem(keys[0]!)!)).toMatchObject({ + state: { byProjectKey: expected }, + }); + } + } finally { + await resetHistoryFixture(); + } + }, +); diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index 3f120d58648e8..50fea702d9a5d 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -255,6 +255,9 @@ const EMPTY_PERSISTED_HISTORY: PersistedBrowserHistory = { }; let historyDatabase: Promise | undefined; let historyChannel: BroadcastChannel | undefined; +let historySync = Promise.resolve(); +let unsavedHistoryUpdates: UpdateHistory[] = []; +let unsavedHistoryBase: PersistedBrowserHistory | undefined; interface HistorySnapshot { readonly key: string; @@ -335,19 +338,18 @@ function mergeLegacyHistory( function transactLegacyHistory(update: UpdateHistory, current: PersistedBrowserHistory) { const snapshots = readHistorySnapshots(); const previous = mergeHistorySnapshots(undefined, snapshots) ?? current; - const next = update(previous); - if (next === previous) return previous; - const history = boundThreadMappings(previous, next); + const history = update(previous); + if (history === previous) return { history, unsavedBase: undefined }; try { window.localStorage.setItem( `${BROWSER_HISTORY_FALLBACK_PREFIX}${randomUUID()}`, JSON.stringify({ state: history, version: 1 }), ); retireHistorySnapshots(snapshots); + return { history, unsavedBase: undefined }; } catch { - // History stays in memory when the browser denies both storage APIs. + return { history, unsavedBase: previous }; } - return history; } function invalidateHistoryDatabase(opening: Promise): void { @@ -399,8 +401,7 @@ async function transactIndexedHistory(update?: UpdateHistory, retry = true) { const saved = request.result as PersistedBrowserHistory | undefined; if (update) snapshots = readHistorySnapshots(); const previous = mergeHistorySnapshots(saved, snapshots) ?? EMPTY_PERSISTED_HISTORY; - const next = update?.(previous) ?? previous; - history = next === previous ? previous : boundThreadMappings(previous, next); + history = update?.(previous) ?? previous; changed = history !== saved; if (update && changed) store.put(history, BROWSER_HISTORY_STORAGE_KEY); }; @@ -422,17 +423,31 @@ export const useBrowserHistoryStore = create()((set, g publish(update(get())); return; } - void transactIndexedHistory(update).then( - ({ history, changed }) => { - publish(history); + historySync = historySync.then(async () => { + unsavedHistoryUpdates.push(update); + const replay = (base: PersistedBrowserHistory) => + unsavedHistoryUpdates.reduce((state, apply) => { + const next = apply(state); + return next === state ? state : boundThreadMappings(state, next); + }, base); + const saved = await transactIndexedHistory(replay).catch(() => null); + if (saved) { + unsavedHistoryUpdates = []; + unsavedHistoryBase = undefined; + publish(saved.history); // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel is scoped to the origin - if (changed) historyChannel?.postMessage(null); - }, - () => { - const { byProjectKey, projectKeyByThreadKey } = get(); - publish(transactLegacyHistory(update, { byProjectKey, projectKeyByThreadKey })); - }, - ); + if (saved.changed) historyChannel?.postMessage(null); + return; + } + const { byProjectKey, projectKeyByThreadKey } = get(); + const fallback = transactLegacyHistory( + replay, + unsavedHistoryBase ?? { byProjectKey, projectKeyByThreadKey }, + ); + unsavedHistoryBase = fallback.unsavedBase; + if (!unsavedHistoryBase) unsavedHistoryUpdates = []; + publish(fallback.history); + }); }; return mergeBrowserHistoryState(undefined, { @@ -538,10 +553,11 @@ if (typeof window !== "undefined") { } if (historyChannel) { historyChannel.onmessage = () => { - void transactIndexedHistory().then( - ({ history }) => useBrowserHistoryStore.setState({ byProjectKey: history.byProjectKey }), - () => undefined, - ); + historySync = historySync.then(async () => { + if (unsavedHistoryUpdates.length > 0) return; + const saved = await transactIndexedHistory().catch(() => null); + if (saved) useBrowserHistoryStore.setState({ byProjectKey: saved.history.byProjectKey }); + }); }; } const hydrate = (history: PersistedBrowserHistory) => { @@ -553,7 +569,7 @@ if (typeof window !== "undefined") { }, })); }; - void transactIndexedHistory((history) => history).then( + historySync = transactIndexedHistory((history) => history).then( ({ history }) => hydrate(history), () => hydrate(mergeHistorySnapshots(undefined, readHistorySnapshots()) ?? EMPTY_PERSISTED_HISTORY), From 2122f93e8e54f880831349b46eda335ee32be6df Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:08:42 -0300 Subject: [PATCH 62/87] fix(web): preserve browser history removals across storage recovery --- .../src/browserHistoryStore.browser.test.ts | 52 ++++++++ apps/web/src/browserHistoryStore.ts | 112 +++++++++++++----- 2 files changed, 134 insertions(+), 30 deletions(-) diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index b06eb3541669f..d604404808dfd 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -342,6 +342,58 @@ it("keeps visits saved while IndexedDB could not open", async () => { } }); +it("keeps a fallback deletion after IndexedDB recovers and an older tab writes", async () => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + const store = useBrowserHistoryStore.getState(); + store.recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + store.recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ + a: [oldEntry], + b: [otherEntry], + }), + ); + + { + using _transaction = vi.spyOn(IDBDatabase.prototype, "transaction").mockImplementation(() => { + throw new DOMException("Storage unavailable", "SecurityError"); + }); + store.removeUrl("a", oldEntry.url); + await vi.waitFor(() => expect(fallbackKeys()).toHaveLength(1)); + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ b: [otherEntry] }); + } + + const recovered = await openHistoryDocument(fixture); + await vi.waitFor(() => expect(fallbackKeys()).toEqual([])); + expect(recovered.getState().byProjectKey).toEqual({ b: [otherEntry] }); + const saved = await readHistoryFixture(db); + expect(saved).toHaveProperty("byProjectKey", { b: [otherEntry] }); + expect(JSON.stringify(saved)).not.toContain(oldEntry.url); + + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [oldEntry] } }, version: 1 }), + ); + const reloaded = await openHistoryDocument(fixture); + await vi.waitFor(() => expect(localStorage.getItem(storageKey)).toBeNull()); + expect(reloaded.getState().byProjectKey).toEqual({ b: [otherEntry] }); + + const revisit = { ...oldEntry, lastVisitedAt: page.lastVisitedAt }; + reloaded.getState().recordVisit("a", revisit.url, revisit.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey", { + a: [revisit], + b: [otherEntry], + }), + ); + } finally { + await resetHistoryFixture(); + } +}); + it.each(["localStorage", "IndexedDB"] as const)( "keeps unsaved changes when %s recovers", async (recoveredStorage) => { diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index 50fea702d9a5d..27ff4c159f5a0 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -1,3 +1,5 @@ +import { sha256 } from "@noble/hashes/sha2"; +import { bytesToHex } from "@noble/hashes/utils"; import { scopedProjectKey, scopedThreadKey, @@ -136,7 +138,10 @@ function evictExcessProjects( return Object.fromEntries(kept.map((key) => [key, byProjectKey[key] ?? []])); } -export function migratePersistedBrowserHistoryState(persistedState: unknown): { +export function migratePersistedBrowserHistoryState( + persistedState: unknown, + fallbackRemovals?: Readonly>, +): { byProjectKey: Record; } { if (!persistedState || typeof persistedState !== "object") return { byProjectKey: {} }; @@ -154,6 +159,12 @@ export function migratePersistedBrowserHistoryState(persistedState: unknown): { const normalizedUrl = normalizeHistoryUrl(url); if (!normalizedUrl) return []; if (!isValidHistoryTimestamp(lastVisitedAt)) return []; + if ( + fallbackRemovals && + lastVisitedAt <= + (fallbackRemovals[historyRemovalKey(projectKey, normalizedUrl)] ?? -Infinity) + ) + return []; return [ { url: normalizedUrl, @@ -225,9 +236,29 @@ function addPendingByThread( type PersistedBrowserHistory = Pick< BrowserHistoryStoreState, "byProjectKey" | "projectKeyByThreadKey" ->; +> & { readonly fallbackRemovals?: Readonly> }; + +type UpdateHistory = ( + state: PersistedBrowserHistory, + fallback?: boolean, +) => PersistedBrowserHistory; + +function historyRemovalKey(projectKey: string, url: string): string { + // Keep the removal without retaining the deleted URL. + return bytesToHex( + sha256(new TextEncoder().encode(JSON.stringify([projectKey, visitLookupKey(url)]))), + ); +} -type UpdateHistory = (state: PersistedBrowserHistory) => PersistedBrowserHistory; +function readFallbackRemovals(state: unknown): Record { + const raw = (state as { fallbackRemovals?: unknown } | null | undefined)?.fallbackRemovals; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; + return Object.fromEntries( + Object.entries(raw).filter( + ([key, value]) => /^[a-f0-9]{64}$/.test(key) && isValidHistoryTimestamp(value), + ), + ); +} function boundThreadMappings( previous: PersistedBrowserHistory, @@ -285,6 +316,7 @@ function readHistorySnapshots(): HistorySnapshot[] { history: { ...migratePersistedBrowserHistoryState(parsed?.state), projectKeyByThreadKey: migratePersistedThreadProjectKeys(parsed?.state), + fallbackRemovals: readFallbackRemovals(parsed?.state), }, }, ]; @@ -314,23 +346,27 @@ function mergeHistorySnapshots( saved: PersistedBrowserHistory | undefined, snapshots: readonly HistorySnapshot[], ): PersistedBrowserHistory | undefined { - for (const { history } of snapshots) { - saved = saved ? mergeLegacyHistory(saved, history) : history; + if (snapshots.length === 0) return saved; + const histories = snapshots.map(({ history }) => history); + if (saved) histories.unshift(saved); + const byProjectKey: Record = Object.create(null); + const fallbackRemovals: Record = {}; + for (const history of histories) { + for (const [projectKey, entries] of Object.entries(history.byProjectKey)) + (byProjectKey[projectKey] ??= []).push(...entries); + for (const [key, at] of Object.entries(history.fallbackRemovals ?? {})) + fallbackRemovals[key] = Math.max(at, fallbackRemovals[key] ?? -Infinity); } - return saved; -} - -// localStorage can gain visits after migration: from the fallback below, or a tab on an older build. -function mergeLegacyHistory( - saved: PersistedBrowserHistory, - legacy: PersistedBrowserHistory, -): PersistedBrowserHistory { - const byProjectKey = { ...saved.byProjectKey }; - for (const [projectKey, entries] of Object.entries(legacy.byProjectKey)) - byProjectKey[projectKey] = [...(byProjectKey[projectKey] ?? []), ...entries]; + const hasRemovals = Object.keys(fallbackRemovals).length > 0; return { - ...migratePersistedBrowserHistoryState({ byProjectKey }), - projectKeyByThreadKey: { ...legacy.projectKeyByThreadKey, ...saved.projectKeyByThreadKey }, + ...migratePersistedBrowserHistoryState( + { byProjectKey }, + hasRemovals ? fallbackRemovals : undefined, + ), + projectKeyByThreadKey: Object.fromEntries( + histories.toReversed().flatMap((history) => Object.entries(history.projectKeyByThreadKey)), + ), + ...(hasRemovals ? { fallbackRemovals } : {}), }; } @@ -338,7 +374,7 @@ function mergeLegacyHistory( function transactLegacyHistory(update: UpdateHistory, current: PersistedBrowserHistory) { const snapshots = readHistorySnapshots(); const previous = mergeHistorySnapshots(undefined, snapshots) ?? current; - const history = update(previous); + const history = update(previous, true); if (history === previous) return { history, unsavedBase: undefined }; try { window.localStorage.setItem( @@ -425,9 +461,9 @@ export const useBrowserHistoryStore = create()((set, g } historySync = historySync.then(async () => { unsavedHistoryUpdates.push(update); - const replay = (base: PersistedBrowserHistory) => + const replay: UpdateHistory = (base, fallback) => unsavedHistoryUpdates.reduce((state, apply) => { - const next = apply(state); + const next = apply(state, fallback); return next === state ? state : boundThreadMappings(state, next); }, base); const saved = await transactIndexedHistory(replay).catch(() => null); @@ -458,6 +494,11 @@ export const useBrowserHistoryStore = create()((set, g const normalized = normalizeHistoryUrl(url); if (!normalized) return; updateHistory((state) => { + if ( + state.fallbackRemovals && + at <= (state.fallbackRemovals[historyRemovalKey(projectKey, normalized)] ?? -Infinity) + ) + return state; const entries = state.byProjectKey[projectKey] ?? []; return { ...state, @@ -502,15 +543,26 @@ export const useBrowserHistoryStore = create()((set, g removeUrl: (projectKey, url) => { const normalized = normalizeHistoryUrl(url); if (!normalized) return; - updateHistory((state) => { - const entries = state.byProjectKey[projectKey]; - if (!entries) return state; - const next = entries.filter((candidate) => candidate.url !== normalized); - if (next.length === entries.length) return state; - const byProjectKey = { ...state.byProjectKey }; - if (next.length === 0) delete byProjectKey[projectKey]; - else byProjectKey[projectKey] = next; - return { ...state, byProjectKey }; + const observed = get().byProjectKey[projectKey]?.find((entry) => entry.url === normalized); + updateHistory((state, fallback) => { + const entries = state.byProjectKey[projectKey] ?? []; + const index = entries.findIndex((entry) => entry.url === normalized); + let next = state; + if (index !== -1) { + const byProjectKey = { ...state.byProjectKey }; + if (entries.length === 1) delete byProjectKey[projectKey]; + else byProjectKey[projectKey] = entries.toSpliced(index, 1); + next = { ...state, byProjectKey }; + } + if (!fallback) return next; + const removedThrough = Math.max( + entries[index]?.lastVisitedAt ?? -Infinity, + observed?.lastVisitedAt ?? -Infinity, + ); + if (removedThrough === -Infinity) return next; + const key = historyRemovalKey(projectKey, normalized); + if (removedThrough <= (state.fallbackRemovals?.[key] ?? -Infinity)) return next; + return { ...next, fallbackRemovals: { ...state.fallbackRemovals, [key]: removedThrough } }; }); }, registerThreadProject: (ref, projectKey) => { From 25f93027f19b7ab616c65ca99f8d77c7a22bdc15 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:13:23 -0300 Subject: [PATCH 63/87] fix: address checkout, Markdown, and provider review findings --- apps/desktop/src/app/DesktopCliShim.ts | 12 +-- .../src/git/sharedCheckoutGuard.test.ts | 12 +++ apps/server/src/git/sharedCheckoutGuard.ts | 16 ++-- .../src/provider/AntigravityProvider.test.ts | 50 +++++++++++- .../src/provider/AntigravityProvider.ts | 77 +++++++++++-------- apps/web/src/components/ChatView.tsx | 1 + .../chat/useQueuedRunEdit.browser.test.tsx | 39 +++++++++- .../src/components/chat/useQueuedRunEdit.ts | 14 +++- apps/web/src/markdown/markdownText.ts | 6 +- apps/web/src/markdown/wordsHast.test.ts | 31 ++++++++ apps/web/src/markdown/wordsHast.ts | 43 ++++++++--- .../provider-pi/src/server/adapter.test.ts | 6 +- packages/provider-pi/src/server/adapter.ts | 4 + packages/shared/src/assistantInsights.ts | 7 +- packages/shared/src/shell.test.ts | 14 +++- packages/shared/src/shell.ts | 52 ++++++++----- 16 files changed, 294 insertions(+), 90 deletions(-) diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 0f7e605da6b36..90f588d651ed7 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -122,15 +122,15 @@ export const renderCliShim = (input: { `${run("$mount")} <&9 9<&- &`, "cli=$!", "exec 9<&-", - `trap 'kill -TERM "$cli" 2>/dev/null' TERM`, - `trap 'kill -HUP "$cli" 2>/dev/null' HUP`, + `trap 'interrupted=1; kill -TERM "$cli" 2>/dev/null' TERM`, + `trap 'interrupted=1; kill -HUP "$cli" 2>/dev/null' HUP`, "trap '' INT", - "status=0", - 'wait "$cli" || status=$?', - // A trapped signal interrupts wait; wait again for the CLI's own exit status. - 'while kill -0 "$cli" 2>/dev/null; do', + // An interrupted wait returns a signal status even if the child has already exited. + "while :; do", + " interrupted=0", " status=0", ' wait "$cli" || status=$?', + ' if [ "$interrupted" -eq 0 ] || [ "$status" -le 128 ]; then break; fi', "done", 'exit "$status"', "", diff --git a/apps/server/src/git/sharedCheckoutGuard.test.ts b/apps/server/src/git/sharedCheckoutGuard.test.ts index db576a3943823..1e46ecfb1aefe 100644 --- a/apps/server/src/git/sharedCheckoutGuard.test.ts +++ b/apps/server/src/git/sharedCheckoutGuard.test.ts @@ -153,6 +153,18 @@ describe("assertCheckoutIdle", () => { }), ); + it.effect("refuses a switch when an activity lookup could not establish checkout state", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ repositoryRoot: "/repo", threads: [], failWorktreeLookup: true }), + ), + ); + expect(error.detail).toContain("Could not verify"); + }), + ); + it.effect("refuses a switch while a nested project or archived thread is working", () => Effect.gen(function* () { const error = yield* assertCheckoutIdle("test", "/repo").pipe( diff --git a/apps/server/src/git/sharedCheckoutGuard.ts b/apps/server/src/git/sharedCheckoutGuard.ts index faeca740db460..af06722c36f45 100644 --- a/apps/server/src/git/sharedCheckoutGuard.ts +++ b/apps/server/src/git/sharedCheckoutGuard.ts @@ -114,27 +114,31 @@ export const assertCheckoutIdle = Effect.fn("sharedCheckoutGuard.assertCheckoutI ...sharingTrackedFolders.flat(), ].map(({ id }) => id), ); - // Archiving does not stop a run, so archived threads can still be working. Each lookup fails - // open on its own, so one failure keeps what the others found. + // Archiving does not stop a run. Keep successful lookups so a busy thread can still be named. const snapshots = yield* Effect.forEach( [ ...checkoutPaths.map((worktreePath) => threadManagement.getShellSnapshot({ worktreePath })), ...[...projectIds].map((projectId) => threadManagement.getShellSnapshot({ projectId })), ], - (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => ({ threads: [], archivedThreads: [] }))), + (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => null)), { concurrency: "unbounded" }, ); const busy = busyThreadsInCheckout({ checkoutPaths, projectIds, - threads: snapshots.flatMap((snapshot) => [...snapshot.threads, ...snapshot.archivedThreads]), + threads: snapshots.flatMap((snapshot) => + snapshot ? [...snapshot.threads, ...snapshot.archivedThreads] : [], + ), }); const titles = [...new Map(busy.map((thread) => [thread.id, thread.title])).values()]; - if (titles.length === 0) return; + if (titles.length === 0 && !snapshots.includes(null)) return; return yield* new GitCommandError({ operation, command: "git checkout", cwd, - detail: describeBusyCheckout(titles), + detail: + titles.length > 0 + ? describeBusyCheckout(titles) + : "Could not verify that this checkout is idle. Try again or use a separate worktree.", }); }); diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 88589d1c9a773..a3811daa2f0b5 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -140,6 +140,9 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( readonly safe?: boolean; readonly probeUsage?: Effect.Effect; readonly rememberedRuntimeModes?: ReadonlyArray; + readonly beforeRememberRuntimeModes?: ( + modes: ReadonlyArray, + ) => Effect.Effect; } = {}, ) { const savedRuntimeModes = yield* Ref.make>>([]); @@ -159,7 +162,10 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( ...(options.rememberedRuntimeModes ? { rememberedRuntimeModes: options.rememberedRuntimeModes } : {}), - rememberRuntimeModes: (modes) => Ref.update(savedRuntimeModes, (saved) => [...saved, modes]), + rememberRuntimeModes: (modes) => + (options.beforeRememberRuntimeModes?.(modes) ?? Effect.void).pipe( + Effect.andThen(Ref.update(savedRuntimeModes, (saved) => [...saved, modes])), + ), probe: Ref.update(probeCalls, (count) => count + 1).pipe( Effect.andThen(Ref.get(probe)), Effect.flatten, @@ -411,6 +417,48 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { }), ); + it.effect("persists sign-out modes after an already-started session save", () => + Effect.gen(function* () { + const writing = yield* Deferred.make(); + const release = yield* Deferred.make(); + const harness = yield* makeHarness({ + beforeRememberRuntimeModes: (modes) => + modes.includes("auto") + ? Deferred.succeed(writing, undefined).pipe(Effect.andThen(Deferred.await(release))) + : Effect.void, + }); + yield* harness.initialize; + const session = yield* harness.provider + .onSessionStarted({ + ...started, + sessionSetupResult: { + ...sessionSetupResult, + modes: { + currentModeId: "default", + availableModes: [ + { id: "default", name: "Default" }, + { id: "auto", name: "Auto" }, + ], + }, + }, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(writing); + const signedOut = yield* harness.nextPublish( + (snapshot) => snapshot.auth.status === "unauthenticated", + ); + const signOut = yield* harness.provider.onSignedOut.pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* signedOut; + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(session); + yield* Fiber.join(signOut); + const saved = yield* Ref.get(harness.savedRuntimeModes); + expect(saved.map((modes) => modes.includes("auto"))).toEqual([true, false]); + }), + ); + it.effect("publishes session metadata and native commands without another health probe", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index f5e18f6bece9d..8b499e0808e20 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -19,6 +19,7 @@ import * as FiberHandle from "effect/FiberHandle"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; import * as Result from "effect/Result"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import type * as EffectAcpErrors from "effect-acp/errors"; @@ -249,13 +250,20 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null); } }; - const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* ( - previous: ReadonlyArray | undefined, - next: ReadonlyArray, - ) { - if (options.rememberRuntimeModes && previous?.join() !== next.join()) { - yield* options.rememberRuntimeModes(next); - } + const runtimeModesWriteGate = yield* Semaphore.make(1); + let rememberedRuntimeModes = initialDraft.supportedRuntimeModes; + const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* () { + const remember = options.rememberRuntimeModes; + if (!remember) return; + yield* runtimeModesWriteGate.withPermit( + Effect.gen(function* () { + const { draft } = yield* SubscriptionRef.get(metadata); + const current = draft.supportedRuntimeModes; + if (!current || rememberedRuntimeModes?.join() === current.join()) return; + yield* remember(current); + rememberedRuntimeModes = current; + }), + ); }); const getSnapshot = SubscriptionRef.get(metadata).pipe( Effect.flatMap((state) => options.stampIdentity(state.draft)), @@ -412,12 +420,12 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const supportsTextGeneration = yield* options.supportsTextGeneration; const updatedAt = DateTime.formatIso(yield* DateTime.now); const supportedRuntimeModes = antigravityRuntimeModes(started.sessionSetupResult); - const previousModes = yield* SubscriptionRef.modify(metadata, (state) => { + const accepted = yield* SubscriptionRef.modify(metadata, (state) => { if ( state.authRevision !== before.authRevision && state.draft.auth.status === "unauthenticated" ) { - return [supportedRuntimeModes, state] as const; + return [false, state] as const; } const { message: _previousMessage, ...draft } = state.draft; const workspaces = draft.workspaceSnapshots ?? []; @@ -453,9 +461,9 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func : {}), }, } satisfies AntigravityProviderState; - return [draft.supportedRuntimeModes, next] as const; + return [true, next] as const; }); - yield* rememberRuntimeModes(previousModes, supportedRuntimeModes); + if (accepted) yield* rememberRuntimeModes(); if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage(); }); @@ -509,30 +517,31 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func yield* resetUsage; if (!settings.enabled) return; const updatedAt = DateTime.formatIso(yield* DateTime.now); - const previousModes = yield* SubscriptionRef.modify(metadata, (state) => [ - state.draft.supportedRuntimeModes, - { - authRevision: state.authRevision + 1, - draft: { - ...state.draft, - auth: { - status: "unauthenticated", - ...(usesCredentials ? options.auth : {}), + yield* SubscriptionRef.update( + metadata, + (state) => + ({ + authRevision: state.authRevision + 1, + draft: { + ...state.draft, + auth: { + status: "unauthenticated", + ...(usesCredentials ? options.auth : {}), + }, + status: "warning", + message: signInMessage, + checkedAt: updatedAt, + models: [], + slashCommands: [], + skills: [], + workspaceSnapshots: [], + supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, + supportsTextGeneration: false, + usageLimits: undefined, }, - status: "warning", - message: signInMessage, - checkedAt: updatedAt, - models: [], - slashCommands: [], - skills: [], - workspaceSnapshots: [], - supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, - supportsTextGeneration: false, - usageLimits: undefined, - }, - } satisfies AntigravityProviderState, - ]); - yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO); + }) satisfies AntigravityProviderState, + ); + yield* rememberRuntimeModes(); discoveredSkills.clear(); thinkingLevels.clear(); }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 40c6edde46433..c15ace60b2675 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -552,6 +552,7 @@ export default function ChatView(props: ChatViewProps) { const queuedRunEdit = useQueuedRunEdit({ environmentId, routeThreadRef, + currentRouteThreadKeyRef, threadDraftTarget: baseComposerDraftTarget, activeThreadId: serverThread !== null || draftThread !== null ? threadId : null, serverProjection, diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index a88da51cce16e..08425b0271621 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -7,7 +7,7 @@ import { ThreadId, type ScopedThreadRef, } from "@t3tools/contracts"; -import { useImperativeHandle, type RefObject } from "react"; +import { useImperativeHandle, useLayoutEffect, useRef, type RefObject } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, @@ -124,14 +124,24 @@ function Harness(props: { readonly runStatus: string; readonly hookRef: RefObject; readonly messages: ReadonlyArray; + readonly promptRef?: { current: string }; }) { + const routeKey = runsKey(props.threadRef); + const currentRouteThreadKeyRef = useRef(routeKey); + useLayoutEffect(() => { + currentRouteThreadKeyRef.current = routeKey; + return () => { + currentRouteThreadKeyRef.current = null; + }; + }, [routeKey]); const result = useQueuedRunEdit({ environmentId: ENV, routeThreadRef: props.threadRef, + currentRouteThreadKeyRef, threadDraftTarget: props.threadRef, activeThreadId: props.threadRef.threadId, serverProjection: projection([{ id: RUN, status: props.runStatus }], props.messages), - promptRef: { current: "" }, + promptRef: props.promptRef ?? { current: "" }, composerRef: { current: null }, }); useImperativeHandle(props.hookRef, () => result); @@ -167,10 +177,17 @@ function view( runStatus: string, hook: { current: HookResult | null }, messages: ReadonlyArray = [], + promptRef?: { current: string }, ) { return ( - + ); } @@ -543,6 +560,22 @@ describe("useQueuedRunEdit", () => { }, ); + it("leaves the current prompt alone when another thread's edit finishes saving", async () => { + const { hook } = setup(); + const promptRef = { current: "" }; + const response = Promise.withResolvers<{ readonly _tag: "Success" }>(); + mocks.editQueuedRun.mockReturnValue(response.promise); + await using screen = await render(view(THREAD_A, "queued", hook, [], promptRef)); + await beginChangedEdit(hook); + const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {}); + await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce()); + await screen.rerender(view(THREAD_B, "queued", hook, [], promptRef)); + promptRef.current = "other thread"; + response.resolve({ _tag: "Success" }); + await act(() => saved); + expect(promptRef.current).toBe("other thread"); + }); + it("leaves a newer edit alone when a save from before navigation finishes", async () => { const { hook } = setup(); let finishSave: (result: { readonly _tag: "Success" }) => void = () => {}; diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 61907b93cfb22..df059ba0a7f6e 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -207,6 +207,7 @@ function useEditQueuedRunCommand() { export function useQueuedRunEdit(input: { readonly environmentId: EnvironmentId; readonly routeThreadRef: ScopedThreadRef; + readonly currentRouteThreadKeyRef: { readonly current: string | null }; readonly threadDraftTarget: ComposerThreadTarget; readonly activeThreadId: ThreadId | null; readonly serverProjection: ThreadStructure | null; @@ -216,6 +217,7 @@ export function useQueuedRunEdit(input: { const { environmentId, routeThreadRef, + currentRouteThreadKeyRef, threadDraftTarget, activeThreadId, serverProjection, @@ -247,7 +249,9 @@ export function useQueuedRunEdit(input: { })); const focusComposerSoon = () => { - window.requestAnimationFrame(() => composerRef.current?.focusAtEnd()); + window.requestAnimationFrame(() => { + if (currentRouteThreadKeyRef.current === editKey) composerRef.current?.focusAtEnd(); + }); }; const clearEditDraft = (runId: RunId) => { const target = queuedRunEditDraftId(routeThreadRef, runId); @@ -460,10 +464,12 @@ export function useQueuedRunEdit(input: { if (error !== null) return; if (changedAfterSave) return; releaseDraftAttachments(newAttachments); - promptRef.current = ""; clearEditDraft(editing.runId); - composerRef.current?.resetCursorState(); - focusComposerSoon(); + if (currentRouteThreadKeyRef.current === editKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + focusComposerSoon(); + } // A plain submit means "Update queued message"; only the opposite-action shortcut or // modifier-click asks to steer, as it does for a new follow-up. if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") { diff --git a/apps/web/src/markdown/markdownText.ts b/apps/web/src/markdown/markdownText.ts index b73e79e72436b..6c3e3d0588b32 100644 --- a/apps/web/src/markdown/markdownText.ts +++ b/apps/web/src/markdown/markdownText.ts @@ -64,5 +64,9 @@ export function renderCodexDirectivesForCopy(markdown: string): string { /** A link destination as written, with its character references and escapes resolved. */ export function decodeMarkdownLinkEscapes(href: string): string { const decoded = href.includes("&") ? decodeHTMLStrict(href) : href; - return isWindowsAbsolutePath(decoded) ? decoded : decoded.replace(/\\([!-/:-@[-`{-~])/g, "$1"); + if (isWindowsAbsolutePath(decoded)) return decoded; + return href.replace( + /\\([!-/:-@[-`{-~])|&(?:#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g, + (value, escaped: string | undefined) => escaped ?? decodeHTMLStrict(value), + ); } diff --git a/apps/web/src/markdown/wordsHast.test.ts b/apps/web/src/markdown/wordsHast.test.ts index 9ec5d255f99a3..478071201602d 100644 --- a/apps/web/src/markdown/wordsHast.test.ts +++ b/apps/web/src/markdown/wordsHast.test.ts @@ -1,3 +1,5 @@ +import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; +import { decodeMarkdownLinkEscapes } from "./markdownText"; import type { Element, Root } from "hast"; import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; @@ -204,6 +206,17 @@ describe("wordsHast", () => { expect(slices).toEqual(["[a](u)", "- [ ] task", "```sh\nls\n```", "- [b](./b.ts)"]); }); + it("preserves line breaks for both insight opener spellings", () => { + expect(shouldPreserveAssistantLineBreaks("`★ Insight ───`\nFirst\nSecond\n───")).toBe(true); + expect(shouldPreserveAssistantLineBreaks("★ Insight ───\nFirst\nSecond\n───")).toBe(true); + }); + + it("decodes link destinations without expanding escaped ampersands", () => { + expect(decodeMarkdownLinkEscapes("docs/a\\&.ts")).toBe("docs/a&.ts"); + expect(decodeMarkdownLinkEscapes("docs/a&b.ts")).toBe("docs/a&b.ts"); + expect(decodeMarkdownLinkEscapes("C:\\path\\a&b.ts")).toBe("C:\\path\\a&b.ts"); + }); + it("renders insight blocks as remarkAssistantInsights did", () => { const markdown = "Intro\n\n`★ Insight ─────────────────────────────────────`\n- one\n- two\n`─────────────────────────────────────────────────`\n\nAfter\n\n```\n★ Insight ─────\n```"; @@ -245,6 +258,13 @@ describe("wordsHast", () => { /^Plan one x two ]* data-markdown-math="inline"[^>]*>]*aria-label="a"/, ); expect(wordsHtml("x".repeat(30), options)).toBe("x".repeat(24)); + expect(wordsHtml("$a$" + "x".repeat(30), options)).toMatch(/<\/span>x{23}$/); + expect( + wordsHtml("$xyz$ more", { + math: true, + extensions: { preview: { maxLength: 2, fallback: "Empty" } }, + }), + ).toBe("Empty"); expect(wordsHtml("", options)).toBe("Thinking"); }); @@ -327,6 +347,11 @@ describe("wordsHast", () => { '

    Status\n\ncontinues

    ', '

    Status
    \n
    \ncontinues

    ', ], + [ + "Intro\n![shot](https://x.dev/a.png) \nNext", + '

    Intro
    \nshot
    \nNext

    ', + '

    Intro
    \nshot
    \nNext

    ', + ], [ "Hard \nbreak and a\\\nbackslash", '

    Hard
    \nbreak and a
    \nbackslash

    ', @@ -340,6 +365,12 @@ describe("wordsHast", () => { }, ); + it("keeps explicit table sections beside the implicit body", () => { + expect( + wordsHtml("
    Row
    Foot
    "), + ).toContain("RowFoot"); + }); + it("reads raw HTML attributes as an HTML parser does", () => { expect(wordsHtml('x')).toContain( 'href="https://x.dev/?q=1&copy=2&b"', diff --git a/apps/web/src/markdown/wordsHast.ts b/apps/web/src/markdown/wordsHast.ts index 7b3dbd2c8b9a1..0e3940701ff6a 100644 --- a/apps/web/src/markdown/wordsHast.ts +++ b/apps/web/src/markdown/wordsHast.ts @@ -18,6 +18,8 @@ import { sanitizeChatHast, } from "@t3tools/shared/markdownHast"; +import { ASSISTANT_INSIGHT_OPENING } from "@t3tools/shared/assistantInsights"; + import { rehypeChipPunctuation } from "../components/chat/markdownChipPunctuation"; import { rehypeHeadingIds } from "../components/chat/markdownFragments"; import { rehypeTextDirection } from "../components/chat/markdownTextDirection"; @@ -280,12 +282,24 @@ function normalizeRawTables(node: Root | Element) { if (child.type === "element") normalizeRawTables(child); } if (node.type !== "element" || node.tagName !== "table") return; - const first = node.children.findIndex((child) => isElement(child, "tr")); - if (first < 0) return; - node.children = [ - ...node.children.slice(0, first), - { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) }, - ]; + if (!node.children.some((child) => isElement(child, "tr"))) return; + const children: ElementContent[] = []; + let body: Element | undefined; + for (const child of node.children) { + if (isElement(child, "tr")) { + if (!body) { + body = { type: "element", tagName: "tbody", properties: {}, children: [] }; + children.push(body); + } + body.children.push(child); + } else if (body && child.type === "text" && child.value.trim() === "") { + body.children.push(child); + } else { + body = undefined; + children.push(child); + } + } + node.children = children; } // Words leaves these raw in Markdown destinations, where micromark percent-encodes them. @@ -750,7 +764,10 @@ function imageOwnsLine(items: ElementContent[], at: number): boolean { before === undefined || (before.type === "text" && /\n[ \t]*$/.test(before.value)) || isElement(before, "br"); - const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value)); + const endsLine = + after === undefined || + isElement(after, "br") || + (after.type === "text" && /^[ \t]*\n/.test(after.value)); return startsLine && endsLine; } @@ -867,7 +884,6 @@ const preserveImageSourceMeta = rehypePreserveImageSourceMeta(); const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks(); const groupChipPunctuation = rehypeChipPunctuation(); -const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; interface InsightSource { @@ -915,7 +931,7 @@ function insightSource(text: string, options: RenderOptions): InsightSource | nu const inCode = code.some(([start, end]) => original >= start && original < end); let output = line; if (indent === undefined) { - const opening = inCode ? null : INSIGHT_OPENING.exec(value); + const opening = inCode ? null : ASSISTANT_INSIGHT_OPENING.exec(value); if (opening && !skipped.has(lineIndex)) { indent = opening[1] ?? ""; opened++; @@ -1040,11 +1056,18 @@ function flattenPreview(tree: Root, preview: NonNullable remaining) { + remaining = 0; + return; + } + remaining -= length; flush(); hasContent = true; endsInSpace = false; // One line has no room for display math, which a preview shows inline. - const svg = node.children[0]; children.push( node.properties.dataMarkdownMath === "display" && svg?.type === "element" ? mathWrapper({ diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index b3e54117f02ee..04dd776ad6054 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4203,6 +4203,10 @@ describe("PiAdapterV2", () => { live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, { inputTokens: 50_668, cachedInputTokens: 40_101 }, ); + yield* fake.emit({ + type: "message_end", + message: { role: "assistant", usage: { ...usage, cacheRead: 40_201, totalTokens: 50_891 } }, + }); yield* fake.emit({ type: "agent_settled" }); const completed = yield* takeEvent( (event) => @@ -4210,7 +4214,7 @@ describe("PiAdapterV2", () => { ); assert.deepInclude( completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, - { inputTokens: 50_668, cachedInputTokens: 40_101 }, + { inputTokens: 50_768, cachedInputTokens: 40_201 }, ); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index e7803bbe9c5ee..243989ff25620 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -2386,6 +2386,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (turn === null) return; const message = event["message"]; if (recordString(message, "role") !== "assistant") return; + const usage = recordField(message, "usage"); + if ((nonNegativeInteger(usage, "totalTokens") ?? 0) > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } yield* completeOpenStreamItems(turn); const reportedProvider = recordString(message, "provider"); const reportedModelId = recordString(message, "model"); diff --git a/packages/shared/src/assistantInsights.ts b/packages/shared/src/assistantInsights.ts index 60f4ad1df349a..17cacf6b6f0b9 100644 --- a/packages/shared/src/assistantInsights.ts +++ b/packages/shared/src/assistantInsights.ts @@ -1,3 +1,8 @@ +export const ASSISTANT_INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; + export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); + return ( + text.includes("★ Insight") && + text.split(/\r\n|\r|\n/u).some((line) => ASSISTANT_INSIGHT_OPENING.test(line)) + ); } diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 08731a41c19ef..97fc960c570db 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -132,7 +132,11 @@ describe("readEnvironmentFromLoginShell", () => { encoding: "utf8", env: { PATH: process.env.PATH }, }).trim(); - NodeFS.copyFileSync(printenv, NodePath.join(tools, "printenv")); + NodeFS.writeFileSync( + NodePath.join(tools, "printenv"), + `#!/bin/sh\nexec '${printenv.replaceAll("'", "'\\''")}' "$@"\n`, + { mode: 0o755 }, + ); vi.stubEnv("PATH", tools); const shellPath = NodePath.join(home, "bin"); const bashEnv = NodePath.join(home, "env.bash"); @@ -675,8 +679,12 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); expect(yield* resolveCommandPath("MYTOOL~1", { env })).toBe(alias); expect(listed).toEqual([first, second]); - yield* fs.writeFileString(path.join(second, "late.EXE"), ""); - yield* fs.utimes(second, AGED_MTIME + 30, AGED_MTIME + 30); + const replacement = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(replacement, "late.EXE"), ""); + yield* fs.utimes(replacement, AGED_MTIME, AGED_MTIME); + yield* fs.rename(second, path.join(replacement, "previous")); + yield* fs.utimes(replacement, AGED_MTIME, AGED_MTIME); + yield* fs.rename(replacement, second); expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE")); expect(listed).toEqual([first, second, second]); }).pipe( diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index ffcc1110fe381..04ced1e7833db 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -583,7 +583,7 @@ export const CommandResolutionCache = Context.Reference | undefined; readonly reusable: boolean; @@ -618,11 +618,16 @@ function isReusableListing( return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS; } -const directoryMtime = (directory: string) => +const directoryListingInfo = (directory: string) => FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe( - Effect.map((info) => - info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined, - ), + Effect.map((info) => { + const modified = + info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined; + if (modified === undefined) return undefined; + const inode = Option.getOrUndefined(info.ino); + const stamp = inode ? [info.dev, inode, modified].join(":") : undefined; + return { modified, stamp }; + }), Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)), ); @@ -631,20 +636,22 @@ const listPathDirectory = Effect.fnUntraced(function* ( directory: string, ): Effect.fn.Return { const path = yield* Path.Path; - const modified = yield* directoryMtime(directory); - if (modified === null) { - return { modified, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) }; + const info = yield* directoryListingInfo(directory); + if (info === null) { + return { stamp: null, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) }; } - if (modified === undefined) return { modified, names: undefined, reusable: false }; + if (!info) return { stamp: undefined, names: undefined, reusable: false }; const listedAtMs = yield* Clock.currentTimeMillis; const entries = yield* FileSystem.FileSystem.use((fileSystem) => fileSystem.readDirectory(directory), ).pipe(Effect.orElseSucceed(() => undefined)); return { - modified, + stamp: info.stamp, names: entries && new Set(entries.map((entry) => entry.toLowerCase())), reusable: - entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute), + entries !== undefined && + info.stamp !== undefined && + isReusableListing(directory, info.modified, listedAtMs, path.isAbsolute), }; }); @@ -663,7 +670,7 @@ export const PathDirectoryListings = Context.Reference( const syncPathDirectoryListings = new Map< string, - { readonly modified: number; readonly names: ReadonlySet } + { readonly stamp: string; readonly names: ReadonlySet } >(); // The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. @@ -672,15 +679,17 @@ function listPathDirectorySync( isAbsolute: (path: string) => boolean, ): ReadonlySet | undefined { let modified: number; + let stamp: string | undefined; try { - const stats = NodeFS.statSync(directory); + const stats = NodeFS.statSync(directory, { bigint: true }); if (!stats.isDirectory()) return undefined; - modified = stats.mtimeMs; + modified = Number(stats.mtimeMs); + if (stats.ino !== 0n) stamp = [stats.dev, stats.ino, stats.mtimeNs].join(":"); } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; } const cached = syncPathDirectoryListings.get(directory); - if (cached?.modified === modified) return cached.names; + if (cached && cached.stamp === stamp) return cached.names; syncPathDirectoryListings.delete(directory); // This resolver runs outside Effect, so it has no Clock to read. // @effect-diagnostics-next-line globalDate:off @@ -691,12 +700,12 @@ function listPathDirectorySync( } catch { return undefined; } - if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { + if (stamp !== undefined && isReusableListing(directory, modified, listedAtMs, isAbsolute)) { if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { const oldest = syncPathDirectoryListings.keys().next().value; if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); } - syncPathDirectoryListings.set(directory, { modified, names }); + syncPathDirectoryListings.set(directory, { stamp, names }); } return names; } @@ -775,9 +784,12 @@ const findOnPath = Effect.fnUntraced(function* ( const matches: string[] = []; for (const pathEntry of pathEntries) { let listing = listings && (yield* Cache.get(listings, pathEntry)); - if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) { - yield* Cache.invalidate(listings, pathEntry); - listing = yield* Cache.get(listings, pathEntry); + if (listings && listing?.names) { + const current = yield* directoryListingInfo(pathEntry); + if (listing.stamp !== (current === null ? null : current?.stamp)) { + yield* Cache.invalidate(listings, pathEntry); + listing = yield* Cache.get(listings, pathEntry); + } } for (const candidate of commandCandidates) { if (isAbsentFromListing(listing?.names, candidate)) continue; From 70815042ff1a726ec02d6a7d0b0bab7148aee634 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:16:23 -0300 Subject: [PATCH 64/87] fix(workspace): reject blocked repository worktree destinations --- apps/server/src/workspace/TaskFolders.test.ts | 39 ++++++++++- .../src/workspace/TaskFolders.testkit.ts | 1 + apps/server/src/workspace/TaskFolders.ts | 65 +++++++++++++------ 3 files changed, 83 insertions(+), 22 deletions(-) diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index 5419ed4899dd8..c8eec6580da99 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -442,14 +442,47 @@ it.live("leaves a hook's link to an empty folder alone", () => state.workspaceRoot = project; state.trackedFolders = tracked(lib, inner); - const created = yield* create("feature").pipe(Effect.exit); - - assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause)); + const { taskFolder } = yield* create("feature"); + state.thread = { worktreePath: taskFolder.projectPath, branch: "feature" }; + const taskFolders = yield* TaskFolders.TaskFolders; + const error = yield* taskFolders + .addRepository({ threadId, repositoryPath: inner }) + .pipe(Effect.flip); + assert.include(error.detail, "link or file"); assert.deepStrictEqual(yield* fileSystem.readDirectory(target), []); + assert.deepStrictEqual((yield* taskFolders.find(taskFolder.root))?.repositories, []); }), ), ); +it.live( + "reports a collision when the project checkout already has files at the repository path", + () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, run, repository, worktreeCount } = yield* fixture; + const project = yield* repository("p"); + const destination = path.join(project, "vendor", "lib"); + yield* fileSystem.makeDirectory(destination, { recursive: true }); + yield* fileSystem.writeFileString(path.join(destination, ".gitkeep"), ""); + yield* run(project, "add", "vendor/lib/.gitkeep"); + yield* run(project, "commit", "-m", "track placeholder"); + const lib = yield* repository("p/vendor/lib"); + state.workspaceRoot = project; + state.trackedFolders = tracked(lib); + + const error = yield* create("feature").pipe(Effect.flip); + + assert.include(error.detail, "already holds files"); + assert.include(error.detail, "vendor"); + assert.equal(yield* worktreeCount(project), 1); + assert.equal(yield* worktreeCount(lib), 1); + assert.deepStrictEqual(yield* (yield* TaskFolderStore.TaskFolderStore).list, []); + assert.isTrue(yield* fileSystem.exists(path.join(destination, ".gitkeep"))); + }), + ), +); + it.live("treats a project folder inside a larger repository as plain", () => withState((state) => Effect.gen(function* () { diff --git a/apps/server/src/workspace/TaskFolders.testkit.ts b/apps/server/src/workspace/TaskFolders.testkit.ts index 3fec74ce9dd66..965a4b7d1832a 100644 --- a/apps/server/src/workspace/TaskFolders.testkit.ts +++ b/apps/server/src/workspace/TaskFolders.testkit.ts @@ -40,6 +40,7 @@ export const layerTaskFoldersWithGit = (state: TaskFoldersTestState) => { .execute({ operation: "task-folders-test", cwd, args, allowNonZeroExit: true }) .pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : null))); return Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: (cwd) => succeeds(cwd, ["rev-parse", "--show-toplevel"]), createWorktree: git.createWorktree, removeWorktree: git.removeWorktree, deleteLocalBranch: git.deleteLocalBranch, diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 17bfc153be5f5..81f507ab930f8 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -242,6 +242,8 @@ const make = Effect.gen(function* () { const exists = (target: string) => fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)); + const realPath = (target: string) => + fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target)); const isRepository = (folder: string) => exists(path.join(folder, ".git")); const occupied = Effect.fnUntraced(function* (target: string) { if (!(yield* exists(target))) return false; @@ -346,15 +348,13 @@ const make = Effect.gen(function* () { // rename: a worktree linked to the repository, on the thread's branch. Null when it is. /** The checkout's own Git directory when it is a worktree linked to its repository. */ const linkedGitDir = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) { - const real = (target: string) => - fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target)); const resolved = yield* gitDirPointer(checkout.worktreePath); if ( resolved === null || !isWithinRoot( path, - yield* real(resolved), - path.join(yield* real(yield* commonGitDir(checkout.repositoryPath)), "worktrees"), + yield* realPath(resolved), + path.join(yield* realPath(yield* commonGitDir(checkout.repositoryPath)), "worktrees"), ) ) return null; @@ -364,7 +364,7 @@ const make = Effect.gen(function* () { .pipe(Effect.orElseSucceed(() => ""))).trim(); if (registered === "") return null; const registeredDirectory = path.dirname(path.resolve(resolved, registered)); - return (yield* real(registeredDirectory)) === (yield* real(checkout.worktreePath)) + return (yield* realPath(registeredDirectory)) === (yield* realPath(checkout.worktreePath)) ? resolved : null; }); @@ -858,6 +858,23 @@ const make = Effect.gen(function* () { const locked = (taskFolder: Pick, effect: Effect.Effect) => withWorkspaceLease(path.resolve(taskFolder.projectPath), effect); + const blockedWorktreePath = Effect.fnUntraced(function* (root: string, worktreePath: string) { + let target = root; + for (const segment of path.relative(root, worktreePath).split(path.sep)) { + target = path.join(target, segment); + if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) return target; + const info = yield* fileSystem.stat(target).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed(null), + ), + ); + if (info === null) break; + if (info.type !== "Directory") return target; + } + return null; + }); + const createRepositoryWorktree = Effect.fnUntraced(function* ( taskFolder: TaskFolder, repository: ProjectTrackedFolder, @@ -867,25 +884,26 @@ const make = Effect.gen(function* () { ) { const worktreePath = mapped(taskFolder, repository.path); // A hook may place a link anywhere along the path to a tracked repository. - const segments = path.relative(taskFolder.root, worktreePath).split(path.sep); - let target = taskFolder.root; - for (const segment of segments) { - target = path.join(target, segment); - if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) - return "blocked" as const; - const info = yield* fileSystem.stat(target).pipe(Effect.option); - if (Option.isNone(info)) break; - if (info.value.type !== "Directory") return "blocked" as const; - } + if ((yield* blockedWorktreePath(taskFolder.root, worktreePath)) !== null) + return "blocked" as const; const checkout = { repositoryPath: repository.path, worktreePath, name: repository.name, } satisfies TaskFolderRepository; if (yield* occupied(worktreePath)) { - return (yield* unadoptable(checkout, branch)) === null - ? { repository: checkout, fromOrigin: false } - : null; + if ((yield* unadoptable(checkout, branch)) === null) + return { repository: checkout, fromOrigin: false }; + const existingRoot = yield* git.repositoryRoot(worktreePath); + if ( + existingRoot !== null && + path.relative(yield* realPath(existingRoot), yield* realPath(worktreePath)) === "" + ) + return null; + return yield* new TaskFolderError({ + operation: "create", + detail: `${worktreePath} already holds files. Move the existing files or choose a different repository folder.`, + }); } yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true }); const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch); @@ -1226,7 +1244,16 @@ const make = Effect.gen(function* () { path.relative(taskFolder.projectRoot, repositoryPath), ).pipe(Effect.mapError(fail("add-repository", "Could not prepare the folder"))) : true; - if (!opened || (yield* occupied(worktreePath))) + const blocked = opened + ? yield* blockedWorktreePath(taskFolder.root, worktreePath).pipe( + Effect.mapError(fail("add-repository", "Could not inspect the worktree path")), + ) + : worktreePath; + if (blocked !== null) + return yield* refuse( + `${blocked} is blocked by a link or file, so no worktree can go there.`, + ); + if (yield* occupied(worktreePath)) return yield* refuse(`${worktreePath} already holds files, so no worktree can go there.`); // The link the worktree took the place of comes back when the worktree does not stay. const relink = wasLinked From 947cc80379d0b608fbde12b5c5ba42f21bf43f72 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:25:45 -0300 Subject: [PATCH 65/87] fix(git): preserve the inferred private pull request base on retry --- apps/server/src/git/GitManager.test.ts | 46 ++++++++++++++++++++++++-- apps/server/src/git/GitManager.ts | 21 ++++++------ 2 files changed, 53 insertions(+), 14 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 19a86f6783f22..f8080131433a3 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -5113,9 +5113,25 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); - it.effect( - "createPullRequest opens a private PR from the companion and never pushes to origin", - () => + it.effect.each([ + { + name: "inferred base", + configuredBaseRef: null, + expectedBaseRef: "refs/remotes/origin/release", + }, + { + name: "stale base", + configuredBaseRef: "refs/remotes/origin/retired", + expectedBaseRef: "refs/remotes/origin/release", + }, + { + name: "valid base", + configuredBaseRef: "refs/heads/release", + expectedBaseRef: "refs/heads/release", + }, + ])( + "createPullRequest opens a private PR from the companion and never pushes to origin ($name)", + ({ configuredBaseRef, expectedBaseRef }) => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); yield* initRepo(repoDir); @@ -5125,6 +5141,10 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { yield* runGit(repoDir, ["push", "-u", "origin", "main"]); yield* runGit(repoDir, ["push", "origin", "main:refs/heads/release"]); yield* runGit(repoDir, ["checkout", "-b", "sec/fix", "--track", "origin/release"]); + if (configuredBaseRef !== null) { + yield* runGit(repoDir, ["branch", "release", "origin/release"]); + yield* runGit(repoDir, ["config", "branch.sec/fix.t3-merge-base-ref", configuredBaseRef]); + } NodeFS.writeFileSync(NodePath.join(repoDir, "fix.txt"), "fix\n"); yield* runGit(repoDir, ["add", "fix.txt"]); yield* runGit(repoDir, ["commit", "-m", "Fix"]); @@ -5154,6 +5174,19 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { expect(created(unsupported.providerCalls)).toEqual([]); const privateRemote = { url: companionDir, repository: "pingdotgg/codething-mvp.private" }; + const failed = yield* makeManager({ + providerScenario: { + privateRemote, + failWith: "Could not open the private PR", + failAfterCalls: 1, + }, + }); + const failure = yield* Effect.flip(createPrivate(failed.manager)); + expect(failure.message).toContain("Could not open the private PR"); + expect(created(failed.providerCalls)).toMatchObject([{ baseRefName: "release" }]); + expect( + (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(), + ).toBe("pingdotgg/sec/fix"); const open = { number: 9, title: "Fix", @@ -5193,6 +5226,13 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }); yield* createPrivate(retry.manager); expect(created(retry.providerCalls)).toMatchObject([{ baseRefName: "release" }]); + expect( + (yield* runGit(repoDir, [ + "config", + "--get", + "branch.sec/fix.t3-merge-base-ref", + ])).stdout.trim(), + ).toBe(expectedBaseRef); // Later commits follow the recorded push remote. NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 32bddd35b1c14..f574e0069f905 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2441,7 +2441,14 @@ export const make = Effect.gen(function* () { remoteName: headContext.remoteName, }); if (upstreamBranch.length > 0 && upstreamBranch !== branch) { - return { baseBranch: upstreamBranch, baseRef: upstreamBranch }; + return { + baseBranch: upstreamBranch, + baseRef: upstreamBranch, + inferredUpstreamBaseRef: + upstreamRef === upstreamBranch + ? `refs/heads/${upstreamBranch}` + : `refs/remotes/${upstreamRef}`, + }; } } @@ -2948,16 +2955,8 @@ export const make = Effect.gen(function* () { ), Effect.tapError(() => invalidateStatus(cwd)), ); - if ( - input.baseBranch === undefined && - status.upstreamRef !== null && - (yield* gitCore.readBranchBase(cwd, branch)) === null && - (yield* gitCore.readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`)) === null - ) { - const baseRef = - status.upstreamRef === baseBranch - ? `refs/heads/${baseBranch}` - : `refs/remotes/${status.upstreamRef}`; + const baseRef = input.baseBranch === undefined ? resolved.inferredUpstreamBaseRef : undefined; + if (baseRef !== undefined) { if ((yield* gitCore.resolveBranchName(cwd, baseRef)) === baseBranch) { yield* gitCore.writeConfigValue({ cwd, From 39ba5f1f9735f8d4d50b2b59778364fd91d6e617 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:32:03 -0300 Subject: [PATCH 66/87] fix(opencode): reconcile accepted commands after status probe failures --- .../Adapters/OpenCode2AdapterV2.test.ts | 28 ++++++++++--- .../src/server/v2/adapter.ts | 42 ++++++++++++------- 2 files changed, 51 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index bb65665959008..b670ec6cf8759 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -3703,7 +3703,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); - it.effect.each(["idle", "active probe failed"] as const)( + it.effect.each(["idle", "active probe failed", "unauthorized active probe"] as const)( "settles a workspace command that never starts an execution (%s)", (probe) => Effect.gen(function* () { @@ -3738,10 +3738,23 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ] : [ - reply("session.active", { - status: 503, - body: { message: "temporarily unavailable" }, - }), + reply( + "session.active", + probe === "unauthorized active probe" + ? { + status: 401, + body: { _tag: "UnauthorizedError", message: "Authentication required" }, + } + : { status: 503, body: { message: "temporarily unavailable" } }, + ), + ...(probe === "unauthorized active probe" + ? [ + out("session.active"), + replyData("session.active", { [SESSION]: { type: "running" } }), + out("session.interrupt", { sessionID: SESSION }), + reply("session.interrupt", { interrupted: true }), + ] + : []), ]), ]); const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); @@ -3756,6 +3769,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { (yield* Fiber.join(terminal))?.status, probe === "idle" ? "completed" : "failed", ); + if (probe === "unauthorized active probe") { + const next = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn(secondTurn(thread)); + assert.equal((yield* Fiber.join(next))?.failure?.message, OPENCODE_2_STILL_STOPPING); + } }).pipe(Effect.scoped), ); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 00dcb67cfff7a..672ce499ec5ac 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4744,22 +4744,36 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr // A command that never prompts the model starts no execution, so no event ends its turn. const idle = () => state.active === turn && !busy.has(sessionId); if (!idle()) return; - const active = yield* client.session.active().pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT)); - if (sessionId in active) return; - // An execution that already ended left history behind; its events may still trail this reply. - const ran = yield* OpenCode2Client.paginate( - { sessionID, order: "desc" as const, limit: 1 }, - client.message.list, - ).pipe( - Stream.takeWhile((message) => message.id !== before), - Stream.filter( - (message) => - message.type === "user" || message.type === "assistant" || message.type === "idle", + const hasExecution = yield* Effect.gen(function* () { + const active = yield* client.session + .active() + .pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT)); + if (sessionId in active) return true; + // An ended execution left history behind, but its events may still trail this reply. + const ran = yield* OpenCode2Client.paginate( + { sessionID, order: "desc" as const, limit: 1 }, + client.message.list, + ).pipe( + Stream.takeWhile((message) => message.id !== before), + Stream.filter( + (message) => + message.type === "user" || + message.type === "assistant" || + message.type === "idle", + ), + Stream.runHead, + Effect.timeout(ACTIVE_CHECK_TIMEOUT), + ); + return Option.isSome(ran); + }).pipe( + // The command was accepted, even if the follow-up request returns a rejection. + Effect.tapError(() => + Effect.sync(() => { + if (state.active === turn) markUnsettled(state); + }), ), - Stream.runHead, - Effect.timeout(ACTIVE_CHECK_TIMEOUT), ); - if (ran._tag === "Some") return; + if (hasExecution) return; return yield* lock.withPermit( Effect.suspend(() => idle() From 280a3915a0fccae000cf62f4db6b376049ae4016 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:46:31 -0300 Subject: [PATCH 67/87] fix: address checkout, composer, and provider review findings --- apps/server/src/git/GitManager.test.ts | 1 + apps/server/src/git/GitManager.ts | 6 + .../src/git/sharedCheckoutGuard.test.ts | 84 +++++++--- apps/server/src/git/sharedCheckoutGuard.ts | 148 +++++++++--------- .../orchestration-v2/ProjectionStore.test.ts | 7 + .../src/orchestration-v2/ProjectionStore.ts | 24 +-- .../ThreadManagementService.ts | 2 +- .../src/components/ChatView.browser.test.tsx | 18 ++- .../ComposerPrimaryActions.browser.test.tsx | 7 + .../chat/ComposerPrimaryActions.tsx | 2 +- apps/web/src/markdown/wordsHast.test.ts | 11 ++ apps/web/src/markdown/wordsHast.ts | 29 ++-- docs/user/thread-sidebar.md | 2 +- .../src/server/adapter.test.ts | 55 +++++-- .../provider-cursor/src/server/adapter.ts | 2 +- ...anStackSourceSourceControlProvider.test.ts | 23 ++- .../TanStackSourceSourceControlProvider.ts | 20 ++- 17 files changed, 290 insertions(+), 151 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index f8080131433a3..48a0050a29d52 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -5173,6 +5173,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { expect(yield* heads("origin")).toEqual(["refs/heads/main", "refs/heads/release"]); expect(created(unsupported.providerCalls)).toEqual([]); + yield* runGit(repoDir, ["remote", "add", "-t", "other", "pingdotgg", companionDir]); const privateRemote = { url: companionDir, repository: "pingdotgg/codething-mvp.private" }; const failed = yield* makeManager({ providerScenario: { diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index f574e0069f905..d661a83aa1669 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2965,6 +2965,12 @@ export const make = Effect.gen(function* () { }); } } + yield* gitCore.fetchRemoteTrackingBranch({ cwd, remoteName, remoteBranch: branch }).pipe( + Effect.mapError((cause) => + fail("Could not fetch the published private branch: " + cause.detail, cause), + ), + Effect.tapError(() => invalidateStatus(cwd)), + ); // The companion branch is the pull request's head, so status finds it through the upstream. yield* gitCore .setBranchUpstream({ cwd, branch, remoteName, remoteBranch: branch }) diff --git a/apps/server/src/git/sharedCheckoutGuard.test.ts b/apps/server/src/git/sharedCheckoutGuard.test.ts index 1e46ecfb1aefe..6ce8e8f66ed6f 100644 --- a/apps/server/src/git/sharedCheckoutGuard.test.ts +++ b/apps/server/src/git/sharedCheckoutGuard.test.ts @@ -2,6 +2,7 @@ import { ProjectId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as FileSystem from "effect/FileSystem"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; @@ -67,11 +68,17 @@ describe("assertCheckoutIdle", () => { const guardLayer = (input: { readonly repositoryRoot: string; readonly threads: ReadonlyArray>; - readonly failWorktreeLookup?: boolean; + readonly failActivityLookup?: boolean; readonly nestedWorkspaceRoot?: string; readonly parentTracksCheckout?: boolean; + readonly projectRoot?: string; + readonly realPaths?: Readonly>; + readonly taskCheckout?: string; }) => Layer.mergeAll( + FileSystem.layerNoop({ + realPath: (path) => Effect.succeed(input.realPaths?.[path] ?? path), + }), Layer.mock(GitWorkflowService.GitWorkflowService)({ repositoryRoot: (cwd) => Effect.succeed(cwd.startsWith("/repo/child") ? "/repo/child" : input.repositoryRoot), @@ -79,7 +86,7 @@ describe("assertCheckoutIdle", () => { Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed({ projects: [ - { id: projectId, workspaceRoot: "/repo" }, + { id: projectId, workspaceRoot: input.projectRoot ?? "/repo" }, { id: nestedProjectId, workspaceRoot: input.nestedWorkspaceRoot ?? "/repo/packages/app", @@ -96,23 +103,26 @@ describe("assertCheckoutIdle", () => { } as never), }), Layer.mock(WorkspaceFolders.WorkspaceFolders)({ - forThread: ({ projectId }) => + forThread: ({ projectId, worktreePath }) => Effect.succeed({ folders: - projectId === otherProjectId && input.parentTracksCheckout - ? [{ path: input.repositoryRoot, name: "Checkout", isGitRepository: true }] - : [], + worktreePath === "/task" && input.taskCheckout + ? [{ path: input.taskCheckout, name: "Task checkout", isGitRepository: true }] + : projectId === otherProjectId && input.parentTracksCheckout + ? [{ path: input.repositoryRoot, name: "Checkout", isGitRepository: true }] + : [], extraRoots: [], }), }), Layer.mock(ThreadManagementService.ThreadManagementService)({ getShellSnapshot: (options) => - options?.worktreePath !== undefined && input.failWorktreeLookup - ? Effect.fail("worktree lookup failed" as never) + options?.activityOnly === true && input.failActivityLookup + ? Effect.fail("activity lookup failed" as never) : Effect.succeed( (() => { const matching = input.threads.filter( (candidate) => + (!options?.activityOnly || candidate.activityRunStatus !== null) && (options?.projectId === undefined || candidate.projectId === options.projectId) && (options?.worktreePath === undefined || @@ -137,28 +147,12 @@ describe("assertCheckoutIdle", () => { }), ); - it.effect("keeps a busy thread when another lookup fails", () => - Effect.gen(function* () { - const error = yield* assertCheckoutIdle("test", "/repo").pipe( - Effect.flip, - Effect.provide( - guardLayer({ - repositoryRoot: "/repo", - threads: [thread("local running")], - failWorktreeLookup: true, - }), - ), - ); - expect(error.detail).toContain("'local running'"); - }), - ); - it.effect("refuses a switch when an activity lookup could not establish checkout state", () => Effect.gen(function* () { const error = yield* assertCheckoutIdle("test", "/repo").pipe( Effect.flip, Effect.provide( - guardLayer({ repositoryRoot: "/repo", threads: [], failWorktreeLookup: true }), + guardLayer({ repositoryRoot: "/repo", threads: [], failActivityLookup: true }), ), ); expect(error.detail).toContain("Could not verify"); @@ -220,6 +214,46 @@ describe("assertCheckoutIdle", () => { }), ); + it.effect("matches a project and linked worktree recorded under symlink aliases", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + projectRoot: "/alias", + realPaths: { "/alias": "/repo", "/worktree-alias": "/repo" }, + threads: [ + thread("aliased project"), + thread("aliased worktree", { + projectId: otherProjectId, + worktreePath: "/worktree-alias", + }), + ], + }), + ), + ); + expect(error.detail).toContain("'aliased project'"); + expect(error.detail).toContain("'aliased worktree'"); + }), + ); + + it.effect("refuses a switch in a checkout belonging to a running task folder", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/task/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/task/repo", + taskCheckout: "/task/repo", + threads: [thread("task running", { worktreePath: "/task" })], + }), + ), + ); + expect(error.detail).toContain("'task running'"); + }), + ); + it.effect("allows a switch when no thread is working", () => assertCheckoutIdle("test", "/repo").pipe( Effect.provide( diff --git a/apps/server/src/git/sharedCheckoutGuard.ts b/apps/server/src/git/sharedCheckoutGuard.ts index af06722c36f45..3f12240d9bf5c 100644 --- a/apps/server/src/git/sharedCheckoutGuard.ts +++ b/apps/server/src/git/sharedCheckoutGuard.ts @@ -5,6 +5,8 @@ import { } from "@t3tools/contracts"; import { isWindowsAbsolutePath, normalizeProjectPathForComparison } from "@t3tools/shared/path"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as GitWorkflowService from "./GitWorkflowService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; @@ -55,90 +57,86 @@ export const assertCheckoutIdle = Effect.fn("sharedCheckoutGuard.assertCheckoutI const projectService = yield* ProjectService.ProjectService; const threadManagement = yield* ThreadManagementService.ThreadManagementService; const workspaceFolders = yield* WorkspaceFolders.WorkspaceFolders; - // `git checkout` from a subdirectory moves the whole checkout; records may hold either spelling. + const fileSystem = yield* FileSystem.FileSystem; + const identify = (path: string) => + fileSystem.realPath(path).pipe( + Effect.orElseSucceed(() => path), + Effect.map(checkoutIdentity), + ); const root = yield* gitWorkflow.repositoryRoot(cwd).pipe(Effect.orElseSucceed(() => null)); - const checkoutPaths = [...new Set([cwd, ...(root === null ? [] : [root])])]; - const checkoutIds = new Set(checkoutPaths.map(checkoutIdentity)); - const rootId = root === null ? null : checkoutIdentity(root); + const cwdId = yield* identify(cwd); + const rootId = root === null ? null : yield* identify(root); const rootPrefix = rootId === null ? null : rootId.endsWith("/") ? rootId : rootId + "/"; - const projects = yield* projectService.snapshot.pipe( - Effect.map((snapshot) => snapshot.projects), - Effect.orElseSucceed(() => []), + const failure = (detail: string) => + new GitCommandError({ operation, command: "git checkout", cwd, detail }); + const cannotVerify = () => + failure("Could not verify that this checkout is idle. Try again or use a separate worktree."); + const snapshot = yield* threadManagement + .getShellSnapshot({ activityOnly: true }) + .pipe(Effect.mapError(cannotVerify)); + // Archiving a thread does not stop its run. + const threads = [...snapshot.threads, ...snapshot.archivedThreads].filter( + (thread) => (thread.activityRunStatus ?? null) !== null, ); - // A project rooted inside the checkout shares it, as in a monorepo package, unless it is its - // own repository nested there. - const nested = yield* Effect.forEach( - projects.filter(({ workspaceRoot }) => { - const id = checkoutIdentity(workspaceRoot); - return rootPrefix !== null && !checkoutIds.has(id) && id.startsWith(rootPrefix); - }), - (project) => - gitWorkflow.repositoryRoot(project.workspaceRoot).pipe( - Effect.map((projectRoot) => - projectRoot !== null && checkoutIdentity(projectRoot) === rootId ? [project] : [], - ), - Effect.orElseSucceed(() => []), - ), - { concurrency: "unbounded" }, + const localIds = new Set( + threads.flatMap((thread) => (thread.worktreePath === null ? [thread.projectId] : [])), ); - const sharingTrackedFolders = yield* Effect.forEach( - projects.filter(({ workspaceRoot, trackedFolders }) => { - const id = checkoutIdentity(workspaceRoot); - return ( - rootId !== null && - !checkoutIds.has(id) && - (rootId.startsWith(id.endsWith("/") ? id : id + "/") || (trackedFolders?.length ?? 0) > 0) - ); - }), + const linkedThreads = new Map(); + for (const thread of threads) { + if (thread.worktreePath !== null) linkedThreads.set(thread.worktreePath, thread.projectId); + } + const projectList = + localIds.size === 0 + ? [] + : (yield* projectService.snapshot.pipe(Effect.mapError(cannotVerify))).projects; + const sameCheckout = (id: string) => id === cwdId || id === rootId; + const sameRepository = Effect.fnUntraced(function* (path: string) { + const actual = yield* gitWorkflow.repositoryRoot(path).pipe(Effect.mapError(cannotVerify)); + return actual !== null && sameCheckout(yield* identify(actual)); + }); + const reachesCheckout = Effect.fnUntraced(function* ( + projectId: ProjectId, + worktreePath: string | null, + ) { + const { folders } = yield* workspaceFolders + .forThread({ projectId, worktreePath }) + .pipe(Effect.mapError(cannotVerify)); + const match = yield* Effect.findFirst(folders, (folder) => + folder.isGitRepository ? sameRepository(folder.path) : Effect.succeed(false), + ); + return Option.isSome(match); + }); + const matchingProjects = yield* Effect.filter( + projectList.filter((project) => localIds.has(project.id)), (project) => - workspaceFolders.forThread({ projectId: project.id, worktreePath: null }).pipe( - Effect.flatMap(({ folders }) => - Effect.findFirst(folders, (folder) => - gitWorkflow.repositoryRoot(folder.path).pipe( - Effect.map( - (folderRoot) => folderRoot !== null && checkoutIdentity(folderRoot) === rootId, - ), - Effect.orElseSucceed(() => false), - ), - ), - ), - Effect.map((match) => (match._tag === "Some" ? [project] : [])), - Effect.orElseSucceed(() => []), - ), + Effect.gen(function* () { + const id = yield* identify(project.workspaceRoot); + if (sameCheckout(id)) return true; + if ( + rootPrefix !== null && + id.startsWith(rootPrefix) && + (yield* sameRepository(project.workspaceRoot)) + ) + return true; + return yield* reachesCheckout(project.id, null); + }), { concurrency: 4 }, ); - const projectIds = new Set( - [ - ...projects.filter(({ workspaceRoot }) => checkoutIds.has(checkoutIdentity(workspaceRoot))), - ...nested.flat(), - ...sharingTrackedFolders.flat(), - ].map(({ id }) => id), - ); - // Archiving does not stop a run. Keep successful lookups so a busy thread can still be named. - const snapshots = yield* Effect.forEach( - [ - ...checkoutPaths.map((worktreePath) => threadManagement.getShellSnapshot({ worktreePath })), - ...[...projectIds].map((projectId) => threadManagement.getShellSnapshot({ projectId })), - ], - (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => null)), - { concurrency: "unbounded" }, + const matchingWorktrees = yield* Effect.filter( + [...linkedThreads], + ([path, projectId]) => + Effect.gen(function* () { + if (sameCheckout(yield* identify(path))) return true; + return yield* reachesCheckout(projectId, path); + }), + { concurrency: 4 }, ); const busy = busyThreadsInCheckout({ - checkoutPaths, - projectIds, - threads: snapshots.flatMap((snapshot) => - snapshot ? [...snapshot.threads, ...snapshot.archivedThreads] : [], - ), + checkoutPaths: matchingWorktrees.map(([path]) => path), + projectIds: new Set(matchingProjects.map((project) => project.id)), + threads, }); + if (busy.length === 0) return; const titles = [...new Map(busy.map((thread) => [thread.id, thread.title])).values()]; - if (titles.length === 0 && !snapshots.includes(null)) return; - return yield* new GitCommandError({ - operation, - command: "git checkout", - cwd, - detail: - titles.length > 0 - ? describeBusyCheckout(titles) - : "Could not verify that this checkout is idle. Try again or use a separate worktree.", - }); + return yield* failure(describeBusyCheckout(titles)); }); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index b6539e46344f1..d420564507bd9 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -8531,6 +8531,13 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { (row) => row.id === threadId, )!; const memoryShell = ProjectionStore.threadShellFromProjection(projection); + const { threads: workingThreads } = yield* projectionStore.getShellSnapshot({ + activityOnly: true, + }); + assert.equal( + workingThreads.some((row) => row.id === threadId), + activityStatus !== "completed", + ); const expected = activityStatus === "completed" ? null : DateTime.toEpochMillis(now); const timestamp = (value: DateTime.Utc | null | undefined) => value == null ? null : DateTime.toEpochMillis(value); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index f7e1db65850c6..5c0b45c563744 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -493,6 +493,7 @@ export interface ShellSnapshotOptions { readonly location?: "active" | "archive"; readonly projectId?: ProjectId; readonly unsettledOnly?: boolean; + readonly activityOnly?: boolean; /** * Only the threads sharing this thread's `lineage.rootThreadId`: the root, its forks, and their * subagent trees. The thread may be deleted: forks keep a deleted source's root. @@ -8440,12 +8441,21 @@ export const layer: Layer.Layer = )`; }; + const activityRuns = sql` + FROM orchestration_v2_projection_runs r + INDEXED BY orchestration_v2_projection_runs_thread_status_idx + WHERE r.thread_id = t.thread_id + AND r.status IN ('preparing', 'starting', 'running', 'waiting') + AND NOT ${isSilentShellRun("r")} + `; + const selectShellThreadRows = ( threadId?: ThreadId, { location, projectId, unsettledOnly = false, + activityOnly = false, familyOf, worktreePath, threadIds, @@ -8484,11 +8494,7 @@ export const layer: Layer.Layer = SELECT r.status -- Read active runs by status. Walking the ordinal index to skip this sort -- reads every run of a thread with none active. - FROM orchestration_v2_projection_runs r - INDEXED BY orchestration_v2_projection_runs_thread_status_idx - WHERE r.thread_id = t.thread_id - AND r.status IN ('preparing', 'starting', 'running', 'waiting') - AND NOT ${isSilentShellRun("r")} + ${activityRuns} ORDER BY r.ordinal DESC, r.run_id DESC LIMIT 1 ) AS activity_run_status, @@ -8499,11 +8505,7 @@ export const layer: Layer.Layer = json_extract(r.payload_json, '$.startedAt'), r.requested_at ) - FROM orchestration_v2_projection_runs r - INDEXED BY orchestration_v2_projection_runs_thread_status_idx - WHERE r.thread_id = t.thread_id - AND r.status IN ('preparing', 'starting', 'running', 'waiting') - AND NOT ${isSilentShellRun("r")} + ${activityRuns} ORDER BY r.ordinal DESC, r.run_id DESC LIMIT 1 ) AS activity_run_started_at, @@ -8651,7 +8653,7 @@ export const layer: Layer.Layer = unsettledOnly ? sql` AND json_extract(t.payload_json, '$.settledAt') IS NULL AND json_extract(t.payload_json, '$.settledOverride') IS NOT 'settled'` : sql`` - }${ + }${activityOnly ? sql` AND EXISTS (SELECT 1 ${activityRuns})` : sql``}${ familyOf === undefined ? sql`` : sql` AND CASE WHEN json_valid(t.payload_json) diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 45b5e9effa8cf..818356f7f25f0 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -462,7 +462,7 @@ export interface ThreadManagementServiceShape { readonly getShellSnapshot: ( options?: Pick< ShellSnapshotOptions, - "location" | "projectId" | "unsettledOnly" | "worktreePath" | "threadIds" + "location" | "projectId" | "unsettledOnly" | "activityOnly" | "worktreePath" | "threadIds" >, ) => Effect.Effect; readonly listActiveSubagentThreadIds: Orchestrator.OrchestratorV2["Service"]["listActiveSubagentThreadIds"]; diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index c8f5b9c715767..2eabe65cd87f4 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -118,6 +118,18 @@ vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (i // Null runs the real compression; a test sets it to hold an image in preparation. const compression = vi.hoisted(() => ({ gate: null as Promise | null })); + +function holdImageCompression() { + const gate = Promise.withResolvers(); + compression.gate = gate.promise; + return { + release: () => gate.resolve(), + [Symbol.dispose]: () => { + compression.gate = null; + gate.resolve(); + }, + }; +} vi.mock(import("~/lib/imageCompression"), async (original) => { const actual = await original(); return { @@ -489,9 +501,7 @@ it.each(["new", "existing"] as const)( // AppRoot brings its own router. router: false, }); - const compressed = Promise.withResolvers(); - compression.gate = compressed.promise; - using _compression = { [Symbol.dispose]: () => (compression.gate = null) }; + using compressed = holdImageCompression(); using _uploads = acceptAttachmentUploads(); const editor = page.getByTestId("composer-editor"); await expect.element(editor).toBeVisible(); @@ -530,7 +540,7 @@ it.each(["new", "existing"] as const)( await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` }); await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible(); - compressed.resolve(); + compressed.release(); await vi.waitFor(() => { if (kind === "new") { expect(launch.calls).toHaveLength(1); diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.browser.test.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.browser.test.tsx index 7d66a8526d56e..df0ea6ad3382a 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.browser.test.tsx @@ -106,6 +106,13 @@ it.each(["resume", "draft", "question"] as const)( }, ); +it("keeps Stop available when a preparing image holds the next send", async () => { + const props = setup(); + await using screen = await render(); + await screen.getByRole("button", { name: "Stop generation" }).click(); + expect(props.onInterrupt).toHaveBeenCalledTimes(1); +}); + it("allows retry after ten seconds and protects a late stop", async () => { const props = setup(); await using screen = await render(); diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 20a2166676fc9..c85224e320948 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -299,7 +299,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ const withStopButton = (action: ReactNode) => ( <> {action} - {stopPhase === "pending" || stopPhase === "timedOut" + {(isSendHeld && canInterrupt) || stopPhase === "pending" || stopPhase === "timedOut" ? renderStopGenerationButton(false) : null} diff --git a/apps/web/src/markdown/wordsHast.test.ts b/apps/web/src/markdown/wordsHast.test.ts index 478071201602d..f9fe4780f75ad 100644 --- a/apps/web/src/markdown/wordsHast.test.ts +++ b/apps/web/src/markdown/wordsHast.test.ts @@ -234,6 +234,11 @@ describe("wordsHast", () => { ).toBe( '
      \n
    • x\n
      ★ Insight ─────\n
      \n
    • \n
    \n
    \n★ Insight ─────\n
    \n
    \n

    q\n★ Insight ─────

    \n
    ', ); + const cr = "★ Insight ───\rFirst\rSecond\r───\r\rAfter"; + expect(wordsHtml(cr, { insights: true })).toContain('data-alert="insight"'); + expect(wordsHtml("\n\nAfter", { insights: true }).trim()).toBe( + '

    After

    ', + ); // What follows an opening keeps its offsets in the message, which components slice. const insight = "★ Insight ─────\nSee [a](./a.ts)\n```sh\nls\n```\n─────"; const tree = wordsHast(insight, { ...ASSISTANT, insights: true }); @@ -372,6 +377,8 @@ describe("wordsHast", () => { }); it("reads raw HTML attributes as an HTML parser does", () => { + expect(wordsHtml('Guide')).toContain('href="/guide"'); + expect(wordsHtml("hello\n\n)|]*>|<\?[\s\S]*?\?>/g; + /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>||$))|]*>|<\?[\s\S]*?\?>/g; const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; // Start tags an HTML parser closes an open `

    ` for, and the elements that scope that search. @@ -107,6 +107,7 @@ function properties(source: string | undefined, inSvg: boolean): Element["proper for (const match of source.matchAll(ATTRIBUTE)) { const name = match[1]!; const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase()); + if (Object.hasOwn(result, info.property)) continue; const raw = match[2] ?? match[3] ?? match[4]; if (raw === undefined) { result[info.property] = info.boolean || info.overloadedBoolean ? true : ""; @@ -913,16 +914,16 @@ function insightSource(text: string, options: RenderOptions): InsightSource | nu }; findCode(parse(text, options)); const nonce = Math.random().toString(36).slice(2); - const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`); + const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r\n?|\n)?`); const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g"); - const lines = text.split(/(?<=\n)/u); + const lines = text.split(/(?<=\n)|(?<=\r)(?!\n)/u); const skipped = new Set(); for (;;) { // Each line's offset in the message and in the source, and how much longer it got. const offsets: Array<{ original: number; source: number; length: number; delta: number }> = []; let original = 0; let rewritten = 0; - let opened = 0; + const unmatchedOpenings = new Set(); let indent: string | undefined; const source = lines .map((line, lineIndex) => { @@ -934,7 +935,7 @@ function insightSource(text: string, options: RenderOptions): InsightSource | nu const opening = inCode ? null : ASSISTANT_INSIGHT_OPENING.exec(value); if (opening && !skipped.has(lineIndex)) { indent = opening[1] ?? ""; - opened++; + unmatchedOpenings.add(lineIndex); output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`; } } else { @@ -955,14 +956,17 @@ function insightSource(text: string, options: RenderOptions): InsightSource | nu return output; }) .join(""); - if (opened === 0) return null; + if (unmatchedOpenings.size === 0) return null; const tree = parse(source, options); let stranded = false; const visit = (node: Root | Element, quoteStart: Text | undefined) => { for (const child of node.children) { if (child.type === "text") { for (const found of child.value.matchAll(anywhere)) { - if (child === quoteStart && found.index === 0) continue; + if (child === quoteStart && found.index === 0) { + unmatchedOpenings.delete(Number(found[1])); + continue; + } skipped.add(Number(found[1])); stranded = true; } @@ -975,7 +979,8 @@ function insightSource(text: string, options: RenderOptions): InsightSource | nu } }; visit(tree, undefined); - if (stranded) continue; + for (const line of unmatchedOpenings) skipped.add(line); + if (stranded || unmatchedOpenings.size > 0) continue; return { source, tree, @@ -1267,7 +1272,7 @@ export function markdownTree( /** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */ export function markdownMathRanges(text: string): Array<{ start: number; end: number }> { - if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; + if (!/\$[\s\S]*\$|\\[([]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; const ranges: Array<{ start: number; end: number }> = []; const visit = (node: Root | Element) => { for (const child of node.children) { @@ -1328,10 +1333,12 @@ export function markdownReferenceDefinitions(markdown: string): string[] { if (child.type !== "element") continue; const label = lookups.get(child.position?.start.offset ?? -1); if (child.tagName === "a" && label !== undefined) { - const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent); + const href = String(child.properties.href ?? "") + .replaceAll("&", "&") + .replace(/[<>\\\n]/g, encodeURIComponent); const title = child.properties.title; definitions.push( - `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, + `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replaceAll("&", "&").replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, ); } else visit(child); } diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 32f5f83117a05..9a8dff4b2310d 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -2,7 +2,7 @@ Use a new thread for a separate task. Choose **New worktree** when its code changes need a separate branch and working directory. Threads in the same checkout share its -branch, so T3 Code refuses a branch switch there while one of them is working. +branch. The branch controls refuse to switch it while one of those threads is working. ## Start a thread diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 89842adfd314e..4a4187d289d2d 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -756,13 +756,14 @@ describe("CursorAdapterV2", () => { ), ); - it.effect("marks failed turns as promptDropped only when Cursor did not checkpoint the run", () => + it.effect("marks uncheckpointed failed or interrupted turns as promptDropped", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-dropped-", }); const checkpointedRuns = new Set(); + const stopped = yield* Deferred.make(); let sendCalls = 0; const instanceId = ProviderInstanceId.make("cursor"); const threadId = ThreadId.make("cursor-dropped-thread"); @@ -799,15 +800,23 @@ describe("CursorAdapterV2", () => { return { agentId: "native-cursor-dropped", runId, - cancel: Effect.void, - wait: Effect.succeed({ - id: runId, - status: "error" as const, - error: { - message: - 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', - }, - }), + cancel: + runId === "native-cursor-run-4" + ? Deferred.succeed(stopped, undefined) + : Effect.void, + wait: + runId === "native-cursor-run-4" + ? Deferred.await(stopped).pipe( + Effect.as({ id: runId, status: "cancelled" as const }), + ) + : Effect.succeed({ + id: runId, + status: "error" as const, + error: { + message: + 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', + }, + }), }; }), }), @@ -850,7 +859,7 @@ describe("CursorAdapterV2", () => { lastVisitedAt: null, deletedAt: null, }; - const runFailed = (ordinal: number) => + const runTurn = (ordinal: number, interrupt = false) => Effect.gen(function* () { yield* runtime.startTurn({ threadId, @@ -871,6 +880,19 @@ describe("CursorAdapterV2", () => { attachments: [], }, }); + if (interrupt) { + const started = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter((event) => event.type === "provider_turn.updated"), + Stream.runHead, + ), + ); + assert(started.type === "provider_turn.updated"); + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: started.providerTurn.id, + }); + } const events = yield* runtime.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, @@ -887,22 +909,27 @@ describe("CursorAdapterV2", () => { }); // Uncheckpointed failure: Cursor never persisted the prompt. - const uncheckpointed = yield* runFailed(1); + const uncheckpointed = yield* runTurn(1); assert.equal(uncheckpointed.terminal?.status, "failed"); assert.equal(uncheckpointed.terminal?.promptDropped, true); assert.equal(uncheckpointed.turn?.promptDropped, true); // Checkpointed failure: Cursor kept the run's prompt in its store. checkpointedRuns.add("native-cursor-run-2"); - const checkpointed = yield* runFailed(2); + const checkpointed = yield* runTurn(2); assert.equal(checkpointed.terminal?.status, "failed"); assert.isUndefined(checkpointed.terminal?.promptDropped); assert.isUndefined(checkpointed.turn?.promptDropped); - const unknown = yield* runFailed(3); + const unknown = yield* runTurn(3); assert.equal(unknown.terminal?.status, "failed"); assert.isUndefined(unknown.terminal?.promptDropped); assert.isUndefined(unknown.turn?.promptDropped); + + const interrupted = yield* runTurn(4, true); + assert.equal(interrupted.terminal?.status, "interrupted"); + assert.equal(interrupted.terminal?.promptDropped, true); + assert.equal(interrupted.turn?.promptDropped, true); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index d560d74d819c1..48f180b60a202 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2594,7 +2594,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ); // Cursor only keeps a run in conversation history once it saves its first checkpoint. const promptDropped = - (input.status === "failed" || input.status === "cancelled") && + input.status !== "completed" && !input.context.compacted && input.context.prompt !== undefined && (yield* ( diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 7b4384cf47478..a3b40e0d82969 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -23,6 +23,7 @@ const PULL = { body: null, base: "main", headRepo: "bob/web", + visibility: undefined as "public" | "private" | undefined, headSha: "c".repeat(40), baseSha: "b".repeat(40), mergeCommitSha: null, @@ -166,7 +167,11 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { // Source publishes no `refs/pull//head` for a private pull request, on either repository. it.effect("takes a private pull request's branch from the companion repository", () => { - const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const pull = { + head: "acme:fix-thing", + headRepo: "acme/web.private-2", + visibility: "private" as const, + }; const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); return Effect.gen(function* () { @@ -176,7 +181,7 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); assert.deepStrictEqual(git, [ `remote source ${REMOTE}`, - "remote acme https://source.tanstack.com/@acme/web.private.git", + "remote acme https://source.tanstack.com/@acme/web.private-2.git", "create fix-thing", "switch fix-thing", "upstream fix-thing acme/fix-thing", @@ -184,6 +189,20 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { }); }); + it.effect("uses the normal pull ref when a numbered companion-like head is public", () => + Effect.gen(function* () { + const { run, git, config } = checkout({ + recordedOwner: null, + isAncestor: true, + pull: { head: "acme:fix-thing", headRepo: "acme/web.private-2", visibility: "public" }, + branches: ["main"], + }); + yield* run; + assert.include(git, "fetch --no-tags origin +refs/pull/42/head:refs/remotes/origin/pull/42"); + assert.isFalse(config.has("branch.fix-thing.pushRemote")); + }), + ); + it.effect("only fast-forwards an existing private branch", () => Effect.gen(function* () { const input = { diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index dd9208231da78..39d639de5f699 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -302,7 +302,10 @@ export const make = Effect.gen(function* () { return yield* error(operation, input.cwd, "No TanStack Source repository remote was found."); }); - const toChangeRequest = (target: Target, pull: Json.SourcePullDetail): ChangeRequest => { + const toChangeRequest = ( + target: Target, + pull: Json.SourcePullDetail, + ): ChangeRequest & { readonly visibility: string | undefined } => { const headRepository = pull.headRepo ?? target.repository; const headBranch = Json.headBranchName(pull.head); // A pull request synced from a GitHub fork names its head only by its pull ref. @@ -323,6 +326,7 @@ export const make = Effect.gen(function* () { mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt), updatedAt: Option.some(DateTime.makeUnsafe(updatedAt)), isCrossRepository: crossRepository, + visibility: pull.visibility, headRepositoryNameWithOwner: headRepository, headRepositoryOwnerLogin: headRepository.split("/")[0] ?? null, }; @@ -533,11 +537,17 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); + const companionName = pull.headRepositoryNameWithOwner; + const companionPrefix = + pullRepository === null ? null : pullRepository.toLowerCase() + ".private"; + const normalizedHead = companionName?.toLowerCase(); const companion = - pullRepository !== null && - pull.headRepositoryNameWithOwner?.toLowerCase() === - `${pullRepository}.private`.toLowerCase() - ? pull.headRepositoryNameWithOwner + pull.visibility !== "public" && + typeof companionName === "string" && + companionPrefix !== null && + normalizedHead?.startsWith(companionPrefix) && + /^(?:-[2-9]|-[1-9]\d+)?$/.test(normalizedHead.slice(companionPrefix.length)) + ? companionName : null; if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; From f923633f1cdd53798ed908d9c360b0c87d1b8244 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:53:44 -0300 Subject: [PATCH 68/87] fix(web): reconcile unsaved history and guard detached sends --- .../src/browserHistoryStore.browser.test.ts | 204 +++++++++++++----- apps/web/src/browserHistoryStore.test.ts | 4 +- apps/web/src/browserHistoryStore.ts | 175 ++++++++++----- .../useMultipleModelSend.browser.test.tsx | 124 +++++++++++ .../components/chat/useMultipleModelSend.ts | 6 +- 5 files changed, 408 insertions(+), 105 deletions(-) create mode 100644 apps/web/src/components/chat/useMultipleModelSend.browser.test.tsx diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index d604404808dfd..49f30bcd31a3a 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -200,10 +200,10 @@ function deleteHistoryDatabase() { } async function resetHistoryFixture() { + await resetBrowserHistoryForTests(); localStorage.removeItem(storageKey); for (const key of fallbackKeys()) localStorage.removeItem(key); await deleteHistoryDatabase(); - resetBrowserHistoryForTests(); } it("moves the legacy snapshot into the shared database", async () => { @@ -342,57 +342,69 @@ it("keeps visits saved while IndexedDB could not open", async () => { } }); -it("keeps a fallback deletion after IndexedDB recovers and an older tab writes", async () => { - await resetHistoryFixture(); - try { - using fixture = new DisposableStack(); - const db = await openHistoryFixture(fixture); - const store = useBrowserHistoryStore.getState(); - store.recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); - store.recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); - await vi.waitFor(() => - expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ - a: [oldEntry], - b: [otherEntry], - }), - ); +it.each(["IndexedDB", "localStorage"])( + "keeps a deletion saved to %s after an older tab writes", + async (backend) => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + const store = useBrowserHistoryStore.getState(); + store.recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + store.recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ + a: [oldEntry], + b: [otherEntry], + }), + ); - { - using _transaction = vi.spyOn(IDBDatabase.prototype, "transaction").mockImplementation(() => { - throw new DOMException("Storage unavailable", "SecurityError"); - }); - store.removeUrl("a", oldEntry.url); - await vi.waitFor(() => expect(fallbackKeys()).toHaveLength(1)); - expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ b: [otherEntry] }); - } + { + using transaction = + backend === "localStorage" + ? vi.spyOn(IDBDatabase.prototype, "transaction").mockImplementation(() => { + throw new DOMException("Storage unavailable", "SecurityError"); + }) + : undefined; + store.removeUrl("a", oldEntry.url); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ b: [otherEntry] }), + ); + if (transaction) expect(fallbackKeys()).toHaveLength(1); + } - const recovered = await openHistoryDocument(fixture); - await vi.waitFor(() => expect(fallbackKeys()).toEqual([])); - expect(recovered.getState().byProjectKey).toEqual({ b: [otherEntry] }); - const saved = await readHistoryFixture(db); - expect(saved).toHaveProperty("byProjectKey", { b: [otherEntry] }); - expect(JSON.stringify(saved)).not.toContain(oldEntry.url); + const recovered = await openHistoryDocument(fixture); + await vi.waitFor(() => { + expect(fallbackKeys()).toEqual([]); + expect(recovered.getState().byProjectKey).toEqual({ b: [otherEntry] }); + }); + const saved = await readHistoryFixture(db); + expect(saved).toHaveProperty("byProjectKey", { b: [otherEntry] }); + expect(JSON.stringify(saved)).not.toContain(oldEntry.url); - localStorage.setItem( - storageKey, - JSON.stringify({ state: { byProjectKey: { a: [oldEntry] } }, version: 1 }), - ); - const reloaded = await openHistoryDocument(fixture); - await vi.waitFor(() => expect(localStorage.getItem(storageKey)).toBeNull()); - expect(reloaded.getState().byProjectKey).toEqual({ b: [otherEntry] }); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [oldEntry] } }, version: 1 }), + ); + const reloaded = await openHistoryDocument(fixture); + await vi.waitFor(() => { + expect(localStorage.getItem(storageKey)).toBeNull(); + expect(reloaded.getState().byProjectKey).toEqual({ b: [otherEntry] }); + }); - const revisit = { ...oldEntry, lastVisitedAt: page.lastVisitedAt }; - reloaded.getState().recordVisit("a", revisit.url, revisit.lastVisitedAt); - await vi.waitFor(async () => - expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey", { - a: [revisit], - b: [otherEntry], - }), - ); - } finally { - await resetHistoryFixture(); - } -}); + const revisit = { ...oldEntry, lastVisitedAt: page.lastVisitedAt }; + reloaded.getState().recordVisit("a", revisit.url, revisit.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey", { + a: [revisit], + b: [otherEntry], + }), + ); + } finally { + await resetHistoryFixture(); + } + }, +); it.each(["localStorage", "IndexedDB"] as const)( "keeps unsaved changes when %s recovers", @@ -414,7 +426,8 @@ it.each(["localStorage", "IndexedDB"] as const)( using _write = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new DOMException("Storage unavailable", "QuotaExceededError"); }); - store.recordVisit("a", otherEntry.url, otherEntry.lastVisitedAt); + for (const at of [0, 1, otherEntry.lastVisitedAt]) + store.recordVisit("a", otherEntry.url, at); await vi.waitFor(() => expect(useBrowserHistoryStore.getState().byProjectKey.a).toEqual([otherEntry, oldEntry]), ); @@ -453,3 +466,96 @@ it.each(["localStorage", "IndexedDB"] as const)( } }, ); + +it.each([ + { + name: "imports a fallback title for the same untitled IndexedDB visit", + indexedTitle: undefined, + }, + { + name: "keeps a concurrent IndexedDB title ahead of a fallback title", + indexedTitle: "Concurrent title", + }, +])("$name", async ({ indexedTitle }) => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + const store = useBrowserHistoryStore.getState(); + store.recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey.a", [oldEntry]), + ); + { + using _transaction = vi.spyOn(IDBDatabase.prototype, "transaction").mockImplementation(() => { + throw new DOMException("Storage unavailable", "SecurityError"); + }); + store.setTitleForUrl("a", oldEntry.url, "Recovered title"); + await vi.waitFor(() => expect(fallbackKeys()).toHaveLength(1)); + } + if (indexedTitle) + await writeHistoryFixture(db, { + byProjectKey: { a: [{ ...oldEntry, title: indexedTitle }] }, + projectKeyByThreadKey: {}, + }); + const expected = [{ ...oldEntry, title: indexedTitle ?? "Recovered title" }]; + const recovered = await openHistoryDocument(fixture); + await vi.waitFor(() => expect(recovered.getState().byProjectKey.a).toEqual(expected)); + expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey.a", expected); + } finally { + await resetHistoryFixture(); + } +}); + +it.each(["empty", "revisited"] as const)( + "recovers unsaved history when IndexedDB reopens %s", + async (status) => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + const store = useBrowserHistoryStore.getState(); + store.recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey.a", [oldEntry]), + ); + const revisit = { ...oldEntry, lastVisitedAt: 10 }; + { + using _transaction = vi + .spyOn(IDBDatabase.prototype, "transaction") + .mockImplementation(() => { + throw new DOMException("Storage unavailable", "SecurityError"); + }); + using _write = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw new DOMException("Storage unavailable", "QuotaExceededError"); + }); + if (status === "empty") { + store.setTitleForUrl("a", oldEntry.url, "Only in memory"); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey.a).toEqual([ + { ...oldEntry, title: "Only in memory" }, + ]), + ); + } else { + store.removeUrl("a", oldEntry.url); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey.a).toBeUndefined(), + ); + } + } + await writeHistoryFixture(db, { + byProjectKey: status === "empty" ? {} : { a: [revisit] }, + projectKeyByThreadKey: {}, + }); + store.recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey", { + a: status === "empty" ? [{ ...oldEntry, title: "Only in memory" }] : [revisit], + b: [otherEntry], + }), + ); + } finally { + await resetHistoryFixture(); + } + }, +); diff --git a/apps/web/src/browserHistoryStore.test.ts b/apps/web/src/browserHistoryStore.test.ts index bc0aa9a29d250..04940c35877aa 100644 --- a/apps/web/src/browserHistoryStore.test.ts +++ b/apps/web/src/browserHistoryStore.test.ts @@ -179,8 +179,8 @@ function settle( applyPreviewServerSnapshot(ref, snapshot); } -function resetStores(): () => void { - resetBrowserHistoryForTests(); +async function resetStores(): Promise<() => void> { + await resetBrowserHistoryForTests(); resetPreviewStateForTests(); return startPreviewTitleRecording(); } diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index 27ff4c159f5a0..84ddecf6b7a4b 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -150,7 +150,6 @@ export function migratePersistedBrowserHistoryState( const byProjectKey: Record = {}; for (const [projectKey, value] of Object.entries(raw as Record)) { if (!Array.isArray(value)) continue; - const seenUrls = new Set(); const entries = value .flatMap((candidate) => { if (!candidate || typeof candidate !== "object") return []; @@ -175,15 +174,20 @@ export function migratePersistedBrowserHistoryState( }, ]; }) - .toSorted((a, b) => b.lastVisitedAt - a.lastVisitedAt) - .filter((entry) => { - const key = visitLookupKey(entry.url); - if (seenUrls.has(key)) return false; - seenUrls.add(key); - return true; - }) - .slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT); - if (entries.length > 0) byProjectKey[projectKey] = entries; + .toSorted((a, b) => b.lastVisitedAt - a.lastVisitedAt); + const latest = new Map(); + for (const entry of entries) { + const key = visitLookupKey(entry.url); + const current = latest.get(key); + if (!current) latest.set(key, entry); + else if (current.lastVisitedAt === entry.lastVisitedAt && !current.title && entry.title) + latest.set(key, { ...current, title: entry.title }); + } + if (latest.size > 0) + byProjectKey[projectKey] = [...latest.values()].slice( + 0, + BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT, + ); } return { byProjectKey: evictExcessProjects(byProjectKey) }; } @@ -238,10 +242,13 @@ type PersistedBrowserHistory = Pick< "byProjectKey" | "projectKeyByThreadKey" > & { readonly fallbackRemovals?: Readonly> }; -type UpdateHistory = ( - state: PersistedBrowserHistory, - fallback?: boolean, -) => PersistedBrowserHistory; +type UpdateHistory = (state: PersistedBrowserHistory) => PersistedBrowserHistory; +type UpdateStoredHistory = (state: PersistedBrowserHistory | undefined) => PersistedBrowserHistory; + +interface UnsavedHistory { + readonly base: PersistedBrowserHistory; + readonly history: PersistedBrowserHistory; +} function historyRemovalKey(projectKey: string, url: string): string { // Keep the removal without retaining the deleted URL. @@ -287,8 +294,7 @@ const EMPTY_PERSISTED_HISTORY: PersistedBrowserHistory = { let historyDatabase: Promise | undefined; let historyChannel: BroadcastChannel | undefined; let historySync = Promise.resolve(); -let unsavedHistoryUpdates: UpdateHistory[] = []; -let unsavedHistoryBase: PersistedBrowserHistory | undefined; +let unsavedHistory: UnsavedHistory | undefined; interface HistorySnapshot { readonly key: string; @@ -348,7 +354,10 @@ function mergeHistorySnapshots( ): PersistedBrowserHistory | undefined { if (snapshots.length === 0) return saved; const histories = snapshots.map(({ history }) => history); - if (saved) histories.unshift(saved); + return mergeHistories(saved ? [saved, ...histories] : histories); +} + +function mergeHistories(histories: readonly PersistedBrowserHistory[]): PersistedBrowserHistory { const byProjectKey: Record = Object.create(null); const fallbackRemovals: Record = {}; for (const history of histories) { @@ -370,21 +379,82 @@ function mergeHistorySnapshots( }; } +function rebaseUnsavedHistory( + saved: PersistedBrowserHistory | undefined, + pending: UnsavedHistory, +): PersistedBrowserHistory { + if ( + !saved || + saved === pending.base || + (Object.keys(saved.byProjectKey).length === 0 && + Object.keys(saved.projectKeyByThreadKey).length === 0 && + Object.keys(saved.fallbackRemovals ?? {}).length === 0) + ) + return pending.history; + + const byProjectKey = { ...saved.byProjectKey }; + const byVisitKey = (visits: readonly BrowserHistoryEntry[] | undefined) => + new Map(visits?.map((entry) => [visitLookupKey(entry.url), entry] as const)); + for (const [projectKey, entries] of Object.entries(pending.history.byProjectKey)) { + const baseEntries = pending.base.byProjectKey[projectKey]; + if (entries === baseEntries) continue; + const base = byVisitKey(baseEntries); + const current = byVisitKey(saved.byProjectKey[projectKey]); + for (const entry of entries) { + const key = visitLookupKey(entry.url); + const before = base.get(key); + if ( + before?.lastVisitedAt === entry.lastVisitedAt && + before.url === entry.url && + before.title === entry.title + ) + continue; + const durable = current.get(key); + if (!durable || entry.lastVisitedAt > durable.lastVisitedAt) { + current.set(key, entry); + } else if ( + entry.lastVisitedAt === durable.lastVisitedAt && + entry.title && + entry.title !== before?.title && + (durable.title === before?.title || durable.title === undefined) + ) { + current.set(key, { ...durable, title: entry.title }); + } + } + byProjectKey[projectKey] = [...current.values()]; + } + const updatedThreadMappings = Object.entries(pending.history.projectKeyByThreadKey).filter( + ([threadKey, projectKey]) => pending.base.projectKeyByThreadKey[threadKey] !== projectKey, + ); + return mergeHistories([ + { + ...saved, + byProjectKey, + projectKeyByThreadKey: Object.fromEntries( + [ + ...new Map([...Object.entries(saved.projectKeyByThreadKey), ...updatedThreadMappings]), + ].slice(-MAX_PERSISTED_THREAD_MAPPINGS), + ), + }, + { ...EMPTY_PERSISTED_HISTORY, fallbackRemovals: pending.history.fallbackRemovals ?? {} }, + ]); +} + // Without IndexedDB, merge into the freshest localStorage snapshot so a reload keeps new visits. -function transactLegacyHistory(update: UpdateHistory, current: PersistedBrowserHistory) { +function transactLegacyHistory(update: UpdateStoredHistory, current: PersistedBrowserHistory) { const snapshots = readHistorySnapshots(); - const previous = mergeHistorySnapshots(undefined, snapshots) ?? current; - const history = update(previous, true); - if (history === previous) return { history, unsavedBase: undefined }; + const base = mergeHistorySnapshots(undefined, snapshots) ?? current; + const history = update(base); + if (history === base) return { history, pending: undefined }; try { window.localStorage.setItem( `${BROWSER_HISTORY_FALLBACK_PREFIX}${randomUUID()}`, JSON.stringify({ state: history, version: 1 }), ); retireHistorySnapshots(snapshots); - return { history, unsavedBase: undefined }; + return { history, pending: undefined }; } catch { - return { history, unsavedBase: previous }; + return { history, pending: { base, history } }; } } @@ -413,7 +483,7 @@ function openHistoryDatabase() { return opening; } -async function transactIndexedHistory(update?: UpdateHistory, retry = true) { +async function transactIndexedHistory(update?: UpdateStoredHistory, retry = true) { const opening = openHistoryDatabase(); const db = await opening; let transaction: IDBTransaction; @@ -436,8 +506,8 @@ async function transactIndexedHistory(update?: UpdateHistory, retry = true) { request.onsuccess = () => { const saved = request.result as PersistedBrowserHistory | undefined; if (update) snapshots = readHistorySnapshots(); - const previous = mergeHistorySnapshots(saved, snapshots) ?? EMPTY_PERSISTED_HISTORY; - history = update?.(previous) ?? previous; + const previous = mergeHistorySnapshots(saved, snapshots); + history = update?.(previous) ?? previous ?? EMPTY_PERSISTED_HISTORY; changed = history !== saved; if (update && changed) store.put(history, BROWSER_HISTORY_STORAGE_KEY); }; @@ -460,16 +530,16 @@ export const useBrowserHistoryStore = create()((set, g return; } historySync = historySync.then(async () => { - unsavedHistoryUpdates.push(update); - const replay: UpdateHistory = (base, fallback) => - unsavedHistoryUpdates.reduce((state, apply) => { - const next = apply(state, fallback); - return next === state ? state : boundThreadMappings(state, next); - }, base); - const saved = await transactIndexedHistory(replay).catch(() => null); + const persist: UpdateStoredHistory = (saved) => { + const base = unsavedHistory + ? rebaseUnsavedHistory(saved, unsavedHistory) + : (saved ?? EMPTY_PERSISTED_HISTORY); + const next = update(base); + return next === base ? base : boundThreadMappings(base, next); + }; + const saved = await transactIndexedHistory(persist).catch(() => null); if (saved) { - unsavedHistoryUpdates = []; - unsavedHistoryBase = undefined; + unsavedHistory = undefined; publish(saved.history); // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel is scoped to the origin if (saved.changed) historyChannel?.postMessage(null); @@ -477,11 +547,10 @@ export const useBrowserHistoryStore = create()((set, g } const { byProjectKey, projectKeyByThreadKey } = get(); const fallback = transactLegacyHistory( - replay, - unsavedHistoryBase ?? { byProjectKey, projectKeyByThreadKey }, + persist, + unsavedHistory?.base ?? { byProjectKey, projectKeyByThreadKey }, ); - unsavedHistoryBase = fallback.unsavedBase; - if (!unsavedHistoryBase) unsavedHistoryUpdates = []; + unsavedHistory = fallback.pending; publish(fallback.history); }); }; @@ -543,23 +612,23 @@ export const useBrowserHistoryStore = create()((set, g removeUrl: (projectKey, url) => { const normalized = normalizeHistoryUrl(url); if (!normalized) return; - const observed = get().byProjectKey[projectKey]?.find((entry) => entry.url === normalized); - updateHistory((state, fallback) => { + const visitKey = visitLookupKey(normalized); + const observed = get().byProjectKey[projectKey]?.find( + (entry) => visitLookupKey(entry.url) === visitKey, + ); + updateHistory((state) => { const entries = state.byProjectKey[projectKey] ?? []; - const index = entries.findIndex((entry) => entry.url === normalized); + const index = entries.findIndex((entry) => visitLookupKey(entry.url) === visitKey); + const entry = entries[index]; + const removedThrough = observed?.lastVisitedAt ?? entry?.lastVisitedAt; + if (removedThrough === undefined) return state; let next = state; - if (index !== -1) { + if (entry && entry.lastVisitedAt <= removedThrough) { const byProjectKey = { ...state.byProjectKey }; if (entries.length === 1) delete byProjectKey[projectKey]; else byProjectKey[projectKey] = entries.toSpliced(index, 1); next = { ...state, byProjectKey }; } - if (!fallback) return next; - const removedThrough = Math.max( - entries[index]?.lastVisitedAt ?? -Infinity, - observed?.lastVisitedAt ?? -Infinity, - ); - if (removedThrough === -Infinity) return next; const key = historyRemovalKey(projectKey, normalized); if (removedThrough <= (state.fallbackRemovals?.[key] ?? -Infinity)) return next; return { ...next, fallbackRemovals: { ...state.fallbackRemovals, [key]: removedThrough } }; @@ -606,7 +675,7 @@ if (typeof window !== "undefined") { if (historyChannel) { historyChannel.onmessage = () => { historySync = historySync.then(async () => { - if (unsavedHistoryUpdates.length > 0) return; + if (unsavedHistory) return; const saved = await transactIndexedHistory().catch(() => null); if (saved) useBrowserHistoryStore.setState({ byProjectKey: saved.history.byProjectKey }); }); @@ -621,7 +690,7 @@ if (typeof window !== "undefined") { }, })); }; - historySync = transactIndexedHistory((history) => history).then( + historySync = transactIndexedHistory((history) => history ?? EMPTY_PERSISTED_HISTORY).then( ({ history }) => hydrate(history), () => hydrate(mergeHistorySnapshots(undefined, readHistorySnapshots()) ?? EMPTY_PERSISTED_HISTORY), @@ -861,7 +930,9 @@ export function useThreadRecentHistory( ); } -export function resetBrowserHistoryForTests(): void { +export async function resetBrowserHistoryForTests(): Promise { + await historySync; + unsavedHistory = undefined; useBrowserHistoryStore.setState({ byProjectKey: {}, projectKeyByThreadKey: {}, diff --git a/apps/web/src/components/chat/useMultipleModelSend.browser.test.tsx b/apps/web/src/components/chat/useMultipleModelSend.browser.test.tsx new file mode 100644 index 0000000000000..2434d4f503dec --- /dev/null +++ b/apps/web/src/components/chat/useMultipleModelSend.browser.test.tsx @@ -0,0 +1,124 @@ +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { snapshotComposerSend } from "../ChatView.logic"; +import { useLocalDispatchState } from "./useLocalDispatchState"; +import { useMultipleModelSend } from "./useMultipleModelSend"; + +vi.mock("../../state/use-orchestration-command", () => ({ + useOrchestrationCommand: () => async () => ({ _tag: "Success", value: undefined }), +})); + +it.each(["starts", "fails preparation"] as const)( + "leaves the current thread's dispatch busy when a detached fanout %s", + async (outcome) => { + const environmentId = EnvironmentId.make("fanout"); + const threadId = ThreadId.make("fanout-" + outcome); + const target = scopeThreadRef(environmentId, threadId); + const routeThreadKey = scopedThreadKey(target); + const activeRoute = { current: routeThreadKey }; + const attachments = Promise.withResolvers<[]>(); + let submission: Promise | undefined; + const createdAt = "2026-11-01T00:00:00.000Z"; + + function Probe() { + const dispatch = useLocalDispatchState({ + environmentId, + activeThread: undefined, + activeLatestRun: null, + latestUserMessageId: null, + phase: "ready", + activePendingApproval: null, + activePendingUserInput: null, + threadError: null, + }); + const send = useMultipleModelSend({ + environmentId, + routeThreadKey, + currentRouteThreadKeyRef: activeRoute, + draftId: null, + composerDraftTarget: target, + composerRef: { current: null }, + promptRef: { current: "" }, + runtimeMode: "full-access", + startFromOrigin: false, + worktreeRepositories: undefined, + resetLocalDispatch: dispatch.resetLocalDispatch, + setThreadError: () => {}, + }); + const start = () => { + dispatch.beginLocalDispatch({ preparingWorktree: true }); + const selections = ["one", "two"].map((model) => ({ + instanceId: ProviderInstanceId.make("codex"), + model, + })); + submission = send({ + threadId, + project: { + id: ProjectId.make("project"), + title: "Project", + environmentId, + workspaceRoot: "/project", + defaultModelSelection: null, + scripts: [], + createdAt, + updatedAt: createdAt, + }, + branch: "main", + selections, + targets: selections.map((selection) => ({ selection, text: "Send to both models" })), + sendSnapshot: snapshotComposerSend({ + prompt: "Send to both models", + images: [], + files: [], + terminalContexts: [], + sendableTerminalContexts: [], + previewAnnotations: [], + reviewComments: [], + threadContexts: [], + environmentContexts: [], + replyTo: null, + }), + createdAt, + attachmentsPromise: attachments.promise, + usesAttachmentUploads: true, + readFileBlockReason: () => null, + buildOutgoingMessageContext: () => undefined, + isCurrentSend: () => true, + draftChangedDuringPreparation: () => false, + }); + }; + return ( + <> + + + {dispatch.isSendBusy ? "Sending" : "Idle"} + + ); + } + + await using screen = await render(); + await screen.getByRole("button", { name: "Send to models" }).click(); + await screen.getByRole("button", { name: "Send from another thread" }).click(); + await expect.element(screen.getByRole("status")).toHaveTextContent("Sending"); + await act(async () => { + if (outcome === "starts") attachments.resolve([]); + else attachments.reject(new Error("Attachment unavailable")); + await submission; + }); + await expect.element(screen.getByRole("status")).toHaveTextContent("Sending"); + }, +); diff --git a/apps/web/src/components/chat/useMultipleModelSend.ts b/apps/web/src/components/chat/useMultipleModelSend.ts index cbfcac768656c..994ff8b1f1316 100644 --- a/apps/web/src/components/chat/useMultipleModelSend.ts +++ b/apps/web/src/components/chat/useMultipleModelSend.ts @@ -224,7 +224,8 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { }), ); sendInFlightRef.current = false; - resetLocalDispatch(); + if (currentRouteThreadKeyRef.current === routeThreadKey && isCurrentSend()) + resetLocalDispatch(); releasedComposer = true; await starts; if (startedCount > 0) { @@ -311,7 +312,8 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { } if (!releasedComposer) { sendInFlightRef.current = false; - resetLocalDispatch(); + if (currentRouteThreadKeyRef.current === routeThreadKey && isCurrentSend()) + resetLocalDispatch(); } }; } From cc886541d6961d2155b299d80e562ba0c1110b6b Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 20:53:55 -0300 Subject: [PATCH 69/87] fix(ci): run the required thread gate on integration pushes --- .github/workflows/fork-coderabbit-gate.yml | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/.github/workflows/fork-coderabbit-gate.yml b/.github/workflows/fork-coderabbit-gate.yml index 95fd0b706b790..5dc2cd4972b0b 100644 --- a/.github/workflows/fork-coderabbit-gate.yml +++ b/.github/workflows/fork-coderabbit-gate.yml @@ -1,5 +1,7 @@ name: Fork CodeRabbit gate on: + push: + branches: ["integration/fork-main-*"] pull_request: types: [opened, synchronize, reopened, ready_for_review, edited] pull_request_review: @@ -8,7 +10,7 @@ permissions: contents: read pull-requests: read concurrency: - group: fork-coderabbit-gate-${{ github.event.pull_request.number }} + group: fork-coderabbit-gate-${{ github.event.pull_request.head.repo.full_name || github.repository }}-${{ github.head_ref || github.ref_name }} cancel-in-progress: true jobs: threads: @@ -20,7 +22,18 @@ jobs: with: script: | const { owner, repo } = context.repo; - const number = context.payload.pull_request.number; + let number = context.payload.pull_request?.number; + if (number === undefined) { + const branch = context.ref.slice('refs/heads/'.length); + const pulls = await github.paginate(github.rest.pulls.list, { + owner, repo, head: owner + ':' + branch, base: 'main', state: 'open', + }); + number = pulls.find((pull) => pull.head.sha === context.sha)?.number; + if (number === undefined) { + core.setFailed('No open pull request to main matches this integration commit.'); + return; + } + } const open = []; let cursor = null; do { From d3797ff14756207f53c7dd4ac00398277ad4cae8 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 21:21:11 -0300 Subject: [PATCH 70/87] fix: preserve checkpoint ordering and legacy thread synchronization --- .../Adapters/CodexAdapterV2.test.ts | 44 ++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 29 +++++------ .../ProviderEventIngestor.test.ts | 39 ++++++++++++++- .../orchestration-v2/ProviderEventIngestor.ts | 23 ++++++--- .../src/workspace/WorkspaceEntries.test.ts | 45 +++++++++-------- .../pullRequest/pullRequestList.logic.test.ts | 11 ++++ .../pullRequest/pullRequestList.logic.ts | 7 ++- .../src/state/threads-atoms.test.ts | 50 +++++++++++++++++-- packages/client-runtime/src/state/threads.ts | 14 ++++-- 9 files changed, 213 insertions(+), 49 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index d30748a0df77c..3ba9cbd119d85 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1560,6 +1560,50 @@ describe("CodexAdapterV2 session initialize", () => { return Predicate.isTagged(error, "CodexAppServerUnresponsiveError"); }; + it.effect("gives config/read and thread/start their own deadlines", () => + Effect.gen(function* () { + const configReady = yield* Deferred.make(); + const releaseConfig = yield* Deferred.make(); + const startReady = yield* Deferred.make(); + const releaseStart = yield* Deferred.make(); + const hold = (ready: Deferred.Deferred, release: Deferred.Deferred) => + Deferred.succeed(ready, undefined).pipe(Effect.andThen(Deferred.await(release))); + const nativeThreadId = "separate-thread-deadlines"; + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: nativeThreadId, + entries: replayPreamble(nativeThreadId).slice(0, 5), + }), + (entry) => + entry.label === "config/read" + ? hold(configReady, releaseConfig) + : entry.label === "thread/start" + ? hold(startReady, releaseStart) + : Effect.void, + ); + const ensured = yield* session + .ensureThread(nativeThreadId) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(configReady); + yield* TestClock.adjust("70 seconds"); + yield* Deferred.succeed(releaseConfig, undefined); + yield* Deferred.await(startReady); + yield* TestClock.adjust("70 seconds"); + yield* Deferred.succeed(releaseStart, undefined); + assert.equal((yield* Fiber.join(ensured)).nativeThreadRef?.nativeId, nativeThreadId); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #24300 a wedged shared app-server left thread/start pending and stayed ready it.effect("fails and retires a shared app-server that never answers thread/start", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 181ed17fd5c16..01950ecdce26a 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8157,19 +8157,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ]), ), Effect.flatMap(([mcpSession, stdioMcpServers]) => - client.request("thread/start", { - ...codexThreadRuntimeParams({ - threadId: threadInput.threadId, - mcpSession, - stdioMcpServers, - modelSelection: threadInput.modelSelection, - runtimePolicy: threadInput.runtimePolicy, - }), - // Codex tags the child's MCP calls with thread_source "subagent". - ...(IdAllocator.isDelegatedTaskThread(threadInput.threadId) - ? { threadSource: "subagent" } - : {}), - }), + client + .request("thread/start", { + ...codexThreadRuntimeParams({ + threadId: threadInput.threadId, + mcpSession, + stdioMcpServers, + modelSelection: threadInput.modelSelection, + runtimePolicy: threadInput.runtimePolicy, + }), + // Codex tags the child's MCP calls with thread_source "subagent". + ...(IdAllocator.isDelegatedTaskThread(threadInput.threadId) + ? { threadSource: "subagent" } + : {}), + }) + .pipe(withAppServerDeadline("thread/start")), ), Effect.map((response): OrchestrationV2ProviderThread => providerThreadFromCodexThread({ @@ -8181,7 +8183,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( thread: response.thread, }), ), - withAppServerDeadline("thread/start"), Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterEnsureThreadError({ diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 67f7bf51554ff..36b40639539ed 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -669,7 +669,18 @@ layer("ProviderEventIngestorV2", (it) => { const now = yield* DateTime.now; const eventSink = yield* EventSink.EventSinkV2; const projectionStore = yield* ProjectionStore.ProjectionStoreV2; - const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2; + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const rewindRequestedLock = yield* Deferred.make(); + const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe( + Effect.provide(Layer.fresh(ProviderEventIngestor.layer)), + Effect.provideService(ThreadCommandExecutor.ThreadCommandExecutor, { + ...executor, + withLock: (key, effect) => + Deferred.succeed(rewindRequestedLock, undefined).pipe( + Effect.andThen(executor.withLock(key, effect)), + ), + }), + ); const idAllocator = yield* IdAllocator.IdAllocatorV2; const threadEvent = yield* threadCreatedEvent(now); const threadId = threadEvent.threadId; @@ -849,7 +860,7 @@ layer("ProviderEventIngestorV2", (it) => { nativeTurnId: null, }); - yield* ingestor.ingestNormalized({ + const rewind = ingestor.ingestNormalized({ providerSessionId, providerInstanceId: modelSelection.instanceId, threadId, @@ -886,6 +897,30 @@ layer("ProviderEventIngestorV2", (it) => { }, }); + const rewindFiber = yield* executor.withLock( + threadId, + Effect.gen(function* () { + const current = yield* projectionStore.getThreadProjection(threadId); + const captured = current.runs.find((run) => run.id === unlocatedRun)!; + const fiber = yield* rewind.pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.raceFirst(Deferred.await(rewindRequestedLock), Fiber.await(fiber)); + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId }), + type: "run.updated", + threadId, + runId: captured.id, + occurredAt: now, + payload: captured, + }, + ], + }); + return fiber; + }), + ); + yield* Fiber.join(rewindFiber); + const projection = yield* projectionStore.getThreadProjection(threadId); const runIds = [otherProviderRun, keptRun, abandonedRun, unlocatedRun, rewindingRun]; assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 118a13a334266..58303f990ae0a 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -913,12 +913,23 @@ export const layer: Layer.Layer< }); }), ), - (effect) => - input.event.type === "app_thread.created" - ? threadCommands.withLock(input.event.appThread.id, effect) - : input.event.type === "thread_model_selection.updated" - ? threadCommands.withLock(input.event.threadId, effect) - : effect, + (effect) => { + const { event } = input; + if (event.type === "app_thread.created") + return threadCommands.withLock(event.appThread.id, effect); + if (event.type === "thread_model_selection.updated") + return threadCommands.withLock(event.threadId, effect); + // A native rewind updates run rows that checkpoint capture reads under this lock. + if ( + event.type === "provider_thread.updated" && + event.retainedNativeTurnIds !== undefined + ) + return threadCommands.withLock( + event.providerThread.appThreadId ?? input.threadId, + effect, + ); + return effect; + }, ), ), }); diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 3bbd5b481e6ed..6387793a93e1a 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -238,26 +238,31 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { const stat = NodeFSP.stat; const readdir = vi.mocked(NodeFSP.readdir); const readDirectory = readdir.getMockImplementation()!; - using _restore = { - [Symbol.dispose]: () => { - held.resolve(); - readdir.mockImplementation(readDirectory); - }, - }; - using _stat = vi.spyOn(NodeFSP, "stat").mockImplementation((async ( - ...args: Parameters - ) => { - if (String(args[0]).startsWith(slow + path.sep)) { - if (++heldCount === 2) started.resolve(); - await held.promise; - } - return stat(...args); - }) as typeof stat); - readdir.mockImplementation((async (...args: Parameters) => { - const entries = await readDirectory(...args); - if (String(args[0]) === next) nextRead.resolve(); - return entries; - }) as typeof NodeFSP.readdir); + yield* Effect.acquireRelease( + Effect.sync(() => { + const slowStat = vi.spyOn(NodeFSP, "stat").mockImplementation((async ( + ...args: Parameters + ) => { + if (String(args[0]).startsWith(slow + path.sep)) { + if (++heldCount === 2) started.resolve(); + await held.promise; + } + return stat(...args); + }) as typeof stat); + readdir.mockImplementation((async (...args: Parameters) => { + const entries = await readDirectory(...args); + if (String(args[0]) === next) nextRead.resolve(); + return entries; + }) as typeof NodeFSP.readdir); + return slowStat; + }), + (slowStat) => + Effect.sync(() => { + held.resolve(); + slowStat.mockRestore(); + readdir.mockImplementation(readDirectory); + }), + ); const workspace = yield* WorkspaceEntries.WorkspaceEntries; const first = yield* workspace diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts index e14d24e7c23b7..54d53ad36bc92 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts @@ -563,6 +563,17 @@ describe("merging the environments' own listings", () => { expect(pullRequestListAnsweredEmpty({ data, isPending: false, error: null })).toBe(true); expect(pullRequestListAnsweredEmpty({ data, isPending: true, error: null })).toBe(false); + const unconfigured = mergePullRequestLists([ + [ + ENV_1, + answer({ + providers: answer().providers.map((provider) => ({ ...provider, configured: false })), + }), + ], + ]); + expect( + pullRequestListAnsweredEmpty({ data: unconfigured, isPending: false, error: null }), + ).toBe(false); }); it("folds a host reached from two environments into one switcher row", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts index 55daa5d2680c7..23ef17fa09df0 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts @@ -595,7 +595,12 @@ export function pullRequestListAnsweredEmpty(view: { readonly isPending: boolean; readonly error: unknown; }): boolean { - return view.data?.entries.length === 0 && !view.isPending && view.error === null; + return ( + !view.isPending && + view.error === null && + view.data?.entries.length === 0 && + view.data.providers.every((provider) => provider.configured) + ); } export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray): string => diff --git a/packages/client-runtime/src/state/threads-atoms.test.ts b/packages/client-runtime/src/state/threads-atoms.test.ts index 9aaa605998a5b..809b8c8b499e2 100644 --- a/packages/client-runtime/src/state/threads-atoms.test.ts +++ b/packages/client-runtime/src/state/threads-atoms.test.ts @@ -54,9 +54,11 @@ const SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = { snapshotSequence: 7, pro const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?: { readonly snapshot?: OrchestrationV2ThreadDetailSnapshot; readonly socketSnapshot?: false; + readonly legacyCompletion?: true; }) { const subscriptions = yield* Queue.unbounded<{ readonly afterSequence: number | undefined; + readonly requestCompletionMarker: boolean | undefined; readonly events: Queue.Queue; readonly closed: Deferred.Deferred; }>(); @@ -71,7 +73,10 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options? let opened = 0; let active = 0; const client = { - [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly afterSequence?: number }) => + [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { + readonly afterSequence?: number; + readonly requestCompletionMarker?: boolean; + }) => Stream.unwrap( Effect.gen(function* () { const events = yield* Queue.unbounded(); @@ -86,7 +91,12 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options? active -= 1; }).pipe(Effect.andThen(Deferred.succeed(closed, undefined))), ); - yield* Queue.offer(subscriptions, { afterSequence: input.afterSequence, events, closed }); + yield* Queue.offer(subscriptions, { + afterSequence: input.afterSequence, + requestCompletionMarker: input.requestCompletionMarker, + events, + closed, + }); // Like a paging server, a fresh subscribe opens with the bounded snapshot. if (input.afterSequence === undefined && options?.socketSnapshot !== false) { yield* Queue.offer(events, { kind: "snapshot", ...snapshot }); @@ -98,7 +108,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options? const session: RpcSession = { client, initialConfig: Effect.succeed({ - threadResumeCompletionMarker: true, + ...(options?.legacyCompletion ? {} : { threadResumeCompletionMarker: true }), threadSnapshotPagination: true, } as never), subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), @@ -408,6 +418,40 @@ describe("createEnvironmentThreadStateAtoms", () => { ); }); +it.effect("uses fresh snapshots on cold opens and reconnects without completion markers", () => + Effect.gen(function* () { + const h = yield* makeHarness({ legacyCompletion: true }); + const unmount = h.registry.mount(h.stateAtom); + const first = yield* Queue.take(h.subscriptions); + expect(first.requestCompletionMarker).toBeUndefined(); + yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live"); + unmount(); + yield* Deferred.await(first.closed); + + const remount = h.registry.mount(h.stateAtom); + const resumed = yield* Queue.take(h.subscriptions); + expect(resumed.afterSequence).toBeUndefined(); + expect(resumed.requestCompletionMarker).toBeUndefined(); + yield* Queue.offer(resumed.events, { + kind: "event", + sequence: 8, + event: { + id: EventId.make("legacy-metadata"), + type: "thread.metadata-updated", + threadId: THREAD_ID, + occurredAt: THREAD.thread.updatedAt, + payload: { ...THREAD.thread, title: "Legacy live update" }, + }, + }); + const live = yield* observeState(h.registry, h.stateAtom, (state) => + Option.exists(state.data, (data) => data.thread.title === "Legacy live update"), + ); + expect(live.status).toBe("live"); + remount(); + yield* Deferred.await(resumed.closed); + }), +); + it.effect("keeps snapshot boundaries and completion markers ordered inside a replay batch", () => Effect.gen(function* () { const h = yield* makeHarness(); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 4882df1a6836e..afe9c1bfda769 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -1074,7 +1074,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } const config = yield* Effect.option(session.initialConfig); - yield* Ref.set(awaitingCompletion, true); + const requestCompletionMarker = Option.exists( + config, + (value) => value.threadResumeCompletionMarker === true, + ); + yield* Ref.set(awaitingCompletion, requestCompletionMarker); yield* markSynchronizing; yield* Ref.set(resumingLive, false); @@ -1151,14 +1155,18 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } const sequence = yield* SubscriptionRef.get(lastSequence); - const canResume = Option.isSome(current.data) && !(yield* Ref.get(forceSnapshot)); + // A legacy replay with no new events cannot confirm that a cached cursor is current. + const canResume = + requestCompletionMarker && + Option.isSome(current.data) && + !(yield* Ref.get(forceSnapshot)); yield* Ref.set(resuming, canResume); const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots); const input = { threadId, ...(canResume ? { afterSequence: sequence } : {}), - requestCompletionMarker: true as const, + ...(requestCompletionMarker ? { requestCompletionMarker: true as const } : {}), ...(acceptBoundedSnapshot ? { acceptBoundedSnapshot: true as const, From 81af658655f8395fb3d0e56576580ad716bfe4d0 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 21:24:55 -0300 Subject: [PATCH 71/87] fix(git): preserve unrelated staging during selected commits --- apps/server/src/git/GitManager.test.ts | 37 ++- apps/server/src/vcs/GitVcsDriverCore.test.ts | 7 +- apps/server/src/vcs/GitVcsDriverCore.ts | 244 ++++++++++--------- 3 files changed, 163 insertions(+), 125 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index aed7a1c478cc1..50a9786375559 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -4023,6 +4023,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { NodeFS.writeFileSync(NodePath.join(repoDir, "a.txt"), "file a\n"); NodeFS.writeFileSync(NodePath.join(repoDir, "b.txt"), "file b\n"); + yield* runGit(repoDir, ["add", "b.txt"]); const { manager } = yield* makeManager(); const result = yield* runStackedAction(manager, { cwd: repoDir, @@ -4035,11 +4036,45 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { const statusStdout = yield* runGit(repoDir, ["status", "--porcelain"]).pipe( Effect.map((r) => r.stdout), ); - expect(statusStdout).toContain("b.txt"); + expect(statusStdout).toContain("A b.txt"); expect(statusStdout).not.toContain("a.txt"); }), ); + it.effect("keeps unrelated staging when a prepared file selection becomes empty", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const readme = NodePath.join(repoDir, "README.md"); + const original = NodeFS.readFileSync(readme); + NodeFS.writeFileSync(readme, "changed while drafting\n"); + NodeFS.writeFileSync(NodePath.join(repoDir, "notes.txt"), "separately staged\n"); + yield* runGit(repoDir, ["add", "notes.txt"]); + const head = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout; + const { manager } = yield* makeManager({ + textGeneration: { + generateCommitMessage: () => + Effect.sync(() => { + NodeFS.writeFileSync(readme, original); + return { subject: "Update readme", body: "" }; + }), + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + filePaths: ["README.md"], + }); + + expect(result.commit.status).toBe("skipped_no_changes"); + expect((yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout).toBe(head); + expect((yield* runGit(repoDir, ["diff", "--cached", "--name-only"])).stdout.trim()).toBe( + "notes.txt", + ); + }), + ); + it.effect("creates feature branch, commits, and pushes with featureBranch option", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 1712dfed07508..0c708d02e3be3 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -9160,16 +9160,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["add", "staged.txt"]); const lockPath = (yield* Path.Path).join(cwd, ".git", "index.lock"); yield* (yield* FileSystem.FileSystem).writeFileString(lockPath, ""); - const { driver } = yield* makeDriverReleasingLock( - (args) => args.includes("reset"), - lockPath, - ); + const { driver } = yield* makeDriverReleasingLock((args) => args.includes("add"), lockPath); const error = yield* driver .commit(cwd, "Add a", "", { stage: { filePaths: ["a.txt"] } }) .pipe(Effect.flip); - assert.equal(error.operation, "GitVcsDriver.commit.reset"); + assert.equal(error.operation, "GitVcsDriver.commit.addSelected"); assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), head); assert.equal(yield* git(cwd, ["diff", "--cached", "--name-only"]), "staged.txt"); }), diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a58ca9eaa5c42..793cbd193f642 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3123,6 +3123,71 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return pathspecFromFileSupported; }); + const assertCanCommitSelection = Effect.fn("GitVcsDriver.assertCanCommitSelection")(function* ( + cwd: string, + ) { + const inProgressHeads = [ + { head: "MERGE_HEAD", operation: "merge" }, + { head: "CHERRY_PICK_HEAD", operation: "cherry-pick" }, + { head: "REVERT_HEAD", operation: "revert" }, + // A conflicted multi-commit `cherry-pick --no-commit` writes only the sequencer; reset + // would clear its unmerged entries, so `--continue` would walk past the conflict. + { head: "sequencer", operation: "cherry-pick or revert" }, + ] as const; + const headPaths = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ + "rev-parse", + ...inProgressHeads.flatMap(({ head }) => ["--git-path", head]), + ]); + const resolvedHeadPaths = headPaths.trim().split("\n"); + // Reftable keeps CHERRY_PICK_HEAD and REVERT_HEAD as refs with no file under .git. A + // same-named branch resolves to its full name; an ambiguity warning would blank stdout. + const operationRefs = new Set(["CHERRY_PICK_HEAD", "REVERT_HEAD"]); + const isOperationRef = (head: string) => + runGitStdout( + "GitVcsDriver.commit.operationRef", + cwd, + [ + "-c", + "core.warnAmbiguousRefs=false", + "rev-parse", + "--verify", + "--quiet", + "--symbolic-full-name", + head, + ], + true, + ).pipe(Effect.map((ref) => ref.trim() === head)); + const inProgress = yield* Effect.findFirst(inProgressHeads, ({ head }, index) => + fileSystem.exists(path.resolve(cwd, resolvedHeadPaths[index] ?? "")).pipe( + Effect.filterOrElse( + (exists) => exists || !operationRefs.has(head), + () => isOperationRef(head), + ), + ), + ).pipe( + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "GitVcsDriver.commit.mergeHead", + command: "git commit", + cwd, + detail: "Could not check whether a merge, cherry-pick or revert is in progress.", + cause, + }), + ), + ); + // Partial commits cannot finish an in-progress merge, cherry-pick or revert. + if (Option.isSome(inProgress)) { + const { operation } = inProgress.value; + return yield* new GitCommandError({ + operation: "GitVcsDriver.commit", + command: "git commit", + cwd, + detail: `Cannot commit selected files during a ${operation}. Commit all files to finish the ${operation}.`, + }); + } + }); + const stageCommitChanges = Effect.fnUntraced(function* ( cwd: string, filePaths?: readonly string[], @@ -3131,7 +3196,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const config = env ? ["-c", "core.splitIndex=false", "-c", "splitIndex.sharedIndexExpire=never"] : []; - let preserveUnselectedConflicts = false; if (filePaths && filePaths.length > 0) { if (env) { const head = yield* executeGit( @@ -3147,96 +3211,51 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* [...config, "read-tree", ...(head.exitCode === 0 ? ["HEAD"] : ["--empty"])], { env }, ); - } else { - const inProgressHeads = [ - { head: "MERGE_HEAD", operation: "merge" }, - { head: "CHERRY_PICK_HEAD", operation: "cherry-pick" }, - { head: "REVERT_HEAD", operation: "revert" }, - // A conflicted multi-commit `cherry-pick --no-commit` writes only the sequencer; reset - // would clear its unmerged entries, so `--continue` would walk past the conflict. - { head: "sequencer", operation: "cherry-pick or revert" }, - ] as const; - const headPaths = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ - "rev-parse", - ...inProgressHeads.flatMap(({ head }) => ["--git-path", head]), - ]); - const resolvedHeadPaths = headPaths.trim().split("\n"); - // Reftable keeps CHERRY_PICK_HEAD and REVERT_HEAD as refs with no file under .git. A - // same-named branch resolves to its full name; an ambiguity warning would blank stdout. - const operationRefs = new Set(["CHERRY_PICK_HEAD", "REVERT_HEAD"]); - const isOperationRef = (head: string) => - runGitStdout( - "GitVcsDriver.commit.operationRef", + } + // Status paths are repository-relative, while cwd can be a subdirectory. + const pathspecForFile = (file: string) => `:(top,literal)${file}`; + let filesToAdd = filePaths; + if (!env) { + const stagedDeletions = new Set( + (yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.stagedDeletions", cwd, [ "-c", - "core.warnAmbiguousRefs=false", - "rev-parse", - "--verify", - "--quiet", - "--symbolic-full-name", - head, + "diff.relative=false", + "diff", + "--cached", + "--no-renames", + "--name-only", + "--diff-filter=D", + "--ignore-submodules=none", + "-z", ], - true, - ).pipe(Effect.map((ref) => ref.trim() === head)); - const inProgress = yield* Effect.findFirst(inProgressHeads, ({ head }, index) => - fileSystem.exists(path.resolve(cwd, resolvedHeadPaths[index] ?? "")).pipe( - Effect.filterOrElse( - (exists) => exists || !operationRefs.has(head), - () => isOperationRef(head), - ), - ), - ).pipe( - Effect.mapError( - (cause) => - new GitCommandError({ - operation: "GitVcsDriver.commit.mergeHead", - command: "git commit", - cwd, - detail: "Could not check whether a merge, cherry-pick or revert is in progress.", - cause, - }), - ), + { maxOutputBytes: Number.POSITIVE_INFINITY }, + )).split("\0"), ); - // Like git commit --only, reject partial commits before reset can discard their state. - if (Option.isSome(inProgress)) { - const { operation } = inProgress.value; - return yield* new GitCommandError({ - operation: "GitVcsDriver.commit", - command: "git commit", - cwd, - detail: `Cannot commit selected files during a ${operation}. Commit all files to finish the ${operation}.`, - }); - } - const selectedFiles = new Set(filePaths); - const unmergedPaths = yield* runGitStdoutWithOptions( - "GitVcsDriver.commit.unmergedPaths", + // Git add cannot match an absent rename source, but commit --only reads it from HEAD. + filesToAdd = filePaths.filter((file) => !stagedDeletions.has(file)); + } + if (filesToAdd.length > 0) { + const addPathspecs = filesToAdd.map(pathspecForFile); + const fromStdin = yield* supportsPathspecFromFile(cwd); + yield* runGit( + "GitVcsDriver.commit.addSelected", cwd, - ["-c", "diff.relative=false", "diff", "--cached", "--name-only", "--diff-filter=U", "-z"], - { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + fromStdin + ? [...config, "add", "-A", "--pathspec-from-file=-", "--pathspec-file-nul"] + : [...config, "add", "-A", "--", ...addPathspecs], + { + ...(env ? { env } : {}), + ...(fromStdin + ? { stdin: addPathspecs.map((pathspec) => `${pathspec}\0`).join("") } + : {}), + }, ); - // Reset drops every conflict stage, so keep the index while unselected files are conflicted. - preserveUnselectedConflicts = unmergedPaths - .split("\0") - .some((file) => file.length > 0 && !selectedFiles.has(file)); - if (!preserveUnselectedConflicts) { - yield* runGit("GitVcsDriver.commit.reset", cwd, ["reset", "--quiet"]); - } } - // Status paths are repository-relative, while cwd can be a subdirectory. - const pathspecs = filePaths.map((file) => `:(top,literal)${file}`); - const fromStdin = yield* supportsPathspecFromFile(cwd); - yield* runGit( - "GitVcsDriver.commit.addSelected", - cwd, - fromStdin - ? [...config, "add", "-A", "--pathspec-from-file=-", "--pathspec-file-nul"] - : [...config, "add", "-A", "--", ...pathspecs], - { - ...(env ? { env } : {}), - ...(fromStdin ? { stdin: pathspecs.map((pathspec) => `${pathspec}\0`).join("") } : {}), - }, - ); + // Commit only these paths so unrelated staged changes survive. + return env ? undefined : filePaths.map(pathspecForFile); } else { // add -A marks unmerged paths resolved, so refuse while one still has conflict markers. const unmergedPaths = (yield* runGitStdoutWithOptions( @@ -3337,9 +3356,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* env ? { env } : {}, ); } - return preserveUnselectedConflicts && filePaths - ? filePaths.map((file) => `:(top,literal)${file}`) - : undefined; + return undefined; }); const prepareCommitContext: GitVcsDriver.GitVcsDriver["Service"]["prepareCommitContext"] = @@ -3488,43 +3505,32 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "--no-ext-diff", "--no-textconv", ]; - if (options?.stage?.unverified) { - const { filePaths } = options.stage; - // A selection can reset the whole index even if it was clean when inspected. - const needsScratchIndex = - (filePaths !== undefined && filePaths.length > 0) || + const stage = options?.stage; + const hasSelection = (stage?.filePaths?.length ?? 0) > 0; + if (hasSelection) yield* assertCanCommitSelection(cwd); + const needsScratchIndex = + hasSelection || + (stage?.unverified === true && (yield* executeGit("GitVcsDriver.commit.indexChanges", cwd, [...diffCached, "--quiet"], { allowNonZeroExit: true, - })).exitCode !== 0; - if ( - needsScratchIndex && - (yield* prepareCommitContext(cwd, filePaths, { includePatch: false })) === null - ) { - return yield* new GitVcsDriver.GitNothingToCommitError({ - operation: "GitVcsDriver.commit", - cwd, - detail: "Staging found no changes.", - }); - } + })).exitCode !== 0); + if ( + needsScratchIndex && + (yield* prepareCommitContext(cwd, stage?.filePaths, { includePatch: false })) === null + ) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); } const partialCommitPaths = - options?.stage !== undefined - ? yield* stageCommitChanges(cwd, options.stage.filePaths) - : undefined; - // Preserved unselected conflicts always show as index changes, so only selected paths count. - const selectedPaths = partialCommitPaths && new Set(options?.stage?.filePaths); - const hasStagedChanges = selectedPaths - ? (yield* runGitStdoutWithOptions( - "GitVcsDriver.commit.stagedChanges", - cwd, - [...diffCached, "--no-renames", "--name-only", "-z"], - { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, - )) - .split("\0") - .some((file) => file.length > 0 && selectedPaths.has(file)) - : (yield* executeGit("GitVcsDriver.commit.stagedChanges", cwd, [...diffCached, "--quiet"], { - allowNonZeroExit: true, - })).exitCode !== 0; + stage === undefined ? undefined : yield* stageCommitChanges(cwd, stage.filePaths); + const hasStagedChanges = + partialCommitPaths !== undefined || + (yield* executeGit("GitVcsDriver.commit.stagedChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode !== 0; if (!hasStagedChanges) { // Like git commit, a merge resolved to HEAD's tree still records its merge commit. const mergeHeadPath = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ From d5c9794453ca2ab5f8b63a0bef0ed5e5a0da5209 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 22 Nov 2026 21:36:06 -0300 Subject: [PATCH 72/87] fix(cursor): avoid replaying restored handoff context twice --- .../src/server/adapter.test.ts | 20 ++++- .../provider-cursor/src/server/adapter.ts | 75 ++++++++++++------- 2 files changed, 64 insertions(+), 31 deletions(-) diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 4a4187d289d2d..8252700abbe01 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -1392,7 +1392,12 @@ describe("CursorAdapterV2", () => { const firstPrompt = "Write me a 1000 word story about a dog."; const steerText = "No wait, a pig please."; - yield* runtime.startTurn(turnInput(1, firstPrompt)); + const handoff = "Context from the other thread."; + const withHandoff = (ordinal: number, context: string, text: string) => { + const prefix = `${context}\n\nUser message:\n`; + return { ...turnInput(ordinal, prefix + text), inlineContextLength: prefix.length }; + }; + yield* runtime.startTurn(withHandoff(1, handoff, firstPrompt)); const started = Option.getOrThrow( yield* runtime.events.pipe( Stream.filter((event) => event.type === "provider_turn.updated"), @@ -1401,11 +1406,13 @@ describe("CursorAdapterV2", () => { ); assert(started.type === "provider_turn.updated"); yield* runtime.interruptTurn({ providerThread, providerTurnId: started.providerTurn.id }); - yield* runtime.startTurn(turnInput(2, steerText)); + yield* runtime.startTurn(withHandoff(2, `${handoff}\nAdditional context.`, steerText)); assert.lengthOf(sentMessages, 2); const steered = sentMessages[1]!; assert.include(steered, steerText); + assert.include(steered, "Additional context."); + assert.equal(steered.split(handoff).length, 2, "restored handoff appears once"); assert.include( steered, firstPrompt, @@ -1422,7 +1429,7 @@ describe("CursorAdapterV2", () => { Stream.filter((event) => event.type === "turn.terminal" && event.status === "completed"), Stream.runHead, ); - yield* runtime.startTurn(turnInput(3, "Now a cow.")); + yield* runtime.startTurn(withHandoff(3, handoff, "Now a cow.")); assert.notInclude(sentMessages[2]!, firstPrompt, "a finished turn carries nothing forward"); assert.notInclude( sentMessages[2]!, @@ -1507,7 +1514,7 @@ describe("CursorAdapterV2", () => { Stream.runHead, ); yield* runtime.startTurn({ - ...turnInput(12, "After resume."), + ...withHandoff(12, handoff, "After resume."), modelSelection: neonSelection, }); assert.include( @@ -1515,6 +1522,11 @@ describe("CursorAdapterV2", () => { "as gemini-4-neon", "native resume after compaction must not mark invalidated runtime instructions delivered", ); + yield* interruptRunning; + yield* runtime.startTurn(turnInput(13, "One more update.")); + assert.equal(sentMessages[12]!.split(handoff).length, 2, "keep context if not sent again"); + assert.include(sentMessages[12]!, "After resume."); + assert.include(sentMessages[12]!, "One more update."); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 48f180b60a202..f1926803918db 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -971,6 +971,11 @@ interface ActiveCursorTextStream { nextSegment: number; } +interface CursorPrompt { + readonly text: string; + readonly withoutInlineContext: string; +} + interface ActiveCursorTurn { readonly input: ProviderAdapter.ProviderAdapterV2TurnInput; readonly run: CursorAgentSdk.CursorAgentSdkRun; @@ -984,7 +989,7 @@ interface ActiveCursorTurn { assistantReply: CursorTransportFailure; readonly reasoning: ActiveCursorTextStream; /** The user text this run sent, before runtime instructions; absent for /compress and resume. */ - readonly prompt: string | undefined; + readonly prompt: CursorPrompt | undefined; readonly message: string | SDKUserMessage; readonly runtimeInstructions: string | undefined; compacted: boolean; @@ -1099,7 +1104,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const interruptedPrompt = yield* Ref.make<{ readonly agent: string; readonly runId: string; - readonly text: string; + readonly prompt: CursorPrompt; readonly message: string | SDKUserMessage; readonly runtimeInstructions: string | undefined; } | null>(null); @@ -2674,7 +2679,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( yield* Ref.set(interruptedPrompt, { agent: input.context.run.agentId, runId: input.context.run.runId, - text: input.context.prompt, + prompt: input.context.prompt, message: input.context.message, runtimeInstructions: input.context.compacted ? undefined @@ -2840,33 +2845,49 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly backgroundWait: boolean; readonly runtime: string | undefined; }, - interrupted: string | undefined, + interrupted: CursorPrompt | undefined, ) { const rawText = turnInput.message.text; if (rawText.trim() === "/compress" && turnInput.message.attachments.length === 0) { return { message: "/compress", prompt: undefined, runtimeInstructions: undefined }; } - const newText = t3OrchestrationPrompt({ - prompt: yield* providerMessageTextWithAttachmentPaths({ - text: yield* resolveCursorSkillText( - rawText, - turnInput.runtimePolicy.cwd ?? undefined, - ), - attachments: turnInput.message.attachments, - resolveAttachmentPath: host.resolveAttachmentPath, - resolveExtractedTextPath: host.resolveExtractedTextPath, - }), - hasT3Mcp: mcpServers !== undefined, - hasDeviceTools, - orchestrationDelivered: delivered.orchestration, - deviceInstructionsDelivered: delivered.device, - providerInstructions: CURSOR_BACKGROUND_WAIT_INSTRUCTIONS, - providerInstructionsDelivered: delivered.backgroundWait, + const inlineContext = rawText.slice(0, turnInput.inlineContextLength ?? 0); + const userMessage = yield* resolveCursorSkillText( + rawText.slice(inlineContext.length), + turnInput.runtimePolicy.cwd ?? undefined, + ); + const textWithAttachments = yield* providerMessageTextWithAttachmentPaths({ + text: inlineContext + userMessage, + attachments: turnInput.message.attachments, + resolveAttachmentPath: host.resolveAttachmentPath, + resolveExtractedTextPath: host.resolveExtractedTextPath, }); - const userText = - interrupted === undefined - ? newText - : `Your previous turn was interrupted and is missing from your history. Some of its work may already be done. Its request was:\n\n${interrupted}\n\nThe new message, which may continue or change that request:\n\n${newText}`; + const formatPrompt = (text: string, previous: string | undefined) => { + const next = t3OrchestrationPrompt({ + prompt: text, + hasT3Mcp: mcpServers !== undefined, + hasDeviceTools, + orchestrationDelivered: delivered.orchestration, + deviceInstructionsDelivered: delivered.device, + providerInstructions: CURSOR_BACKGROUND_WAIT_INSTRUCTIONS, + providerInstructionsDelivered: delivered.backgroundWait, + }); + return previous === undefined + ? next + : `Your previous turn was interrupted and is missing from your history. Some of its work may already be done. Its request was:\n\n${previous}\n\nThe new message, which may continue or change that request:\n\n${next}`; + }; + // When orchestration supplies fresh inline context, it already includes the restored handoffs. + const userText = formatPrompt( + textWithAttachments, + inlineContext === "" ? interrupted?.text : interrupted?.withoutInlineContext, + ); + const withoutInlineContext = + inlineContext === "" && interrupted?.text === interrupted?.withoutInlineContext + ? userText + : formatPrompt( + textWithAttachments.slice(inlineContext.length), + interrupted?.withoutInlineContext, + ); const images = yield* Effect.forEach( turnInput.message.attachments.filter(isProviderNativeImageAttachment), (attachment: ChatAttachment) => @@ -2916,7 +2937,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( : userText; return { message: images.length === 0 ? text : ({ text, images } satisfies SDKUserMessage), - prompt: userText, + prompt: { text: userText, withoutInlineContext }, runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined, }; }); @@ -2994,7 +3015,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( : resume === "replay" ? { message: dropped!.message, - prompt: dropped!.text, + prompt: dropped!.prompt, runtimeInstructions: dropped!.runtimeInstructions, } : yield* resolveUserMessage( @@ -3002,7 +3023,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( mcpServers, hasDeviceTools, delivered, - dropped?.text, + dropped?.prompt, ); const compacted = resume === undefined && prompt === undefined; const pendingUpdates: Array = []; From 5e9bcf051c9b667b888a309e11277a0c8ba86c5e Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Mon, 23 Nov 2026 01:49:19 -0300 Subject: [PATCH 73/87] fix: address first integration review regressions --- .../CheckpointService.test.ts | 2 +- .../DelegatedChildTerminalRetry.test.ts | 3 +- .../DelegatedCompletionDelivery.test.ts | 273 ++++++++++-------- .../src/orchestration-v2/Orchestrator.ts | 59 +++- .../SteeringCompletion.integration.test.ts | 40 +++ apps/server/src/vcs/GitVcsDriverCore.test.ts | 52 ++++ apps/server/src/vcs/GitVcsDriverCore.ts | 109 ++++--- .../src/vcs/VcsStatusBroadcaster.test.ts | 24 +- apps/server/src/vcs/VcsStatusBroadcaster.ts | 6 +- .../src/browserHistoryStore.browser.test.ts | 95 +++++- apps/web/src/browserHistoryStore.ts | 81 ++++-- .../chat/ThreadServersPanel.browser.test.tsx | 17 +- .../components/chat/ThreadServersPanel.tsx | 2 + .../files/PdfViewer.browser.test.tsx | 7 +- apps/web/src/components/files/PdfViewer.tsx | 21 +- .../components/files/VirtualTablePreview.tsx | 1 + .../CloudVoiceConfiguration.browser.test.tsx | 35 ++- .../settings/CloudVoiceConfiguration.tsx | 8 +- apps/web/src/env.ts | 4 + ...useEnvironmentSpeechInput.browser.test.tsx | 35 ++- .../src/speech/useEnvironmentSpeechInput.ts | 16 +- apps/web/src/speech/voiceInputSession.ts | 18 +- apps/web/src/state/portForwards.ts | 9 +- apps/web/vite.config.ts | 3 + .../src/shared/definition.test.ts | 12 + .../src/shared/definition.ts | 4 +- 26 files changed, 687 insertions(+), 249 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 0433208167a73..7773737554826 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -611,7 +611,7 @@ it.effect("skips post-turn captures that waited out another capture's timeout in appRunOrdinal: 1, capturedAt: scope.createdAt, }) - .pipe(Effect.forkChild); + .pipe(Effect.forkChild({ startImmediately: true })); // A baseline's short budget running out says nothing about a post-turn capture. const baseline = yield* checkpoints .captureBaseline({ scope: scopeFor("baseline"), ordinalWithinScope: 0 }) diff --git a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts index b9c20c02b5afe..ead59fb66d6d1 100644 --- a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts @@ -175,7 +175,8 @@ const runDelegation = (input: { const orchestrator = yield* Orchestrator.OrchestratorV2; const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => - orchestrator.streamDomainEvents.pipe( + orchestrator.streamStoredEvents.pipe( + Stream.map((stored) => stored.event), Stream.filter(predicate), Stream.take(1), Stream.runDrain, diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 441c9992e73cc..0382ec0cba59e 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -2464,133 +2464,156 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( }), ); - it.effect("checkpoint retry releases a pending sibling after its wake offer failed", () => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const sink = yield* EventSink.EventSinkV2; - const outbox = yield* EffectOutbox.EffectOutboxV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; - const now = yield* DateTime.now; - const threadId = ThreadId.make("thread:checkpoint-own-delivery"); - const originRunId = RunId.make("run:checkpoint-own-delivery:origin"); - const firstId = NodeId.make("node:checkpoint-own-delivery:first"); - const siblingId = NodeId.make("node:checkpoint-own-delivery:sibling"); - yield* seedParentWithTerminalTask({ - threadId, - projectId: ProjectId.make("project:checkpoint-own-delivery"), - runId: originRunId, - rootNodeId: NodeId.make("node:checkpoint-own-delivery:root"), - taskId: firstId, - deliveryState: "claimed", - deliveryTaskIds: [firstId], - parentRunStatus: "completed", - now, - }); - const original = yield* orchestrator.getThreadProjection(threadId); - const first = original.subagents.find((task) => task.id === firstId)!; - const delivery = original.runs.find((run) => run.id === originRunId)!.delegatedCompletion! - .delivery!; - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: reconcileCommandId("checkpoint-own-delivery-wake"), - threadId, - messageId: delivery.messageId, - text: "First result", - attachments: [], - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: originRunId, - generation: delivery.generation, - taskIds: delivery.taskIds, - }, - }); - const started = yield* orchestrator.getThreadProjection(threadId); - const run = started.runs.find( - (candidate) => candidate.userMessageId === delivery.messageId, - )!; - const scopeId = started.nodes.find( - (node) => node.id === run.rootNodeId, - )!.checkpointScopeId!; - yield* outbox.cancelUnsettled({ - threadId, - effectTypes: ["provider-turn.start"], - reason: "The delivery turn already completed.", - }); - const commandId = reconcileCommandId("checkpoint-own-delivery-finished"); - yield* sink.writeWithEffects({ - commandId, - events: [ - { - id: EventId.make("event:checkpoint-own-delivery:sibling"), - type: "subagent.updated", - threadId, - runId: originRunId, - nodeId: siblingId, - occurredAt: now, - payload: { - ...first, - id: siblingId, - completionDelivery: { state: "pending", observedByRunId: null }, - }, + it.effect.each(["checkpoint", "failed run"] as const)( + "%s retry releases a pending sibling after its wake offer failed", + (retry) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + const now = yield* DateTime.now; + const threadId = ThreadId.make(`thread:checkpoint-own-delivery:${retry}`); + const originRunId = RunId.make(`run:checkpoint-own-delivery:origin:${retry}`); + const firstId = NodeId.make(`node:checkpoint-own-delivery:first:${retry}`); + const siblingId = NodeId.make(`node:checkpoint-own-delivery:sibling:${retry}`); + yield* seedParentWithTerminalTask({ + threadId, + projectId: ProjectId.make(`project:checkpoint-own-delivery:${retry}`), + runId: originRunId, + rootNodeId: NodeId.make(`node:checkpoint-own-delivery:root:${retry}`), + taskId: firstId, + deliveryState: "claimed", + deliveryTaskIds: [firstId], + parentRunStatus: "completed", + now, + }); + const original = yield* orchestrator.getThreadProjection(threadId); + const first = original.subagents.find((task) => task.id === firstId)!; + const delivery = original.runs.find((run) => run.id === originRunId)!.delegatedCompletion! + .delivery!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "server", + commandId: reconcileCommandId(`checkpoint-own-delivery-wake:${retry}`), + threadId, + messageId: delivery.messageId, + text: "First result", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + delegatedCompletion: { + parentRunId: originRunId, + generation: delivery.generation, + taskIds: delivery.taskIds, }, - { - id: EventId.make("event:checkpoint-own-delivery:finished"), - type: "run.updated", - threadId, - runId: run.id, - occurredAt: now, - payload: { - ...run, - status: "completed", - startedAt: now, - completedAt: now, - checkpointId: CheckpointId.make("checkpoint:own-delivery"), + }); + const started = yield* orchestrator.getThreadProjection(threadId); + const run = started.runs.find( + (candidate) => candidate.userMessageId === delivery.messageId, + )!; + const scopeId = started.nodes.find( + (node) => node.id === run.rootNodeId, + )!.checkpointScopeId!; + yield* outbox.cancelUnsettled({ + threadId, + effectTypes: ["provider-turn.start"], + reason: "The delivery turn already completed.", + }); + const firstOffer = yield* Deferred.make(); + using offer = vi + .spyOn(requests, "offer") + .mockImplementationOnce(() => + Deferred.succeed(firstOffer, undefined).pipe( + Effect.andThen(Effect.die("successor wake offer failed")), + ), + ); + const commandId = + retry === "checkpoint" + ? reconcileCommandId(`checkpoint-own-delivery-finished:${retry}`) + : CommandId.make("command:failed-own-delivery-finished"); + yield* sink.writeWithEffects({ + commandId, + events: [ + { + id: EventId.make(`event:checkpoint-own-delivery:sibling:${retry}`), + type: "subagent.updated", + threadId, + runId: originRunId, + nodeId: siblingId, + occurredAt: now, + payload: { + ...first, + id: siblingId, + completionDelivery: { state: "pending", observedByRunId: null }, + }, }, - }, - ], - effects: [ - { - id: "effect:checkpoint-own-delivery", - commandId, - threadId, - request: { type: "checkpoint.capture", runId: run.id, scopeId }, - }, - ], - }); - using offer = vi - .spyOn(requests, "offer") - .mockImplementationOnce(() => Effect.die("successor wake offer failed")); - const firstAttempt = yield* Effect.exit( - orchestrator.recoverDelegatedTask(threadId, { completedRunId: run.id }), - ); - assert.isTrue(Exit.isFailure(firstAttempt)); - const reserved = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (candidate) => candidate.id === originRunId, - )!.delegatedCompletion!.delivery!; - assert.deepEqual(reserved.taskIds, [siblingId]); - yield* worker.drain(); - assert.lengthOf(offer.mock.calls, 2); - const completed = yield* orchestrator.getThreadProjection(threadId); - assert.equal( - completed.subagents.find((task) => task.id === firstId)?.completionDelivery?.state, - "delivered", - ); - assert.equal( - completed.subagents.find((task) => task.id === siblingId)?.completionDelivery?.state, - "claimed", - ); - assert.deepEqual( - completed.runs.find((candidate) => candidate.id === originRunId)?.delegatedCompletion - ?.delivery?.taskIds, - [siblingId], - ); - let wake = yield* requests.take; - while (wake.threadId !== threadId) wake = yield* requests.take; - assert.equal(wake.delegatedCompletion?.generation, delivery.generation + 1); - }), + { + id: EventId.make(`event:checkpoint-own-delivery:finished:${retry}`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { + ...run, + status: retry === "checkpoint" ? "completed" : "failed", + startedAt: now, + completedAt: now, + ...(retry === "checkpoint" + ? { checkpointId: CheckpointId.make("checkpoint:own-delivery") } + : {}), + }, + }, + ], + effects: + retry === "failed run" + ? [] + : [ + { + id: `effect:checkpoint-own-delivery:${retry}`, + commandId, + threadId, + request: { type: "checkpoint.capture", runId: run.id, scopeId }, + }, + ], + }); + if (retry === "checkpoint") { + const firstAttempt = yield* Effect.exit( + orchestrator.recoverDelegatedTask(threadId, { completedRunId: run.id }), + ); + assert.isTrue(Exit.isFailure(firstAttempt)); + } else { + yield* Deferred.await(firstOffer); + } + const reserved = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === originRunId, + )!.delegatedCompletion!.delivery!; + assert.deepEqual(reserved.taskIds, [siblingId]); + if (retry === "checkpoint") { + yield* worker.drain(); + } else { + yield* TestClock.adjust("1 second"); + } + assert.lengthOf(offer.mock.calls, 2); + const completed = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + completed.subagents.find((task) => task.id === firstId)?.completionDelivery?.state, + "delivered", + ); + assert.equal( + completed.subagents.find((task) => task.id === siblingId)?.completionDelivery?.state, + "claimed", + ); + assert.deepEqual( + completed.runs.find((candidate) => candidate.id === originRunId)?.delegatedCompletion + ?.delivery?.taskIds, + [siblingId], + ); + let wake = yield* requests.take; + while (wake.threadId !== threadId) wake = yield* requests.take; + assert.equal(wake.delegatedCompletion?.generation, delivery.generation + 1); + }), ); it.effect.each(["live", "checkpoint-retry", "checkpoint-offer-retry"] as const)( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index d748ecd345935..8559ae07a5a39 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7528,6 +7528,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio turn.status !== "running")))) ) { dispatchMode = { type: "start_immediately" }; + } else if (dispatchMode.type === "steer_active" && target?.status === "waiting") { + dispatchMode = { type: "queue_after_active" }; } } // Stop leaves the run reading as running until its provider stops. A plain @@ -16529,7 +16531,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : dispatch; }); - const parentTaskSyncRetries = yield* FiberSet.make(); + const retryDelegatedCompletionDelivery = Effect.fn( + "Orchestrator.retryDelegatedCompletionDelivery", + )(function* (threadId: ThreadId, runId: RunId) { + yield* threadDispatch.withLock( + threadId, + Effect.gen(function* () { + const message = yield* projectionStore.getRunMessage(threadId, runId); + if (message?.delegatedCompletion === undefined) return; + // A prior attempt may have committed the next generation before offering its wake. + yield* offerDelegatedCompletionDelivery(threadId, message.delegatedCompletion.parentRunId); + yield* finalizeDelegatedCompletionDelivery(threadId, runId); + }), + ); + }); + + const delegatedTaskRetries = yield* FiberSet.make(); const syncDelegatedParentTask = Effect.fn("Orchestrator.syncDelegatedParentTask")(function* ( childThreadId: ThreadId, options: { readonly syncRunId: RunId | undefined; readonly retry: boolean }, @@ -16573,7 +16590,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause, }), ), - FiberSet.run(parentTaskSyncRetries), + FiberSet.run(delegatedTaskRetries), ), ), ), @@ -16609,7 +16626,29 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId, runId: run.id, cause, - }), + }).pipe( + Effect.andThen( + run.status === "completed" || + run.status === "interrupted" || + run.status === "cancelled" + ? Effect.void + : retryDelegatedCompletionDelivery(threadId, run.id).pipe( + Effect.retry({ schedule: parentTaskSyncRetry }), + Effect.delay("1 second"), + Effect.catchCause((retryCause) => + Effect.logWarning( + "Failed to retry settlement for its delegated delivery", + { + threadId, + runId: run.id, + cause: retryCause, + }, + ), + ), + FiberSet.run(delegatedTaskRetries), + ), + ), + ), ), ); yield* threadDispatch @@ -16934,19 +16973,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { const completedRunId = options?.completedRunId; if (completedRunId !== undefined) { - yield* threadDispatch.withLock( - threadId, - Effect.gen(function* () { - const message = yield* projectionStore.getRunMessage(threadId, completedRunId); - if (message?.delegatedCompletion === undefined) return; - // A prior attempt may have committed the next generation before offering its wake. - yield* offerDelegatedCompletionDelivery( - threadId, - message.delegatedCompletion.parentRunId, - ); - yield* finalizeDelegatedCompletionDelivery(threadId, completedRunId); - }), - ); + yield* retryDelegatedCompletionDelivery(threadId, completedRunId); } const sourceRunId = options?.sourceRunId; const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId); diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index dd2d95cfc1b81..8698fb2249174 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1122,6 +1122,46 @@ it.effect.each( }), ); +it.effect("queues a delayed steer for an already waiting run", () => + Effect.gen(function* () { + const { layer, startFirstTurn } = yield* nextTurnSelectionHarness("steer-into-waiting"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* startFirstTurn; + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("waiting-run"), + type: "run.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...run, status: "waiting" }, + }, + ], + }); + const messageId = MessageId.make("message:delayed-steer"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("delayed-steer"), + threadId, + messageId, + text: "Queue this while waiting", + attachments: [], + deliveryIntent: "steer", + dispatchMode: { type: "steer_active", targetRunId: run.id }, + createdBy: "user", + creationSource: "mobile", + }); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + after.runs.find((candidate) => candidate.userMessageId === messageId)?.status, + "queued", + ); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("force sends multiple queued messages and can force send a requeued message again", () => Effect.gen(function* () { const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 0c708d02e3be3..e37d5d84e5548 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -10300,6 +10300,58 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("uses the captured push branch when HEAD switches during divergence", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["switch", "-c", "feature"]); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", "feature"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "Feature ahead"]); + const feature = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, ["branch", "other"]); + yield* git(cwd, ["push", "origin", "other"]); + yield* git(cwd, ["branch", "--set-upstream-to=origin/other", "other"]); + + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const fixtureDriver = yield* GitVcsDriver.GitVcsDriver; + let switched = false; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if ( + ChildProcess.isStandardCommand(command) && + !switched && + command.args.includes("--left-right") + ) { + switched = true; + yield* git(cwd, ["switch", "other"]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, fixtureDriver), + Effect.orDie, + ); + } + return yield* delegate.spawn(command); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + assert.isTrue(switched); + assert.deepInclude(pushed, { + status: "pushed", + branch: "feature", + upstreamBranch: "origin/feature", + }); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", "refs/heads/feature"]), + feature, + ); + }), + ); + it.effect( "pushes upstream branches to the remote branch name, not the upstream shorthand", () => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 793cbd193f642..686227a4ec4b6 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1476,30 +1476,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); }); - // `--abbrev-ref` prints `remotes/origin/` when a local `origin/` branch exists. - const readCurrentUpstreamRef = Effect.fn("readCurrentUpstreamRef")(function* (cwd: string) { - const upstreamRef = yield* runGitStdout( + const readBranchUpstreamRef = Effect.fn("readBranchUpstreamRef")(function* ( + cwd: string, + branch: string, + ) { + const revision = `${branch}@{upstream}`; + const fullRef = (yield* runGitStdout( "GitVcsDriver.resolveCurrentUpstream", cwd, - ["rev-parse", "--symbolic-full-name", "@{upstream}"], + ["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", revision], true, - ).pipe(Effect.map((stdout) => stdout.trim().replace(/^refs\/(?:remotes|heads)\//, ""))); - - if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { - return null; - } - return upstreamRef; + )).trim(); + return fullRef === "" || fullRef === revision ? null : fullRef; }); - const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* ( + const shortUpstreamRef = (fullRef: string) => fullRef.replace(/^refs\/(?:remotes|heads)\//, ""); + + const resolveUpstreamDestination = Effect.fn("resolveUpstreamDestination")(function* ( cwd: string, - knownUpstreamRef?: string, + upstreamRef: string, ) { - const upstreamRef = knownUpstreamRef ?? (yield* readCurrentUpstreamRef(cwd)); - if (upstreamRef === null) { - return null; - } - const remoteNames = yield* runGitStdout("GitVcsDriver.listRemoteNames", cwd, ["remote"]).pipe( Effect.map(parseRemoteNames), Effect.orElseSucceed((): ReadonlyArray => []), @@ -2238,11 +2234,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null)); }); - const remoteRefContainsHead = (cwd: string, remoteRef: string) => + const remoteRefContainsHead = (cwd: string, sourceRef: string, remoteRef: string) => executeGit( "GitVcsDriver.pushCurrentBranch.publishContainsHead", cwd, - ["merge-base", "--is-ancestor", "HEAD", `refs/remotes/${remoteRef}`], + ["merge-base", "--is-ancestor", sourceRef, `refs/remotes/${remoteRef}`], { allowNonZeroExit: true }, ).pipe( Effect.map((result) => result.exitCode === 0), @@ -2669,21 +2665,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); } // `%(upstream:remotename)` is empty exactly when `@{upstream}` does not resolve. - const currentUpstreamRef = - upstreamRemoteName === "" ? null : yield* readCurrentUpstreamRef(cwd); + const fullUpstreamRef = + branch === null || upstreamRemoteName === "" + ? null + : yield* readBranchUpstreamRef(cwd, branch); + const currentUpstreamRef = fullUpstreamRef === null ? null : shortUpstreamRef(fullUpstreamRef); let upstreamRef = currentUpstreamRef; // Trimming a remote that starts with Unicode whitespace can leave a leading slash. if (currentUpstreamRef?.startsWith("/")) { - upstreamRef = (yield* resolveCurrentUpstream(cwd, currentUpstreamRef))?.upstreamRef ?? null; + upstreamRef = + (yield* resolveUpstreamDestination(cwd, currentUpstreamRef))?.upstreamRef ?? null; } let aheadCount = 0; let behindCount = 0; - if (upstreamRef) { + if (upstreamRef && fullUpstreamRef) { const divergence = yield* executeGit( "GitVcsDriver.statusDetailsRemote.divergence", cwd, - ["rev-list", "--left-right", "--count", `${headRef}...@{upstream}`], + ["rev-list", "--left-right", "--count", `${headRef}...${fullUpstreamRef}`], { allowNonZeroExit: true }, ); if (divergence.exitCode === 0) { @@ -3641,6 +3641,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd: string, branch: string, hasUpstream: boolean, + observedUpstream?: string | null, ) { if (!hasUpstream) { // A deleted upstream keeps its config: republish to it when it was this branch's own, @@ -3679,11 +3680,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; } + const fullUpstream = + observedUpstream === undefined + ? yield* readBranchUpstreamRef(cwd, branch).pipe(Effect.orElseSucceed(() => null)) + : null; + const upstreamRef = + observedUpstream ?? (fullUpstream === null ? null : shortUpstreamRef(fullUpstream)); + if (upstreamRef === null) return null; if ((yield* readConfigValue(cwd, `branch.${branch}.remote`)) === ".") { - const localUpstream = yield* readCurrentUpstreamRef(cwd).pipe( - Effect.orElseSucceed(() => null), - ); - if (localUpstream === null) return null; // A local upstream is a base; publish under the full local name so `origin/main` never lands on remote `main`. const remoteName = yield* resolvePushRemoteName(cwd, branch).pipe( Effect.orElseSucceed(() => null), @@ -3693,12 +3697,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* remoteName, branchName: branch, publishes: true, - upstream: { remoteName: ".", branchName: localUpstream, upstreamRef: localUpstream }, + upstream: { remoteName: ".", branchName: upstreamRef, upstreamRef }, pushRemote: null, }; } - const upstream = yield* resolveCurrentUpstream(cwd).pipe(Effect.orElseSucceed(() => null)); + const upstream = yield* resolveUpstreamDestination(cwd, upstreamRef).pipe( + Effect.orElseSucceed(() => null), + ); if (!upstream) return null; if (isAliasOfUpstreamHead(branch, upstream.branchName, upstream.upstreamRef)) { // A fork workflow pushes to the configured push remote and keeps the upstream for pulls, as plain `git push` does. @@ -3780,7 +3786,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; - const destination = yield* resolvePushDestination(cwd, branch, details.hasUpstream); + const destination = yield* resolvePushDestination( + cwd, + branch, + details.hasUpstream, + details.upstreamRef, + ); if (hasNoLocalDelta && details.hasUpstream) { if (!destination?.pushRemote) { // A local upstream and a separate push URL both leave the publish destination unchecked. @@ -3806,7 +3817,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* remoteName: pushRemote, remoteBranch: branchName, }).pipe( - Effect.andThen(remoteRefContainsHead(cwd, pushRemoteRef)), + Effect.andThen(remoteRefContainsHead(cwd, sourceRef, pushRemoteRef)), Effect.orElseSucceed(() => false), )); if (pushRemoteHasHead) { @@ -3834,6 +3845,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if ( (yield* remoteRefContainsHead( cwd, + sourceRef, `${destination.remoteName}/${destination.branchName}`, )) && (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName)) @@ -3933,7 +3945,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const [refName, currentUpstreamRef] = yield* Effect.all( [ readCurrentBranch("GitVcsDriver.pullCurrentBranch.branch", cwd), - readCurrentUpstreamRef(cwd), + readBranchUpstreamRef(cwd, "").pipe( + Effect.map((ref) => (ref === null ? null : shortUpstreamRef(ref))), + ), ], { concurrency: 2 }, ); @@ -5363,7 +5377,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const gitDirArgs = ["--git-dir", gitCommonDir] as const; // Read occupancy first so a concurrent worktree addition changes the cached stamp. const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir); - const [refsResult, defaultRefResult, remoteNamesResult] = yield* Effect.all( + const [refsResult, remoteNamesResult] = yield* Effect.all( [ executeGitWithStableDiagnostics( "GitVcsDriver.listRefs.snapshotRefs", @@ -5381,22 +5395,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* fallbackErrorDetail: "Git ref snapshot enumeration failed.", }, ), - executeGit( - "GitVcsDriver.listRefs.defaultRef", - fetchCwd, - [ - ...gitDirArgs, - "rev-parse", - "--verify", - "--quiet", - "--symbolic-full-name", - "refs/remotes/origin/HEAD", - ], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ), executeGit("GitVcsDriver.listRefs.remoteNames", fetchCwd, [...gitDirArgs, "remote"], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -5412,14 +5410,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* `GitVcsDriver.listRefs: remote name lookup returned code ${remoteNamesResult.exitCode} for ${gitCommonDir}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, ); } - const defaultBranch = - defaultRefResult.exitCode === 0 - ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin") - : null; + const lines = refsResult.stdout.split("\n"); + const defaultRef = lines.find((line) => line.startsWith("refs/remotes/origin/HEAD\t")); + const defaultBranch = parseDefaultBranchFromRemoteHeadRef( + defaultRef?.split("\t")[1] ?? "", + "origin", + ); const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; - const lines = refsResult.stdout.split("\n"); for (const line of lines) { if (line.length === 0) continue; const [fullRefName, symbolicTarget, upstreamRef, , lastCommitRaw] = line.split("\t"); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index f01e7ccd68593..f17968bb347a2 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -1579,6 +1579,28 @@ describe("VcsStatusBroadcaster", () => { }); }); + it.effect("reads the local-only refs digest after refreshing status", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const before = yield* broadcaster.refreshStatus("/repo", { localOnly: true }); + state.beforeLocalStatus = Effect.sync(() => { + state.refSnapshot = "moved"; + }); + const after = yield* broadcaster.refreshStatus("/repo", { localOnly: true }); + assert.isString(before.refsDigest); + assert.isString(after.refsDigest); + assert.notEqual(after.refsDigest, before.refsDigest); + }).pipe(Effect.provide(layerTestFor(state))); + }); + it.effect("an explicit refresh re-reads local totals only after refs moved", () => { const totals = (insertions: number): VcsStatusLocalResult => ({ ...baseLocalStatus, @@ -1639,7 +1661,7 @@ describe("VcsStatusBroadcaster", () => { assert.equal(state.localStatusCalls, 2); assert.deepStrictEqual(moved.branchChanges, totals(0).branchChanges); assert.isString(moved.refsDigest); - assert.notEqual(moved.refsDigest, unmoved.refsDigest); + assert.notEqual(moved.refsDigest, worktreeChanged.refsDigest); assert.deepStrictEqual( [...(yield* Fiber.join(events))].map((event) => event._tag), // The first refresh adds the totals this palette-style subscription skipped. diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index b02c8358099b5..d5f8ece9a8470 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -746,10 +746,8 @@ export const make = Effect.gen(function* () { refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), }; if (options?.localOnly) { - const [refs] = yield* Effect.all( - [workflow.readRefSnapshot(cwd), refreshLocalStatusCore(cwd)], - { concurrency: "unbounded" }, - ); + yield* refreshLocalStatusCore(cwd); + const refs = yield* workflow.readRefSnapshot(cwd); // Never cache a remote here: readers take `value: null` as "read and found no PR". const parts = yield* getStatusParts(cwd); return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs); diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index 49f30bcd31a3a..db9298355b55e 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -132,6 +132,59 @@ it("refreshes the open history when another document adds a visit", async () => } }); +it("caps the persisted mappings after importing multiple snapshots", async () => { + await resetHistoryFixture(); + try { + using documents = new DisposableStack(); + for (const group of ["first", "second"]) { + const mappings = Object.fromEntries( + Array.from({ length: 60 }, (_, index) => [`env:${group}-${index}`, "a"]), + ); + localStorage.setItem( + fallbackPrefix + group, + JSON.stringify({ + state: { byProjectKey: { a: [page] }, projectKeyByThreadKey: mappings }, + version: 1, + }), + ); + } + const store = await openHistoryDocument(documents); + await vi.waitFor(() => expect(store.getState().byProjectKey).toEqual({ a: [page] })); + const db = await openHistoryFixture(documents); + const saved = (await readHistoryFixture(db)) as { + projectKeyByThreadKey: Record; + }; + expect(Object.keys(saved.projectKeyByThreadKey)).toHaveLength(100); + } finally { + await resetHistoryFixture(); + } +}); + +it("includes fallback history when receiving an IndexedDB notification", async () => { + await resetHistoryFixture(); + try { + using documents = new DisposableStack(); + const db = await openHistoryFixture(documents); + const channel = new BroadcastChannel(storageKey); + documents.defer(() => channel.close()); + localStorage.setItem( + fallbackPrefix + "visit", + JSON.stringify({ state: { byProjectKey: { b: [otherEntry] } }, version: 1 }), + ); + await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: {} }); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel is scoped to the origin + channel.postMessage(null); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ + a: [page], + b: [otherEntry], + }), + ); + } finally { + await resetHistoryFixture(); + } +}); + it("bounds saved thread mappings while keeping live registrations", async () => { await resetHistoryFixture(); const mappings = Object.fromEntries( @@ -321,6 +374,39 @@ it("keeps overlapping visits from independent documents", async () => { } }); +it("replaces a fallback snapshot when keeping both records would exceed quota", async () => { + await resetHistoryFixture(); + try { + const store = useBrowserHistoryStore.getState(); + const setItem = Storage.prototype.setItem; + { + using _transaction = vi.spyOn(IDBDatabase.prototype, "transaction").mockImplementation(() => { + throw new DOMException("Storage unavailable", "SecurityError"); + }); + store.recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + await vi.waitFor(() => expect(fallbackKeys()).toHaveLength(1)); + using _quota = vi.spyOn(Storage.prototype, "setItem").mockImplementation(function ( + this: Storage, + key: string, + value: string, + ) { + if (key.startsWith(fallbackPrefix) && this.getItem(key) === null) + throw new DOMException("Only one snapshot fits", "QuotaExceededError"); + setItem.call(this, key, value); + }); + store.setTitleForUrl("a", oldEntry.url, "Kept within quota"); + await vi.waitFor(() => + expect(JSON.parse(localStorage.getItem(fallbackKeys()[0]!) ?? "null")).toMatchObject({ + state: { byProjectKey: { a: [{ ...oldEntry, title: "Kept within quota" }] } }, + }), + ); + expect(fallbackKeys()).toHaveLength(1); + } + } finally { + await resetHistoryFixture(); + } +}); + it("keeps visits saved while IndexedDB could not open", async () => { await resetHistoryFixture(); try { @@ -486,6 +572,10 @@ it.each([ await vi.waitFor(async () => expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey.a", [oldEntry]), ); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { b: [otherEntry] } }, version: 1 }), + ); { using _transaction = vi.spyOn(IDBDatabase.prototype, "transaction").mockImplementation(() => { throw new DOMException("Storage unavailable", "SecurityError"); @@ -501,7 +591,10 @@ it.each([ const expected = [{ ...oldEntry, title: indexedTitle ?? "Recovered title" }]; const recovered = await openHistoryDocument(fixture); await vi.waitFor(() => expect(recovered.getState().byProjectKey.a).toEqual(expected)); - expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey.a", expected); + expect(await readHistoryFixture(db)).toHaveProperty("byProjectKey", { + a: expected, + b: [otherEntry], + }); } finally { await resetHistoryFixture(); } diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index 84ddecf6b7a4b..be16cb4580f31 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -335,13 +335,26 @@ function readHistorySnapshots(): HistorySnapshot[] { } } +async function withHistorySnapshotLock(run: (locked: boolean) => A): Promise { + if (!navigator.locks) return run(false); + let acquired = false; + try { + return await navigator.locks.request(BROWSER_HISTORY_STORAGE_KEY, () => { + acquired = true; + return run(true); + }); + } catch (error) { + if (acquired) throw error; + return run(false); + } +} + function retireHistorySnapshots(snapshots: readonly HistorySnapshot[]): void { try { const storage = window.localStorage; for (const { key, raw } of snapshots) { - // Fallback keys are immutable. Older clients may still overwrite the original key. - if (key !== BROWSER_HISTORY_STORAGE_KEY || storage.getItem(key) === raw) - storage.removeItem(key); + // A quota-limited writer can replace an existing snapshot after the transaction read it. + if (storage.getItem(key) === raw) storage.removeItem(key); } } catch { // The browser can deny access to localStorage independently of IndexedDB. @@ -442,20 +455,34 @@ function rebaseUnsavedHistory( // Without IndexedDB, merge into the freshest localStorage snapshot so a reload keeps new visits. function transactLegacyHistory(update: UpdateStoredHistory, current: PersistedBrowserHistory) { - const snapshots = readHistorySnapshots(); - const base = mergeHistorySnapshots(undefined, snapshots) ?? current; - const history = update(base); - if (history === base) return { history, pending: undefined }; - try { - window.localStorage.setItem( - `${BROWSER_HISTORY_FALLBACK_PREFIX}${randomUUID()}`, - JSON.stringify({ state: history, version: 1 }), - ); - retireHistorySnapshots(snapshots); - return { history, pending: undefined }; - } catch { - return { history, pending: { base, history } }; - } + return withHistorySnapshotLock((locked) => { + const snapshots = readHistorySnapshots(); + const base = mergeHistorySnapshots(current, snapshots) ?? current; + const history = update(base); + if (history === base) return { history, pending: undefined }; + try { + const storage = window.localStorage; + const raw = JSON.stringify({ state: history, version: 1 }); + let savedKey = `${BROWSER_HISTORY_FALLBACK_PREFIX}${randomUUID()}`; + try { + storage.setItem(savedKey, raw); + } catch (error) { + if (!locked || !(error instanceof DOMException) || error.name !== "QuotaExceededError") + throw error; + const largest = snapshots + .filter(({ key }) => key.startsWith(BROWSER_HISTORY_FALLBACK_PREFIX)) + .toSorted((a, b) => b.raw.length - a.raw.length)[0]; + if (!largest) throw error; + // An atomic replacement keeps the previous record if the new value still cannot fit. + storage.setItem(largest.key, raw); + savedKey = largest.key; + } + retireHistorySnapshots(snapshots.filter(({ key }) => key !== savedKey)); + return { history, pending: undefined }; + } catch { + return { history, pending: { base, history } }; + } + }); } function invalidateHistoryDatabase(opening: Promise): void { @@ -505,16 +532,26 @@ async function transactIndexedHistory(update?: UpdateStoredHistory, retry = true let snapshots: readonly HistorySnapshot[] = []; request.onsuccess = () => { const saved = request.result as PersistedBrowserHistory | undefined; - if (update) snapshots = readHistorySnapshots(); + snapshots = readHistorySnapshots(); const previous = mergeHistorySnapshots(saved, snapshots); history = update?.(previous) ?? previous ?? EMPTY_PERSISTED_HISTORY; changed = history !== saved; - if (update && changed) store.put(history, BROWSER_HISTORY_STORAGE_KEY); + if (update && changed) { + if (snapshots.length > 0) + history = boundThreadMappings(previous ?? EMPTY_PERSISTED_HISTORY, history); + store.put(history, BROWSER_HISTORY_STORAGE_KEY); + } }; transaction.oncomplete = () => { // Keep the migration source until the IndexedDB snapshot has committed. - if (snapshots.length > 0) retireHistorySnapshots(snapshots); - resolve({ history, changed }); + if (update && snapshots.length > 0) { + void withHistorySnapshotLock(() => retireHistorySnapshots(snapshots)).then( + () => resolve({ history, changed }), + reject, + ); + } else { + resolve({ history, changed }); + } }; transaction.onabort = () => reject(transaction.error); }); @@ -546,7 +583,7 @@ export const useBrowserHistoryStore = create()((set, g return; } const { byProjectKey, projectKeyByThreadKey } = get(); - const fallback = transactLegacyHistory( + const fallback = await transactLegacyHistory( persist, unsavedHistory?.base ?? { byProjectKey, projectKeyByThreadKey }, ); diff --git a/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx b/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx index 101c31f0c1f7a..3c3248d66d8e4 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx @@ -8,9 +8,9 @@ vi.mock("~/env", () => ({ isElectron: true })); vi.mock(import("../../state/portForwards"), async (importOriginal) => ({ ...(await importOriginal()), canForwardPorts: () => true, - useForwardLocality: () => "remote" as const, + useForwardLocality: () => "pending" as const, usePortForwards: () => [], - forwardPort: (async (environmentId: string, remotePort: number) => ({ + forwardPort: vi.fn(async (environmentId: string, remotePort: number) => ({ environmentId, remotePort, localPort: 45000, @@ -50,6 +50,7 @@ vi.mock(import("../../portDiscoveryState"), async (importOriginal) => ({ })); import { render } from "../../../test/render"; +import { forwardPort } from "../../state/portForwards"; import { ThreadServersPanel } from "./ThreadServersPanel"; const panel = (threadId: string) => ( @@ -89,3 +90,15 @@ it("opens a remote server in the system browser through the forward a modified c expect(shell.openExternal).toHaveBeenCalledWith("http://localhost:45000/"), ); }); + +it("opens a local server on a modified click before locality resolves", async () => { + shell.openExternal.mockClear(); + vi.mocked(forwardPort).mockRejectedValueOnce( + new Error("Same machine", { cause: new Error("LoopbackTunnelSameMachineError") }), + ); + await using _screen = await render(panel("a")); + await page.getByText("localhost:3000", { exact: true }).click({ modifiers: ["ControlOrMeta"] }); + await vi.waitFor(() => + expect(shell.openExternal).toHaveBeenCalledExactlyOnceWith("http://localhost:3000"), + ); +}); diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index e71a6be549a42..b3b645ec45c73 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -31,6 +31,7 @@ import { findPortForward, forwardedUrl, forwardPort, + isSameMachinePortForwardError, stopPortForward, useForwardLocality, usePortForwards, @@ -111,6 +112,7 @@ function ThreadServersList(props: ThreadServersPanelProps) { ? await forwardPort(props.environmentId, server.port).then( (forward) => forwardedUrl(forward, server.url), (error: unknown) => { + if (isSameMachinePortForwardError(error)) return server.url; reportFailure(gt("Could not forward port {port}", { port: server.port }), error); return null; }, diff --git a/apps/web/src/components/files/PdfViewer.browser.test.tsx b/apps/web/src/components/files/PdfViewer.browser.test.tsx index ef339999e8d10..1a07b4113339c 100644 --- a/apps/web/src/components/files/PdfViewer.browser.test.tsx +++ b/apps/web/src/components/files/PdfViewer.browser.test.tsx @@ -267,7 +267,8 @@ it("follows a link to another page and exposes a web link", async () => { text: "BT /F1 24 Tf 30 700 Td (See p. 2) Tj 0 -60 Td (Website) Tj ET", annots: [ "<< /Type /Annot /Subtype /Link /Rect [30 690 200 730] /Border [0 0 0] /Dest [5 0 R /XYZ 0 792 0] >>", - "<< /Type /Annot /Subtype /Link /Rect [30 630 200 670] /Border [0 0 0] /A << /S /URI /URI (https://example.com/) >> >>", + "<< /Type /Annot /Subtype /Link /Rect [30 -30 200 670] /Border [0 0 0] /A << /S /URI /URI (https://example.com/) >> >>", + "<< /Type /Annot /Subtype /Link /F 2 /Rect [30 610 200 620] /A << /S /URI /URI (https://example.com/hidden) >> >>", ].join(" "), }, { box: "0 0 612 792", rotate: 0, text: "BT /F1 24 Tf 30 700 Td (Target) Tj ET" }, @@ -287,6 +288,10 @@ it("follows a link to another page and exposes a web link", async () => { return link!; }); expect(getComputedStyle(web).cursor).toBe("pointer"); + expect(web.getBoundingClientRect().bottom).toBeLessThanOrEqual( + web.parentElement!.getBoundingClientRect().bottom + 1, + ); + expect(region.querySelector('a[href="https://example.com/hidden"]')).toBeNull(); const internal = await vi.waitFor(() => { const link = Array.from(region.querySelectorAll("a")).find( (anchor) => anchor !== web, diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index 31faf628fbeb9..f8c173c98bbc2 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -43,6 +43,8 @@ type PdfPosition = PdfViewState & { width: number; ratios: readonly number[] }; // Thread switches unmount the preview; retain only the most recent documents. const positions = new Map(); +const PDF_ANNOTATION_HIDDEN = 2; + type PdfLink = { box: readonly [number, number, number, number] } & ( | { url: string } | { page: number } @@ -134,14 +136,23 @@ function PdfPage(props: { const linked = page.getAnnotations({ intent: "display" }).then(async (annotations) => { const found: PdfLink[] = []; for (const annotation of annotations) { - if (annotation.subtype !== "Link") continue; + if ( + annotation.subtype !== "Link" || + ((annotation.annotationFlags ?? 0) & PDF_ANNOTATION_HIDDEN) !== 0 + ) + continue; const [x1, y1] = viewport.convertToViewportPoint(annotation.rect[0], annotation.rect[1]); const [x2, y2] = viewport.convertToViewportPoint(annotation.rect[2], annotation.rect[3]); + const left = Math.max(0, Math.min(x1, x2)); + const right = Math.min(viewport.width, Math.max(x1, x2)); + const top = Math.max(0, Math.min(y1, y2)); + const bottom = Math.min(viewport.height, Math.max(y1, y2)); + if (!(left < right && top < bottom)) continue; const box = [ - Math.min(x1, x2) / viewport.width, - Math.min(y1, y2) / viewport.height, - Math.abs(x2 - x1) / viewport.width, - Math.abs(y2 - y1) / viewport.height, + left / viewport.width, + top / viewport.height, + (right - left) / viewport.width, + (bottom - top) / viewport.height, ] as const; if (typeof annotation.url === "string" && /^https?:\/\//i.test(annotation.url)) { found.push({ box, url: annotation.url }); diff --git a/apps/web/src/components/files/VirtualTablePreview.tsx b/apps/web/src/components/files/VirtualTablePreview.tsx index 229a6efb87329..ebe512abbfe66 100644 --- a/apps/web/src/components/files/VirtualTablePreview.tsx +++ b/apps/web/src/components/files/VirtualTablePreview.tsx @@ -404,6 +404,7 @@ function ScaledRows( if (existing && (existing.row === row || sameRowCells(existing.row, row))) { existing.row = row; } else { + cache.delete(index); uncached.push({ index, row }); } } diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx index f859695e3360d..752e0a021a81a 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx @@ -10,6 +10,11 @@ import { useEnvironmentScope, usePreparedConnection } from "../../state/session" import { VoiceSettingsPanel } from "./VoiceSettingsPanel"; import { SettingsScopeProvider } from "./SettingsScopeContext"; +const legacy = vi.hoisted(() => ({ active: false, enabled: false })); +vi.mock(import("../../env"), async (importOriginal) => ({ + ...(await importOriginal()), + legacySecretsFeatureEnabled: () => legacy.enabled, +})); vi.mock(import("../../state/session"), { spy: true }); vi.mock("../../state/environments", async (importOriginal) => ({ ...(await importOriginal()), @@ -20,7 +25,7 @@ vi.mock("../../state/environments", async (importOriginal) => ({ label: "Laptop", connection: { phase: "available" }, serverConfig: { - featureFlags: { secretProviders: true }, + ...(legacy.active ? {} : { featureFlags: { secretProviders: true } }), secretReferences: true, settings: { secretProviders: { @@ -108,6 +113,34 @@ it("cancelling a provider's setup keeps the current destination and writes nothi ); }); +it.each([true, false])("respects the client flag on legacy voice servers (%s)", async (enabled) => { + legacy.active = true; + legacy.enabled = enabled; + try { + await withVoicePanel( + (url) => + url.pathname === "/api/voice/cloud/keys" + ? Promise.resolve(Response.json({ openai: false, xai: true })) + : null, + async (screen) => { + await screen.getByRole("combobox", { name: "Transcribe with" }).click(); + await page.getByRole("option", { name: "OpenAI via Laptop" }).click(); + const dialog = page.getByRole("dialog"); + const source = dialog.getByRole("combobox", { name: "OpenAI API key source" }); + if (enabled) { + await source.click(); + await expect.element(page.getByRole("option", { name: "Work vault" })).toBeVisible(); + } else { + await expect.element(source).not.toBeInTheDocument(); + } + }, + ); + } finally { + legacy.active = false; + legacy.enabled = false; + } +}); + it("enables the chosen provider only after a successful setup", async () => { chooseAudioDestination({ kind: "environment", environmentId: id }); const writes: unknown[] = []; diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 0a992f4f93b61..a7f5e55630f2a 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -32,6 +32,7 @@ import type { HttpClient } from "effect/http"; import { Atom, AsyncResult } from "effect/reactivity"; import { useId, useState } from "react"; import { T, useGT, useMessages, Var } from "gt-react"; +import { legacySecretsFeatureEnabled } from "../../env"; import { inEnvironmentSpeechRuntime, runEnvironmentSpeech, @@ -193,9 +194,12 @@ export function CloudVoiceConfiguration({ const [model, setModel] = useState(currentModel ?? ""); const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; + const secretsEnabled = + environment.serverConfig?.featureFlags === undefined + ? legacySecretsFeatureEnabled() + : hasFeatureFlag(environment.serverConfig, "secretProviders"); const sources = - hasFeatureFlag(environment.serverConfig, "secretProviders") && - environment.serverConfig?.secretReferences + secretsEnabled && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) : []; const reference = diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts index be2a563d736bd..d0e453724793a 100644 --- a/apps/web/src/env.ts +++ b/apps/web/src/env.ts @@ -1,2 +1,6 @@ // Preload installs desktopBridge before web code runs, so module-load detection is reliable. export const isElectron = typeof window !== "undefined" && window.desktopBridge !== undefined; + +export function legacySecretsFeatureEnabled(): boolean { + return ["1", "true"].includes(import.meta.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? ""); +} diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 99cbff1c14a13..9a6ab667d2212 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -23,6 +23,7 @@ import { GlobalVoiceInputIndicator } from "../components/chat/GlobalVoiceInputIn import { VoiceInputSetup } from "../components/chat/VoiceInputSetup"; import type { createBrowserVoiceInputPlatform } from "./browserVoiceInput"; import { useEnvironmentSpeechInput } from "./useEnvironmentSpeechInput"; +import { VoiceInputSession } from "./voiceInputSession"; import { chooseAudioDestination, chooseTranscriptCleanup, @@ -119,7 +120,9 @@ vi.mock("../hooks/useSettings", () => ({ ), }), })); -vi.mock("./runEnvironmentSpeech", () => ({ runEnvironmentSpeech: Effect.runPromise })); +vi.mock("./runEnvironmentSpeech", async () => ({ + runEnvironmentSpeech: (await import("effect/Effect")).runPromise, +})); vi.mock("../components/ui/toast", () => ({ toastManager: { add: vi.fn() } })); vi.mock("@t3tools/client-runtime/voice-input", async (importOriginal) => ({ ...(await importOriginal()), @@ -275,6 +278,7 @@ function Probe(props: { readonly showWizard?: boolean; readonly ownerKey?: string; readonly persistent?: boolean; + readonly disabled?: boolean; }) { const value = useEnvironmentSpeechInput({ environmentId: THREAD_ENV as EnvironmentId, @@ -282,6 +286,7 @@ function Probe(props: { projectName: props.projectName, cleanup: props.cleanup, ownerKey: props.ownerKey ?? "draft", + disabled: props.disabled === true, persistentDraft: props.persistent ? { readStoredText: () => mocks.storedDraft, @@ -988,6 +993,34 @@ it("lets the user retry after a status failure without reselecting the destinati expect(mocks.transcribeCalls).toEqual(["env-a"]); }); +it("submits the accepted transcript even before the live field rerenders", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using _screen = await render(); + await act(() => mocks.voice.start()); + await act(async () => mocks.voice.submitAfterDictation(submit)); + await vi.waitFor(() => expect(submit).toHaveBeenCalledExactlyOnceWith("dictated")); + expect(mocks.committed).toHaveBeenCalledWith("dictated", expect.anything()); +}); + +it("refuses a late queued submission for the same disabled owner", async () => { + setup({ destination: "env-a" }); + const queued: { submit?: (text: string) => void } = {}; + using _queue = vi + .spyOn(VoiceInputSession.prototype, "queueSubmission") + .mockImplementationOnce((_ownerKey, submit) => { + queued.submit = submit; + return true; + }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + queued.submit!("transcript that arrived after disabling dictation"); + expect(submit).not.toHaveBeenCalled(); +}); + it("delivers a queued submission for a persistent draft after switching owners", async () => { setup({ destination: "env-a" }); const submit = vi.fn(); diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index c7915685727b6..a0269c1c356e2 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -302,7 +302,12 @@ export function useEnvironmentSpeechInput(input: HookInput) { submit(latestRef.current.input.readDraft().text); return; } - session.queueSubmission(latestRef.current.input.ownerKey, submit); + const { ownerKey } = latestRef.current.input; + session.queueSubmission(ownerKey, (text) => { + const current = latestRef.current.input; + if (mountedRef.current && current.ownerKey === ownerKey && current.disabled) return; + submit(text); + }); }); const createTarget = useStableCallback((): VoiceInputTarget => { @@ -335,12 +340,15 @@ export function useEnvironmentSpeechInput(input: HookInput) { }, commitDraft: (text, selection) => { if (!live()) { - persistent?.commitStoredText(text); - return; + if (persistent === null) return false; + persistent.commitStoredText(text); + return persistent.readStoredText() === text; } - if (latestRef.current.input.disabled) return; + if (latestRef.current.input.disabled) return false; latestRef.current.input.commitDraft(text, selection); + return true; }, + canSubmit: () => (live() ? !latestRef.current.input.disabled : persistent !== null), readContext: () => (live() ? readContext() : startContext), }; }); diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index 577b26595efed..2275ab11c8117 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -62,7 +62,8 @@ export type VoiceInputTarget = { readonly persistent: boolean; readonly open: (() => void) | null; readonly readDraft: () => DraftInput | null; - readonly commitDraft: (text: string, selection: DraftInput["selection"]) => void; + readonly commitDraft: (text: string, selection: DraftInput["selection"]) => boolean; + readonly canSubmit: () => boolean; readonly readContext: () => VoiceRecordingContext; }; @@ -243,9 +244,11 @@ export class VoiceInputSession { return target && draft ? { ownerKey: target.ownerKey, ...draft } : null; }, commitDraft: (text, selection) => { - const ownerKey = this.target?.ownerKey ?? null; - this.target?.commitDraft(text, selection); - if (ownerKey !== null && this.pendingSubmission?.ownerKey === ownerKey) { + const target = this.target; + if ( + target?.commitDraft(text, selection) && + this.pendingSubmission?.ownerKey === target.ownerKey + ) { this.pendingSubmission.text = text; } }, @@ -263,7 +266,12 @@ export class VoiceInputSession { if (state.phase === "idle" && this.pendingSubmission !== null) { const pending = this.pendingSubmission; this.pendingSubmission = null; - if (pending.text !== undefined) pending.submit(pending.text); + if ( + pending.text !== undefined && + this.target?.ownerKey === pending.ownerKey && + this.target.canSubmit() + ) + pending.submit(pending.text); } }, }); diff --git a/apps/web/src/state/portForwards.ts b/apps/web/src/state/portForwards.ts index 477ad39885adb..cfdc2bf514ea6 100644 --- a/apps/web/src/state/portForwards.ts +++ b/apps/web/src/state/portForwards.ts @@ -128,6 +128,13 @@ export const findPortForward = ( (forward) => forward.environmentId === environmentId && forward.remotePort === remotePort, ); +export function isSameMachinePortForwardError(error: unknown): boolean { + const original = error instanceof Error ? (error.cause ?? error) : error; + return (original instanceof Error ? original.message : String(original)).includes( + "LoopbackTunnelSameMachineError", + ); +} + export function forwardPort(environmentId: EnvironmentId, remotePort: number) { const bridge = previewBridge(); if (!bridge) return Promise.reject(new Error(m(msg("Port forwarding needs the desktop app.")))); @@ -135,7 +142,7 @@ export function forwardPort(environmentId: EnvironmentId, remotePort: number) { // Electron flattens main-process errors into "Error invoking remote method '…': Tag: text". const raw = error instanceof Error ? error.message : String(error); throw new Error( - raw.includes("LoopbackTunnelSameMachineError") + isSameMachinePortForwardError(error) ? m( msg("This environment runs on this computer, so localhost:{port} already reaches it.", { port: remotePort, diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 005e828202bda..26eadf791b380 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -369,6 +369,9 @@ export default defineConfig(({ command }) => { "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify( configuredDesktopUpdateRepository, ), + "import.meta.env.T3CODE_FEATURE_SECRETS": JSON.stringify( + process.env.T3CODE_FEATURE_SECRETS ?? "", + ), "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel), "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion), }, diff --git a/packages/source-control-azure-devops/src/shared/definition.test.ts b/packages/source-control-azure-devops/src/shared/definition.test.ts index 9234546a8a5a8..6ef4e6adeadaa 100644 --- a/packages/source-control-azure-devops/src/shared/definition.test.ts +++ b/packages/source-control-azure-devops/src/shared/definition.test.ts @@ -169,6 +169,18 @@ describe("Azure DevOps repository keys", () => { ).toBe(false); }); + it.each([ + "https://dev.azure.com/acme/_git/web/pullrequest/7", + "https://acme.visualstudio.com/_git/web/pullrequest/7", + ])("matches project-less links to a project named after the repository (%s)", (url) => { + const remoteUrl = "https://dev.azure.com/acme/web/_git/web"; + const identity: ChangeRequestProjectIdentity = { + canonicalKey: registry.repositoryKeyFromRemote(remoteUrl), + locator: { source: "git-remote", remoteName: "origin", remoteUrl }, + }; + expect(definition.isChangeRequestInRepository(identity, parse(url)!)).toBe(true); + }); + it("matches a repository however its name is percent-encoded", () => { const remoteUrl = "https://example@dev.azure.com/example/Sample%20(Beta)/_git/Sample%20(Beta)"; const canonicalKey = registry.repositoryKeyFromRemote(remoteUrl); diff --git a/packages/source-control-azure-devops/src/shared/definition.ts b/packages/source-control-azure-devops/src/shared/definition.ts index a32ba471a7b48..0708fbf488339 100644 --- a/packages/source-control-azure-devops/src/shared/definition.ts +++ b/packages/source-control-azure-devops/src/shared/definition.ts @@ -63,7 +63,9 @@ function canonicalRepositoryKey(key: string): string | null { .replace( /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u, "dev.azure.com/$1/$2/_git/$3", - ); + ) + .replace(/^dev\.azure\.com\/([^/]+)\/_git\/([^/]+)$/u, "dev.azure.com/$1/$2/_git/$2") + .replace(/^([^.]+)\.visualstudio\.com\/_git\/([^/]+)$/u, "dev.azure.com/$1/$2/_git/$2"); return canonical.startsWith("dev.azure.com/") ? canonical : null; } From b50d4f5a4470d1a44d76f5dac1b8e02b3d6133af Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Tue, 24 Nov 2026 09:56:08 -0300 Subject: [PATCH 74/87] fix(codex): refuse work after the app-server retires --- .../Adapters/CodexAdapterV2.test.ts | 85 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 2 + 2 files changed, 87 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 3ba9cbd119d85..8c2f34e2598e0 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1176,6 +1176,7 @@ describe("CodexAdapterV2 session initialize", () => { transcript: CodexReplay.CodexAppServerReplayTranscript, beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"], compatibility?: CodexAdapterV2.CodexAdapterV2Options["compatibility"], + awaitTermination?: CodexClient.CodexAppServerClient["Service"]["awaitTermination"], ) => Effect.gen(function* () { const driver = yield* CodexReplay.makeReplayDriver( @@ -1198,6 +1199,7 @@ describe("CodexAdapterV2 session initialize", () => { (client) => ({ ...client, + awaitTermination: awaitTermination ?? client.awaitTermination, request: (method, params) => Effect.sync(() => { if (method === "initialize") initializeRequests++; @@ -1604,6 +1606,89 @@ describe("CodexAdapterV2 session initialize", () => { ), ); + it.effect.each(["thread/start", "turn/start"] as const)( + "refuses %s when the app-server retires while config is pending", + (method) => + Effect.gen(function* () { + const waitingForConfig = yield* Deferred.make(); + const releaseConfig = yield* Deferred.make(); + const retire = yield* Deferred.make(); + const nativeThreadId = "retired-during-config"; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "return-after-retirement", + prompt: "Hello", + }); + let holdConfig = method === "thread/start"; + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: method, + entries: preamble.slice(0, method === "thread/start" ? 5 : 7), + }), + (entry) => + entry.label === "config/read" && holdConfig + ? Deferred.succeed(waitingForConfig, undefined).pipe( + Effect.andThen(Deferred.await(releaseConfig)), + ) + : Effect.void, + undefined, + Deferred.await(retire).pipe( + Effect.andThen( + Effect.fail( + new CodexError.CodexAppServerProcessExitedError({ + code: 17, + pid: 52, + }), + ), + ), + ), + ); + const eventsExit = yield* Stream.runDrain(session.events).pipe( + Effect.exit, + Effect.forkChild({ startImmediately: true }), + ); + const threadId = ThreadId.make("thread-retired-during-config"); + const start = yield* Effect.gen(function* () { + if (method === "thread/start") return session.ensureThread(threadId).pipe(Effect.asVoid); + const providerThread = yield* session.ensureThread(threadId); + holdConfig = true; + return session.runtime.startTurn( + makeCodexTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("retired-during-config-attempt"), + text: "Hello", + }), + ); + }); + const pending = yield* Effect.exit(start).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(waitingForConfig); + yield* Deferred.succeed(retire, undefined); + assert.isTrue(Exit.isFailure(yield* Fiber.join(eventsExit))); + yield* Deferred.succeed(releaseConfig, undefined); + const outcome = yield* Fiber.join(pending); + const error = Exit.isFailure(outcome) ? Cause.squash(outcome.cause) : undefined; + assert.isTrue( + Predicate.hasProperty(error, "cause") && + Predicate.isTagged(error.cause, "CodexAppServerRetiredError"), + `retired app-server did not refuse ${method}`, + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #24300 a wedged shared app-server left thread/start pending and stayed ready it.effect("fails and retires a shared app-server that never answers thread/start", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 01950ecdce26a..9b6fe6405176e 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -7761,6 +7761,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(turnInput.appContext === undefined ? {} : { appContext: turnInput.appContext }), ...(configuredReasoningSummary === undefined ? {} : { configuredReasoningSummary }), }); + yield* rejectIfRetired; yield* Ref.update(pendingRootTurns, (current) => { const updated = new Map(current); updated.set(threadId, turnInput); @@ -8156,6 +8157,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readStdioMcpServers(threadInput.runtimePolicy.cwd), ]), ), + Effect.tap(() => rejectIfRetired), Effect.flatMap(([mcpSession, stdioMcpServers]) => client .request("thread/start", { From f1f8961e521ae65b80412678ccf51f981077008f Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Tue, 24 Nov 2026 10:22:20 -0300 Subject: [PATCH 75/87] fix(git): pin private PR worktree pushes to the companion --- apps/server/src/git/GitManager.test.ts | 23 ++++- apps/server/src/git/GitManager.ts | 93 +++++++++++++------ packages/contracts/src/sourceControl.ts | 1 + .../TanStackSourceSourceControlProvider.ts | 40 +++++--- 4 files changed, 109 insertions(+), 48 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 48a0050a29d52..90e0795f8744b 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -6638,9 +6638,14 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); - it.effect.each([{ blocker: null }, { blocker: "t3code" }, { blocker: "t3code/pr-81" }])( - "preserves fork upstream tracking when preparing a worktree PR thread (local branch $blocker)", - ({ blocker }) => + it.effect.each([ + { blocker: null, privateHead: false }, + { blocker: "t3code", privateHead: false }, + { blocker: "t3code/pr-81", privateHead: false }, + { blocker: null, privateHead: true }, + ])( + "preserves fork upstream tracking when preparing a worktree PR thread (local branch $blocker, private head $privateHead)", + ({ blocker, privateHead }) => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); yield* initRepo(repoDir); @@ -6655,6 +6660,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { yield* runGit(repoDir, ["commit", "-m", "Fork PR branch"]); yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-fork"]); yield* runGit(repoDir, ["checkout", "main"]); + if (privateHead) { + yield* runGit(repoDir, ["config", "remote.pushDefault", "origin"]); + } const mainHead = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim(); // A local branch owning a parent of the generated `t3code/pr-/` ref must not block checkout. if (blocker !== null) yield* runGit(repoDir, ["branch", blocker]); @@ -6669,6 +6677,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { headRefName: "feature/pr-fork", state: "open", isCrossRepository: true, + ...(privateHead ? { requiresPrivateHeadPush: true as const } : {}), headRepositoryNameWithOwner: "octocat/codething-mvp", headRepositoryOwnerLogin: "octocat", }, @@ -6694,6 +6703,14 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { "@{upstream}", ])).stdout.trim(); expect(upstreamRef).toBe("fork-seed/feature/pr-fork"); + if (privateHead) { + const route = yield* runGit( + result.worktreePath!, + ["config", "--get", `branch.${result.branch}.pushRemote`], + true, + ); + expect(route.stdout.trim()).toBe("fork-seed"); + } expect(upstreamRef.startsWith("origin/")).toBe(false); expect( (yield* runGit(result.worktreePath as string, [ diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index d661a83aa1669..a131b6a927433 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -317,6 +317,7 @@ interface PullRequestHeadRemoteInfo { isCrossRepository?: boolean | undefined; headRepositoryNameWithOwner?: string | null | undefined; headRepositoryOwnerLogin?: string | null | undefined; + requiresPrivateHeadPush?: true | undefined; } interface BranchHeadContext { @@ -767,8 +768,10 @@ function toPullRequestHeadRemoteInfo(pr: { isCrossRepository?: boolean | undefined; headRepositoryNameWithOwner?: string | null | undefined; headRepositoryOwnerLogin?: string | null | undefined; + requiresPrivateHeadPush?: true | undefined; }): PullRequestHeadRemoteInfo { return { + ...(pr.requiresPrivateHeadPush === true ? { requiresPrivateHeadPush: true } : {}), ...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}), ...(pr.headRepositoryNameWithOwner !== undefined ? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner } @@ -1067,6 +1070,32 @@ export const make = Effect.gen(function* () { return host ? { host } : {}; }; + const ensureNamedPullRequestHeadRemote = Effect.fn("GitManager.ensureNamedPullRequestHeadRemote")( + function* ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + repositoryNameWithOwner: string, + ) { + const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({ + cwd, + repository: repositoryNameWithOwner, + ...pullRequestHostOptions(pullRequest.url), + }); + const originRemoteUrl = yield* readRemoteUrl(cwd, "origin"); + const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url; + const preferredRemoteName = + pullRequest.headRepositoryOwnerLogin?.trim() || + repositoryNameWithOwner.split("/")[0]?.trim() || + "fork"; + return yield* gitCore.ensureRemote({ + cwd, + preferredName: preferredRemoteName, + url: remoteUrl, + ...(pullRequest.requiresPrivateHeadPush === true ? { pushOnlyToFetchUrl: true } : {}), + }); + }, + ); + const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")( function* ( cwd: string, @@ -1094,22 +1123,11 @@ export const make = Effect.gen(function* () { return; } - const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({ + const remoteName = yield* ensureNamedPullRequestHeadRemote( cwd, - repository: repositoryNameWithOwner, - ...pullRequestHostOptions(pullRequest.url), - }); - const originRemoteUrl = yield* readRemoteUrl(cwd, "origin"); - const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url; - const preferredRemoteName = - pullRequest.headRepositoryOwnerLogin?.trim() || - repositoryNameWithOwner.split("/")[0]?.trim() || - "fork"; - const remoteName = yield* gitCore.ensureRemote({ - cwd, - preferredName: preferredRemoteName, - url: remoteUrl, - }); + pullRequest, + repositoryNameWithOwner, + ); yield* gitCore.fetchRemoteTrackingBranch({ cwd, @@ -1208,22 +1226,11 @@ export const make = Effect.gen(function* () { return; } - const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({ + const remoteName = yield* ensureNamedPullRequestHeadRemote( cwd, - repository: repositoryNameWithOwner, - ...pullRequestHostOptions(pullRequest.url), - }); - const originRemoteUrl = yield* readRemoteUrl(cwd, "origin"); - const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url; - const preferredRemoteName = - pullRequest.headRepositoryOwnerLogin?.trim() || - repositoryNameWithOwner.split("/")[0]?.trim() || - "fork"; - const remoteName = yield* gitCore.ensureRemote({ - cwd, - preferredName: preferredRemoteName, - url: remoteUrl, - }); + pullRequest, + repositoryNameWithOwner, + ); yield* gitCore.fetchRemoteBranch({ cwd, @@ -3713,6 +3720,28 @@ export const make = Effect.gen(function* () { localBranches, ); + const pinPrivateHeadPush = Effect.fn("GitManager.pinPrivateHeadPush")(function* () { + if (pullRequestWithRemoteInfo.requiresPrivateHeadPush !== true) return; + const repository = resolveHeadRepositoryNameWithOwner(pullRequestWithRemoteInfo); + if (repository === null) { + return yield* new GitManagerError({ + operation: "preparePullRequestThread", + cwd: input.cwd, + detail: "The host did not identify the private repository for this pull request head.", + }); + } + const remote = yield* ensureNamedPullRequestHeadRemote( + input.cwd, + pullRequestWithRemoteInfo, + repository, + ); + yield* gitCore.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localPullRequestBranch}.pushRemote`, + value: remote, + }); + }); + // Git refuses to move checked-out branches; advance reused checkouts from inside their worktree. const reuseExistingWorktree = Effect.fn("reuseExistingWorktree")(function* ( worktreePath: string, @@ -3728,6 +3757,8 @@ export const make = Effect.gen(function* () { }; } + yield* pinPrivateHeadPush(); + // Capture upstream before its forced fetch so rewritten heads remain distinguishable from local commits. const upstreamCommitBeforeFetch = yield* gitCore .resolveCommit({ cwd: worktreePath, revision: "@{upstream}" }) @@ -3944,6 +3975,8 @@ export const make = Effect.gen(function* () { "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", }); } + yield* pinPrivateHeadPush(); + // Materializing would force this branch onto the head. if (existingBranchBeforeFetch !== null) { let isOnPullRequestHead = false; diff --git a/packages/contracts/src/sourceControl.ts b/packages/contracts/src/sourceControl.ts index 3138c3985a4aa..fb4ffea39d43c 100644 --- a/packages/contracts/src/sourceControl.ts +++ b/packages/contracts/src/sourceControl.ts @@ -35,6 +35,7 @@ export const ChangeRequest = Schema.Struct({ isCrossRepository: Schema.optional(Schema.Boolean), headRepositoryNameWithOwner: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), headRepositoryOwnerLogin: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + requiresPrivateHeadPush: Schema.optional(Schema.Literal(true)), }); export type ChangeRequest = typeof ChangeRequest.Type; diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index 39d639de5f699..68587701986bc 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -50,6 +50,19 @@ export function effectiveAccount( ); } +function privateCompanionName( + repository: string | null, + head: string | null | undefined, + visibility: string | undefined, +): string | null { + if (visibility === "public" || repository === null || typeof head !== "string") return null; + const prefix = repository.toLowerCase() + ".private"; + const key = head.toLowerCase(); + return key.startsWith(prefix) && /^(?:-[2-9]|-[1-9]\d+)?$/.test(key.slice(prefix.length)) + ? head + : null; +} + const decodeUser = Schema.decodeEffect(Schema.fromJsonString(Json.SourceUser)); const authAccounts = (accounts: ReturnType) => @@ -306,11 +319,14 @@ export const make = Effect.gen(function* () { target: Target, pull: Json.SourcePullDetail, ): ChangeRequest & { readonly visibility: string | undefined } => { - const headRepository = pull.headRepo ?? target.repository; + const requiresPrivateHeadPush = + pull.visibility === "private" || + privateCompanionName(target.repository, pull.headRepo, pull.visibility) !== null; + const headRepository = pull.headRepo ?? (requiresPrivateHeadPush ? null : target.repository); const headBranch = Json.headBranchName(pull.head); // A pull request synced from a GitHub fork names its head only by its pull ref. const crossRepository = - headRepository.toLowerCase() !== target.repository.toLowerCase() || + headRepository?.toLowerCase() !== target.repository.toLowerCase() || headBranch.startsWith("refs/"); const updatedAt = pull.mergedAt ?? pull.createdAt; return { @@ -328,7 +344,8 @@ export const make = Effect.gen(function* () { isCrossRepository: crossRepository, visibility: pull.visibility, headRepositoryNameWithOwner: headRepository, - headRepositoryOwnerLogin: headRepository.split("/")[0] ?? null, + headRepositoryOwnerLogin: headRepository?.split("/")[0] ?? null, + ...(requiresPrivateHeadPush ? { requiresPrivateHeadPush: true as const } : {}), }; }; @@ -537,18 +554,11 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - const companionName = pull.headRepositoryNameWithOwner; - const companionPrefix = - pullRepository === null ? null : pullRepository.toLowerCase() + ".private"; - const normalizedHead = companionName?.toLowerCase(); - const companion = - pull.visibility !== "public" && - typeof companionName === "string" && - companionPrefix !== null && - normalizedHead?.startsWith(companionPrefix) && - /^(?:-[2-9]|-[1-9]\d+)?$/.test(normalizedHead.slice(companionPrefix.length)) - ? companionName - : null; + const companion = privateCompanionName( + pullRepository, + pull.headRepositoryNameWithOwner, + pull.visibility, + ); if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; const remoteBranch = { From b294b213a30f8caa1c2f117d1ec1e1ed8e055eff Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Tue, 24 Nov 2026 10:35:16 -0300 Subject: [PATCH 76/87] test(git): await lane startup before releasing processes --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d3d1a4baa27b8..ae6db71c62067 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -196,8 +196,8 @@ it.effect("runs background Git in its own lane so user commands never queue behi concurrency: "unbounded", }).pipe(Effect.forkChild); - yield* TestClock.adjust("2 seconds"); - const started = yield* Queue.takeAll(starts); + const started = yield* Queue.takeBetween(starts, 6, 6); + yield* Deferred.succeed(gate, undefined); assert.deepStrictEqual([...started].toSorted(), [ "background", "background", @@ -206,7 +206,6 @@ it.effect("runs background Git in its own lane so user commands never queue behi "foreground", "foreground", ]); - yield* Deferred.succeed(gate, undefined); assert.equal((yield* Fiber.join(background)).length, 12); assert.equal((yield* Fiber.join(foreground)).length, 4); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), From fbb2b1facf090e867e06821b9ff9331729c0f1b7 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Tue, 24 Nov 2026 11:31:21 -0300 Subject: [PATCH 77/87] fix(server): preserve feedback when resuming a provider turn [skip ci] Keep the session busy through the resumed turn while forwarding the fork feedback mode to the adapter. Tooling: GPT-6.2 Sol via Codex. --- .../orchestration-v2/ProviderSessionManager.test.ts | 4 +++- .../src/orchestration-v2/ProviderSessionManager.ts | 13 +++---------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 9cd43318e92a4..8ec04216e65e2 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -2298,7 +2298,9 @@ const idleReleaseAroundRun = (start: "compactThread" | "resumeTurn") => yield* Fiber.join(terminal); yield* TestClock.adjust("2 seconds"); assert.isFalse(yield* manager.isLive(providerSessionId)); - }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000 }))); + }).pipe( + Effect.provide(layerTest({ state, idleTimeoutMs: 1_000, resumeTurn: () => Effect.void })), + ); }); it.effect.each([ diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 2da1ef1c02582..f0be00fa56163 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2614,14 +2614,6 @@ export const layerWithOptions = ( ); return { ...runtime, - ...(resumeTurn === undefined - ? {} - : { - resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - agentFeedbackMode.pipe( - Effect.flatMap((agentFeedback) => resumeTurn({ ...input, agentFeedback })), - ), - }), // Pi replaces its session snapshot as metadata changes. get providerSession() { return runtime.providerSession; @@ -2757,12 +2749,13 @@ export const layerWithOptions = ( turnMetrics("send", input.modelSelection.model), ), ), - ...(runtime.resumeTurn === undefined + ...(resumeTurn === undefined ? {} : { resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => busyTurn(input, () => - runtime.resumeTurn!(input).pipe( + agentFeedbackMode.pipe( + Effect.flatMap((agentFeedback) => resumeTurn({ ...input, agentFeedback })), turnMetrics("resume", input.modelSelection.model), ), ), From 96b2abe9406b0895faa23e0b594f11d15d9e59a2 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Tue, 24 Nov 2026 11:32:38 -0300 Subject: [PATCH 78/87] fix(antigravity): preserve fork MCP approvals [skip ci] Require the proxy tool title and server metadata to agree before automatically approving a T3 MCP request. Tooling: GPT-6.2 Sol via Codex. --- .../src/provider/acp/AntigravityAcpSupport.ts | 21 +++++++------------ 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 31439ea03277f..ffaa7cfa9151d 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -183,10 +183,6 @@ export function antigravitySessionMode( return modeId === "yolo" || modeId === "auto_edit" ? "default" : modeId; } -// Only calls that name T3's server: before agy 1.5.8 "Running " names no server, so another -// MCP server's tool of the same name would pass. -const ANTIGRAVITY_T3_MCP_TITLE = /^Run mcp_t3-code_(?[A-Za-z0-9_]+)\??$/; - // call_mcp_tool is the one call whose rawInput names a server and tool; in every other call // rawInput is the tool's own arguments. const ANTIGRAVITY_PROXIED_MCP_TITLE = /^MCP Tool (?[A-Za-z0-9_]+)\??$/; @@ -194,17 +190,14 @@ const ANTIGRAVITY_PROXIED_MCP_TITLE = /^MCP Tool (?[A-Za-z0-9_]+)\??$/; function isAntigravityT3McpRequest(request: EffectAcpSchema.RequestPermissionRequest): boolean { const title = request.toolCall.title?.trim() ?? ""; const rawInput = unknownRecord(request.toolCall.rawInput); - const proxiedTool = ANTIGRAVITY_PROXIED_MCP_TITLE.exec(title)?.groups?.tool; - if (proxiedTool !== undefined) { - return ( - rawInput?.ServerName === "t3-code" && - rawInput.ToolName === proxiedTool && - T3_MCP_TOOL_NAMES.has(proxiedTool) - ); - } if (typeof rawInput?.CommandLine === "string") return false; - const tool = ANTIGRAVITY_T3_MCP_TITLE.exec(title)?.groups?.tool; - return tool !== undefined && T3_MCP_TOOL_NAMES.has(tool); + const proxiedTool = ANTIGRAVITY_PROXIED_MCP_TITLE.exec(title)?.groups?.tool; + return ( + proxiedTool !== undefined && + rawInput?.ServerName === "t3-code" && + rawInput.ToolName === proxiedTool && + T3_MCP_TOOL_NAMES.has(proxiedTool) + ); } export function antigravityPermissionDisposition( From ed2d9ea18fb2f67d2b530360fc13930818322c65 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Tue, 24 Nov 2026 11:43:47 -0300 Subject: [PATCH 79/87] fix(git): strip Git line endings from upstream refs [skip ci] Preserve Unicode whitespace in ref names while removing the Git output line terminator so status and push resolve the upstream consistently. Tooling: GPT-6.2 Sol via Codex. --- apps/server/src/vcs/GitVcsDriverCore.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 80e4477841913..19b41fdd5d6af 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1482,7 +1482,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", revision], true, - ); + ).pipe(Effect.map(trimAsciiWhitespace)); return fullRef === "" || fullRef === revision ? null : fullRef; }); From 875ae5d617d2e85343a574c5a932f3509710044d Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Wed, 25 Nov 2026 10:39:15 -0300 Subject: [PATCH 80/87] feat(fork): merge and delete the source branch [skip ci] --- .../PullRequestMergeControls.tsx | 33 +- apps/mobile/src/i18n/translations/de.json | 5 +- apps/mobile/src/i18n/translations/en.json | 5 +- apps/mobile/src/i18n/translations/es.json | 5 +- apps/mobile/src/i18n/translations/fr.json | 5 +- apps/mobile/src/i18n/translations/ja.json | 5 +- apps/mobile/src/i18n/translations/ko.json | 5 +- apps/mobile/src/i18n/translations/pt-BR.json | 5 +- apps/mobile/src/i18n/translations/ru.json | 5 +- apps/mobile/src/i18n/translations/sv.json | 5 +- apps/mobile/src/i18n/translations/zh.json | 5 +- .../PostMergeBranchCleanup.test.ts | 138 ++++++++ .../src/pullRequest/PostMergeBranchCleanup.ts | 323 ++++++++++++++++++ .../src/pullRequest/PullRequestService.ts | 122 ++++++- apps/server/src/server.ts | 8 + .../pullRequest/PullRequestDetailActions.tsx | 48 ++- ...stDetailPanel.permissions.browser.test.tsx | 50 +++ .../pullRequest/PullRequestDetailPanel.tsx | 33 ++ apps/web/src/i18n/translations/de.json | 6 +- apps/web/src/i18n/translations/en.json | 6 +- apps/web/src/i18n/translations/es.json | 6 +- apps/web/src/i18n/translations/fr.json | 6 +- apps/web/src/i18n/translations/ja.json | 6 +- apps/web/src/i18n/translations/ko.json | 6 +- apps/web/src/i18n/translations/pt-BR.json | 6 +- apps/web/src/i18n/translations/ru.json | 6 +- apps/web/src/i18n/translations/sv.json | 6 +- apps/web/src/i18n/translations/zh.json | 6 +- packages/contracts/src/pullRequest.ts | 4 + .../server/AzureDevOpsPullRequestProvider.ts | 1 + .../src/server/azureDevOpsPullRequestJson.ts | 3 + .../server/BitbucketPullRequestProvider.ts | 4 +- .../src/server/GitCafePullRequestProvider.ts | 5 +- .../src/server/GitLabPullRequestCli.ts | 10 +- .../src/server/gitLabMergeRequestJson.ts | 4 + 35 files changed, 841 insertions(+), 55 deletions(-) create mode 100644 apps/server/src/pullRequest/PostMergeBranchCleanup.test.ts create mode 100644 apps/server/src/pullRequest/PostMergeBranchCleanup.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx index 6ff51d23cf3b2..43b1f76848140 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx @@ -165,9 +165,13 @@ export function PullRequestMergeControls(props: { permissions.canWrite && canPerformPullRequestAction(pr, autoAction); + const canMergeAndDelete = + canMergeSingle && !stack.stack && pr.capabilities.mergeAndDeleteBranch === true && !!pr.headSha; + const perform = async ( action: "merge" | "enable-auto-merge" | "disable-auto-merge", shownHeadSha: string | undefined, + deleteBranchAfterMerge?: true, ) => { if ( pending.current || @@ -182,6 +186,7 @@ export function PullRequestMergeControls(props: { input: { ...target.input, action, + ...(deleteBranchAfterMerge ? { deleteBranchAfterMerge } : {}), // A merge lands the head on screen and refuses one that moved; a stack pins its other layers. ...(action !== "disable-auto-merge" && shownHeadSha ? { expectedHeadSha: shownHeadSha } @@ -231,6 +236,9 @@ export function PullRequestMergeControls(props: { stack.refresh(); pending.current = false; setBusy(false); + if (AsyncResult.isSuccess(response) && response.value?.branchCleanupNotice) { + Dialog.alert(gt("Branch cleanup incomplete"), response.value.branchCleanupNotice); + } if (AsyncResult.isFailure(response)) { const cause = squashAtomCommandFailure(response); Dialog.alert( @@ -355,6 +363,9 @@ export function PullRequestMergeControls(props: { state: id === method ? ("on" as const) : ("off" as const), attributes: { disabled: !canMerge && !canAutoMerge }, })), + ...(canMergeAndDelete + ? [{ id: "merge-and-delete", title: gt("Merge and delete branch") }] + : []), ...(canAutoMerge ? [ { @@ -373,7 +384,27 @@ export function PullRequestMergeControls(props: { if (selected) { setSelectedMethod(selected); void savePreferences({ pullRequestMergeMethod: selected }); - } else if (id === autoAction && canAutoMerge) confirm(autoAction); + } else if (id === autoAction && canAutoMerge) { + confirm(autoAction); + } else if (id === "merge-and-delete" && canMergeAndDelete) { + Dialog.alert( + gt("Merge and delete branch"), + gt( + "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed.", + { + branch: pr.headBranch, + }, + ), + [ + { text: gt("Cancel"), style: "cancel" }, + { + text: gt("Merge and delete branch"), + style: "destructive", + onPress: () => void perform("merge", pr.headSha, true), + }, + ], + ); + } }} /> {permissions.connected && !status && reason ? ( diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index b6c76e7afcfcb..fe51d24d228f3 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5702,5 +5702,8 @@ "1a1beecff68a6e61": "Google-Konto bestätigen", "99451a5d2d40440f": "Zurückgezogen von {by}.", "3ee30a50b70fffab": "Zurückgezogen von {by}: {reason}", - "201490988858b511": "zurückgezogen von {by}" + "201490988858b511": "zurückgezogen von {by}", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 49ea2c92c4c32..19232f9875919 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5704,5 +5704,8 @@ "1a1beecff68a6e61": "Verify Google account", "99451a5d2d40440f": "Withdrawn by {by}.", "3ee30a50b70fffab": "Withdrawn by {by}: {reason}", - "201490988858b511": "withdrawn by {by}" + "201490988858b511": "withdrawn by {by}", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index b4b8aed972ac0..c291ec7d0862b 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5696,5 +5696,8 @@ "1a1beecff68a6e61": "Verificar cuenta de Google", "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", - "201490988858b511": "retirada por {by}" + "201490988858b511": "retirada por {by}", + "9ba1231a060b65d8": "Limpieza de la rama incompleta", + "a38ef558d90eebd0": "Fusionar y eliminar la rama", + "d5ae55bd8630fd5d": "¿Fusionar y eliminar la rama de origen {branch} del repositorio remoto y de este proyecto? Si su worktree de T3 Code está limpio, también se eliminará." } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 46f34fd868c01..464986e67835a 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5696,5 +5696,8 @@ "1a1beecff68a6e61": "Vérifier le compte Google", "99451a5d2d40440f": "Retirée par {by}.", "3ee30a50b70fffab": "Retirée par {by} : {reason}", - "201490988858b511": "retirée par {by}" + "201490988858b511": "retirée par {by}", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 7fbb23bd3cd3c..7e3862d16f034 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5673,5 +5673,8 @@ "1a1beecff68a6e61": "Google アカウントを確認", "99451a5d2d40440f": "{by} が取り下げました。", "3ee30a50b70fffab": "{by} が取り下げました: {reason}", - "201490988858b511": "{by} が取り下げ" + "201490988858b511": "{by} が取り下げ", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 50f693f6b7f4d..89204d37ae7a5 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5680,5 +5680,8 @@ "1a1beecff68a6e61": "Google 계정 확인", "99451a5d2d40440f": "{by}에서 철회했습니다.", "3ee30a50b70fffab": "{by}에서 철회했습니다: {reason}", - "201490988858b511": "{by}에서 철회함" + "201490988858b511": "{by}에서 철회함", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index ff83c02bb2e99..2e8aa5ec5145d 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5696,5 +5696,8 @@ "1a1beecff68a6e61": "Verificar conta Google", "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", - "201490988858b511": "retirada por {by}" + "201490988858b511": "retirada por {by}", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 63528b1e20da3..4e60c60af92de 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5776,5 +5776,8 @@ "1a1beecff68a6e61": "Подтвердить аккаунт Google", "99451a5d2d40440f": "Отозван: {by}.", "3ee30a50b70fffab": "Отозван ({by}): {reason}", - "201490988858b511": "отозван: {by}" + "201490988858b511": "отозван: {by}", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 616644fea60b9..ef2d6cdd8fdd1 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5702,5 +5702,8 @@ "1a1beecff68a6e61": "Verifiera Google-konto", "99451a5d2d40440f": "Återkallad av {by}.", "3ee30a50b70fffab": "Återkallad av {by}: {reason}", - "201490988858b511": "återkallad av {by}" + "201490988858b511": "återkallad av {by}", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 290c3a26b2e14..9bff1e9baed11 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5683,5 +5683,8 @@ "1a1beecff68a6e61": "验证 Google 账户", "99451a5d2d40440f": "已由 {by} 撤回。", "3ee30a50b70fffab": "已由 {by} 撤回:{reason}", - "201490988858b511": "已由 {by} 撤回" + "201490988858b511": "已由 {by} 撤回", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "a38ef558d90eebd0": "Merge and delete branch", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/server/src/pullRequest/PostMergeBranchCleanup.test.ts b/apps/server/src/pullRequest/PostMergeBranchCleanup.test.ts new file mode 100644 index 0000000000000..75c25dd7df521 --- /dev/null +++ b/apps/server/src/pullRequest/PostMergeBranchCleanup.test.ts @@ -0,0 +1,138 @@ +import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; + +import * as ServerConfig from "../config.ts"; +import { ProjectionStoreV2 } from "../orchestration-v2/ProjectionStore.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; +import { TaskFolderStore } from "../workspace/TaskFolderStore.ts"; +import * as Cleanup from "./PostMergeBranchCleanup.ts"; + +const layer = Cleanup.layer.pipe( + Layer.provideMerge(GitVcsDriver.layer), + Layer.provide(VcsProcess.layer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-merge-delete-" })), + Layer.provide( + Layer.mergeAll( + Layer.mock(ServerSettingsService)({ getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS) }), + Layer.mock(ProjectionStoreV2)({ + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 0, + threads: [], + archivedThreads: [], + }), + }), + Layer.mock(TaskFolderStore)({ findContaining: () => Effect.succeed(null) }), + ), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), +); + +const fixture = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const config = yield* ServerConfig.ServerConfig; + const driver = yield* GitVcsDriver.GitVcsDriver; + const cleanup = yield* Cleanup.PostMergeBranchCleanup; + const repo = yield* fs.makeTempDirectoryScoped({ prefix: "t3-merge-delete-repo-" }); + const url = path.join(repo, "remote.git"); + const cwd = path.join(repo, "checkout"); + const git = (...args: string[]) => driver.execute({ operation: "test.cleanup", cwd, args }); + yield* fs.makeDirectory(cwd); + yield* git("init", "--bare", "--initial-branch=main", url); + yield* git("init", "--initial-branch=main"); + yield* git( + "-c", + "user.name=test", + "-c", + "user.email=test@example.com", + "commit", + "--allow-empty", + "-m", + "base", + ); + yield* git("remote", "add", "origin", url); + yield* git("push", "origin", "main"); + yield* git("branch", "feature"); + yield* git("push", "-u", "origin", "feature"); + const sha = (yield* git("rev-parse", "feature")).stdout.trim(); + const target = { branch: "feature", remote: "origin", url, sha }; + const worktree = path.join( + yield* fs.realPath(config.baseDir), + "worktrees", + path.basename(repo), + "feature", + ); + yield* git("worktree", "add", worktree, "feature"); + return { + git, + worktree, + remove: cleanup.remove(cwd, target), + target, + cwd, + cleanup, + local: git("for-each-ref", "refs/heads/feature"), + remote: git("ls-remote", "--heads", "origin", "refs/heads/feature"), + worktrees: git("worktree", "list", "--porcelain"), + }; +}); + +it.layer(layer)("PostMergeBranchCleanup", (it) => { + it.effect("removes the exact remote and local branch and its clean managed worktree", () => + Effect.gen(function* () { + const repo = yield* fixture; + yield* repo.remove; + assert.equal((yield* repo.remote).stdout, ""); + assert.equal((yield* repo.local).stdout, ""); + assert.isFalse((yield* repo.worktrees).stdout.includes(repo.worktree)); + yield* repo.remove; + }), + ); + + it.effect("keeps a dirty worktree and its local branch after removing the remote ref", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const repo = yield* fixture; + yield* fs.writeFileString(repo.worktree + "/new.txt", "keep me"); + const error = yield* repo.remove.pipe(Effect.flip); + assert.include(error.detail, "Git refused"); + assert.equal((yield* repo.remote).stdout, ""); + assert.include((yield* repo.local).stdout, repo.target.sha); + assert.include((yield* repo.worktrees).stdout, repo.worktree); + }), + ); + + it.effect("keeps a remote branch that advanced and refuses the default branch", () => + Effect.gen(function* () { + const repo = yield* fixture; + yield* repo.git( + "-c", + "user.name=test", + "-c", + "user.email=test@example.com", + "commit", + "--allow-empty", + "-m", + "new", + ); + yield* repo.git("push", "origin", "HEAD:refs/heads/feature"); + const error = yield* repo.remove.pipe(Effect.flip); + assert.include(error.detail, "received new commits"); + assert.notEqual((yield* repo.remote).stdout, ""); + assert.include((yield* repo.local).stdout, repo.target.sha); + const defaultError = yield* repo.cleanup + .remove(repo.cwd, { ...repo.target, branch: "main" }) + .pipe(Effect.flip); + assert.include(defaultError.detail, "default branch"); + }), + ); +}); diff --git a/apps/server/src/pullRequest/PostMergeBranchCleanup.ts b/apps/server/src/pullRequest/PostMergeBranchCleanup.ts new file mode 100644 index 0000000000000..a52e0e1d512b3 --- /dev/null +++ b/apps/server/src/pullRequest/PostMergeBranchCleanup.ts @@ -0,0 +1,323 @@ +import { PullRequestOperationError } from "@t3tools/contracts"; +import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition"; +import { canonicalRepositoryPath, parseGitRemoteRepository } from "@t3tools/shared/git"; +import type { ProviderChangeRequestDetail } from "@t3tools/source-control-core/server/PullRequestProvider"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import { ProjectionStoreV2 } from "../orchestration-v2/ProjectionStore.ts"; +import { TaskFolderStore } from "../workspace/TaskFolderStore.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { GitVcsDriver } from "../vcs/GitVcsDriver.ts"; +import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; +import type { SupportedProject } from "./PullRequestService.ts"; + +type ChangeRequest = Pick< + ProviderChangeRequestDetail, + "headBranch" | "baseBranch" | "headSha" | "headRepositoryNameWithOwner" | "state" +>; + +export interface Target { + readonly branch: string; + readonly sha: string; + readonly remote: string; + readonly url: string; +} + +const fail = (detail: string) => + new PullRequestOperationError({ operation: "mergeAndDeleteBranch", detail }); + +const fullCommit = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i; + +function projectLocator(project: SupportedProject, request: ChangeRequest) { + const identity = project.project.repositoryIdentity; + if ( + !identity?.locator || + sourceControlDefinitions.canonicalRepositoryKey(identity.canonicalKey) !== project.remote || + request.state !== "open" || + request.headBranch === request.baseBranch || + request.headRepositoryNameWithOwner === null || + !request.headSha || + !fullCommit.test(request.headSha) + ) { + return null; + } + return identity.locator; +} + +export const make = Effect.gen(function* () { + const git = yield* GitVcsDriver; + const tasks = yield* TaskFolderStore; + const threads = yield* ProjectionStoreV2; + const isManagedWorktree = yield* makeIsManagedWorktreePath; + + const execute = (cwd: string, args: readonly string[]) => + git.execute({ + operation: "mergeAndDeleteBranch", + cwd, + args, + timeoutMs: 30_000, + env: { GIT_TERMINAL_PROMPT: "0" }, + }); + + const remoteState = Effect.fn("PostMergeBranchCleanup.remoteState")(function* ( + cwd: string, + url: string, + ref: string, + ) { + const { stdout } = yield* execute(cwd, ["ls-remote", "--symref", "--", url, "HEAD", ref]); + const entries = stdout + .trimEnd() + .split("\n") + .map((line) => line.split("\t")); + return { + defaultRef: entries + .find(([value, name]) => name === "HEAD" && value?.startsWith("ref: refs/heads/"))?.[0] + ?.slice(5), + sha: entries.find(([, name]) => name === ref)?.[0]?.toLowerCase(), + }; + }); + + const prepare = Effect.fn("PostMergeBranchCleanup.prepare")(function* ( + project: SupportedProject, + request: ChangeRequest, + ) { + const locator = projectLocator(project, request); + if (locator === null || !request.headSha) { + return yield* fail("This change request does not identify a source branch on this project."); + } + const cwd = project.project.workspaceRoot; + const branch = request.headBranch; + const ref = "refs/heads/" + branch; + const sha = request.headSha.toLowerCase(); + yield* execute(cwd, ["check-ref-format", ref]).pipe( + Effect.mapError(() => fail("The host returned an invalid source branch name.")), + ); + + const checkoutRemote = parseGitRemoteRepository(locator.remoteUrl); + if (checkoutRemote === null) { + return yield* fail("Could not identify the Git remote of this checkout."); + } + const headRepository = request.headRepositoryNameWithOwner; + const expectedPath = headRepository + ? canonicalRepositoryPath(headRepository) + : checkoutRemote.path; + const remotes = + headRepository && + expectedPath !== checkoutRemote.path && + expectedPath !== canonicalRepositoryPath(project.repository) + ? (yield* execute(cwd, ["remote"]).pipe( + Effect.mapError(() => fail("Could not read the Git remotes of this checkout.")), + )).stdout + .trim() + .split("\n") + : [locator.remoteName]; + + for (const remote of remotes) { + if (remote.length === 0) continue; + const push = yield* execute(cwd, ["remote", "get-url", "--push", "--all", "--", remote]).pipe( + Effect.option, + ); + if (Option.isNone(push)) continue; + const urls = push.value.stdout.trimEnd().split("\n"); + const url = urls[0]; + if (url === undefined || urls.length !== 1) continue; + const destination = parseGitRemoteRepository(url); + if ( + destination === null || + parseGitRemoteHost(url)?.host !== parseGitRemoteHost(locator.remoteUrl)?.host || + destination.path !== + (remote === locator.remoteName && + expectedPath === canonicalRepositoryPath(project.repository) + ? checkoutRemote.path + : expectedPath) + ) + continue; + + const state = yield* remoteState(cwd, url, ref).pipe( + Effect.mapError(() => + fail("Could not verify the source branch using the configured Git credentials."), + ), + ); + if (state.defaultRef === undefined || state.defaultRef === ref) { + return yield* fail("The source repository's default branch must be verified and kept."); + } + if (state.sha !== sha) { + return yield* fail( + "The Git remote does not have the reviewed source commit. Refresh the change request first.", + ); + } + return { branch, sha, remote, url } satisfies Target; + } + return yield* fail( + "Configure a Git push remote for the change request's source repository first.", + ); + }); + + const removeLocal = Effect.fn("PostMergeBranchCleanup.removeLocal")(function* ( + cwd: string, + target: Target, + ref: string, + ) { + const readLocal = () => + execute(cwd, [ + "for-each-ref", + "--format=%(objectname)%00%(refname)%00%(upstream:remotename)%00%(upstream:remoteref)", + ref, + ]).pipe( + Effect.map(({ stdout }) => + stdout + .split("\n") + .map((line) => line.split("\0")) + .find(([, name]) => name === ref), + ), + ); + const local = yield* readLocal(); + if (local === undefined) return; + if (local[0] !== target.sha || (local[2] && (local[2] !== target.remote || local[3] !== ref))) { + return yield* fail( + "Remote branch removed. The local branch has different commits or tracks a different branch.", + ); + } + const listWorktrees = () => + execute(cwd, ["worktree", "list", "--porcelain", "-z"]).pipe( + Effect.map(({ stdout }) => stdout.split("\0\0").map((record) => record.split("\0"))), + ); + const records = yield* listWorktrees(); + const projectRoot = (yield* execute(cwd, ["rev-parse", "--show-toplevel"])).stdout.trimEnd(); + for (const [index, record] of records.entries()) { + if (!record.includes("branch " + ref)) continue; + const worktree = record[0]?.slice("worktree ".length); + if ( + worktree === undefined || + !record.includes("HEAD " + target.sha) || + index === 0 || + worktree === projectRoot || + !(yield* isManagedWorktree(worktree)) + ) { + return yield* fail( + "Remote branch removed. The local branch is checked out outside a matching T3 Code worktree.", + ); + } + const active = yield* threads + .getShellSnapshot({ worktreePath: worktree, activityOnly: true }) + .pipe( + Effect.mapError(() => + fail("Remote branch removed. T3 Code could not verify whether the worktree is in use."), + ), + ); + if (active.threads.length > 0) { + return yield* fail("Remote branch removed. An active thread is using the worktree."); + } + const taskError = () => + fail("Remote branch removed. T3 Code could not complete task folder cleanup."); + const task = yield* tasks.findContaining(worktree).pipe(Effect.mapError(taskError)); + if ( + task !== null && + (task.root !== worktree || task.projectPath !== worktree || task.repositories.length > 0) + ) { + return yield* fail( + "Remote branch removed. The worktree belongs to a task folder with its own layout or other repositories.", + ); + } + yield* git + .removeWorktree({ cwd, path: worktree, force: false }) + .pipe( + Effect.mapError(() => + fail( + "Remote branch removed. The local branch and worktree were kept because Git refused to remove the worktree.", + ), + ), + ); + if (task !== null) yield* tasks.remove(task.root).pipe(Effect.mapError(taskError)); + } + if ((yield* listWorktrees()).some((record) => record.includes("branch " + ref))) { + return yield* fail("Remote branch removed. The local branch is still checked out."); + } + // Delete only the reviewed object, including when the merge was squashed or rebased. + yield* execute(cwd, ["update-ref", "--no-deref", "-d", ref, target.sha]); + }); + + const remove = Effect.fn("PostMergeBranchCleanup.remove")(function* ( + cwd: string, + target: Target, + ) { + const ref = "refs/heads/" + target.branch; + yield* Effect.gen(function* () { + const configured = yield* execute(cwd, [ + "remote", + "get-url", + "--push", + "--all", + "--", + target.remote, + ]); + if (configured.stdout.trimEnd() !== target.url) { + return yield* fail( + "The merge completed. The Git push remote changed, so the branches were kept.", + ); + } + const state = yield* remoteState(cwd, target.url, ref); + if (state.defaultRef === undefined || state.defaultRef === ref) { + return yield* fail( + "The merge completed. The source repository's default branch could not be ruled out.", + ); + } + if (state.sha !== undefined) { + if (state.sha !== target.sha) { + return yield* fail( + "The merge completed. The remote source branch received new commits and was kept.", + ); + } + yield* execute(cwd, [ + "push", + "--porcelain", + "--no-follow-tags", + "--no-mirror", + "--no-recurse-submodules", + "--force-with-lease=" + ref + ":" + target.sha, + "--", + target.remote, + ":" + ref, + ]); + if ((yield* remoteState(cwd, target.url, ref)).sha !== undefined) { + return yield* fail( + "The merge completed. The source branch is present on the remote, so the local branch was kept.", + ); + } + } + }).pipe( + Effect.catchTags({ + GitCommandError: () => + fail( + "The merge completed. Git could not confirm removal of the remote branch, so the local branch was kept.", + ), + }), + ); + yield* removeLocal(cwd, target, ref).pipe( + Effect.catchTags({ + GitCommandError: () => + fail( + "Remote branch removed. Git could not complete cleanup of the local branch and worktree.", + ), + }), + Effect.ensuring(git.invalidateRefs(cwd)), + ); + }); + + return { + canPrepare: (project: SupportedProject, request: ChangeRequest) => + projectLocator(project, request) !== null, + prepare, + remove, + }; +}); + +export class PostMergeBranchCleanup extends Context.Service< + PostMergeBranchCleanup, + Effect.Success +>()("t3/pullRequest/PostMergeBranchCleanup") {} + +export const layer = Layer.effect(PostMergeBranchCleanup, make); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index cb6c62a9b9058..d9c986079f35d 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -99,6 +99,7 @@ import { type PullRequestProviderApi, PullRequestProviderError, } from "@t3tools/source-control-core/server/PullRequestProvider"; +import * as PostMergeBranchCleanup from "./PostMergeBranchCleanup.ts"; import * as PullRequestReadCache from "./PullRequestReadCache.ts"; import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts"; import * as ViewedFiles from "./pullRequestViewedFiles.ts"; @@ -789,6 +790,9 @@ export const make = Effect.gen(function* () { const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository; const readCache = yield* PullRequestReadCache.PullRequestReadCache; const clock = yield* Clock.Clock; + const branchCleanup = Option.getOrUndefined( + yield* Effect.serviceOption(PostMergeBranchCleanup.PostMergeBranchCleanup), + ); /** * Where each project's remote is served from, by the remote's recognised base URL: a remote no @@ -1956,7 +1960,12 @@ export const make = Effect.gen(function* () { ).pipe( Effect.map(([{ value: changeRequest, observedAt }, viewer]): PullRequestDetail => ({ provider: project.api.kind, - capabilities: project.api.capabilities, + capabilities: { + ...project.api.capabilities, + ...(branchCleanup?.canPrepare(project, changeRequest) + ? { mergeAndDeleteBranch: true } + : {}), + }, projectId: project.project.id, projectTitle: project.project.title, workspaceRoot: project.project.workspaceRoot, @@ -2207,6 +2216,10 @@ export const make = Effect.gen(function* () { type ActionOutcome = { readonly repository: string; readonly summary: PullRequestSummary | undefined; + readonly cleanup?: { + readonly project: SupportedProject; + readonly target: PostMergeBranchCleanup.Target; + }; }; const runAction = ( input: PullRequestActionInput, @@ -2320,14 +2333,44 @@ export const make = Effect.gen(function* () { ), ) : Effect.succeed(false); - return pinnedHead(project, input, "runAction").pipe( - Effect.flatMap((expectedHeadSha) => - Effect.map(mergeSettings, (removeAgentCreditsOnMerge) => ({ - expectedHeadSha, - removeAgentCreditsOnMerge, - })), - ), - Effect.flatMap(({ expectedHeadSha, removeAgentCreditsOnMerge }) => + const head = input.deleteBranchAfterMerge + ? Effect.gen(function* () { + if ( + branchCleanup === undefined || + input.action !== "merge" || + input.stackNumber !== undefined || + input.expectedHeadSha === undefined || + input.replyWithSummary !== true || + input.projectId !== project.project.id + ) { + return yield* new PullRequestOperationError({ + operation: "runAction", + detail: + "Branch cleanup requires a single change request and its reviewed head on this project.", + }); + } + const detail = yield* project.api + .getChangeRequest({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + }) + .pipe(Effect.mapError(toPullRequestError("runAction"))); + if (!detail.headSha || !isHeadSha(detail.headSha, input.expectedHeadSha)) { + return yield* new PullRequestOperationError({ + operation: "runAction", + detail: "The source branch changed. Review its latest commits first.", + }); + } + const target = yield* branchCleanup.prepare(project, detail); + return { expectedHeadSha: target.sha, cleanup: { project, target } }; + }) + : pinnedHead(project, input, "runAction").pipe( + Effect.map((expectedHeadSha) => ({ expectedHeadSha, cleanup: undefined })), + ); + return Effect.all([head, mergeSettings]).pipe( + Effect.flatMap(([{ expectedHeadSha, cleanup }, removeAgentCreditsOnMerge]) => project.api .runAction({ cwd: project.project.workspaceRoot, @@ -2355,6 +2398,7 @@ export const make = Effect.gen(function* () { Effect.mapError(toPullRequestError("runAction")), observeRead, Effect.map(({ value, observedAt }) => ({ + ...(cleanup === undefined ? {} : { cleanup }), repository: project.repositoryKey !== null ? input.repository.trim() @@ -4038,7 +4082,7 @@ export const make = Effect.gen(function* () { const ref = yield* canonicalRef(input); yield* readCache.invalidate(refScope(ref)); // A refusal (e.g. a merge conflict) means readers hold stale state, so refresh them too. - const { repository, summary } = yield* runAction(input).pipe( + const { repository, summary, cleanup } = yield* runAction(input).pipe( Effect.ensuring(readCache.invalidate(refScope(ref))), Effect.tapError(() => Effect.suspend(() => { @@ -4051,13 +4095,31 @@ export const make = Effect.gen(function* () { bumpRefEpoch({ ...ref, repository }); listingsEpoch = ++epochCounter; yield* SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); + let reply = summary; if (input.action === "merge") { // A successful merge action can merely enqueue the PR or enable auto-merge. const merged = summary?.state === "merged" ? summary : null; const confirmed = - merged?.mergedAt != null + merged?.mergedAt != null && (cleanup === undefined || merged.headSha !== undefined) ? merged - : yield* summaryUncached({ ...input, repository }).pipe( + : yield* ( + cleanup === undefined + ? summaryUncached({ ...input, repository }) + : cleanup.project.api + .getChangeRequest({ + cwd: cleanup.project.project.workspaceRoot, + host: cleanup.project.host, + repository: cleanup.project.repository, + number: input.number, + }) + .pipe( + Effect.mapError(toPullRequestError("mergeAndDeleteBranch")), + observeRead, + Effect.map(({ value, observedAt }) => + toSummary(cleanup.project, value, observedAt), + ), + ) + ).pipe( Effect.map((reread) => (reread.state === "merged" ? reread : merged)), Effect.catch((error) => Effect.logWarning("failed to confirm pull request merge", { error }).pipe( @@ -4073,8 +4135,42 @@ export const make = Effect.gen(function* () { mergedAt: confirmed.mergedAt ?? DateTime.formatIso(yield* DateTime.now), }); } + if (cleanup !== undefined && branchCleanup !== undefined) { + const { project, target } = cleanup; + const current = + confirmed ?? + summary ?? + (yield* summaryUncached({ ...input, repository }).pipe( + Effect.mapError( + () => + new PullRequestOperationError({ + operation: "mergeAndDeleteBranch", + detail: + "The merge request was sent, but the host did not confirm the outcome. The branches were kept.", + }), + ), + )); + let branchCleanupNotice: string | undefined; + if (current.state !== "merged") { + branchCleanupNotice = "The host has not confirmed the merge. The branch was kept."; + } else if ( + current.headBranch !== target.branch || + current.headSha?.toLowerCase() !== target.sha + ) { + branchCleanupNotice = + "The host did not confirm the reviewed commit as merged. The branch was kept."; + } else { + branchCleanupNotice = yield* branchCleanup + .remove(project.project.workspaceRoot, target) + .pipe( + Effect.as(undefined), + Effect.catch((error) => Effect.succeed(error.detail)), + ); + } + reply = branchCleanupNotice === undefined ? current : { ...current, branchCleanupNotice }; + } } - return input.replyWithSummary === true ? summary : undefined; + return input.replyWithSummary === true ? reply : undefined; }); const credentialCached = diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d3d5c6c34ee71..5e1ec92b5cab9 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -61,6 +61,7 @@ import * as CloudSpeech from "./speech/CloudSpeech.ts"; import { speechHttpApiLayer } from "./speech/http.ts"; import { speechStreamRouteLayer } from "./speech/stream.ts"; import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts"; +import * as PostMergeBranchCleanup from "./pullRequest/PostMergeBranchCleanup.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; import * as IssueService from "./issue/IssueService.ts"; import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; @@ -460,6 +461,13 @@ const layerRepositoryIdentityResolver = Layer.effect( ).pipe(Layer.provide(layerSourceControlProviderRegistry), Layer.provide(ProcessRunner.layer)); const layerPullRequestService = PullRequestService.layer.pipe( + Layer.provide( + PostMergeBranchCleanup.layer.pipe( + Layer.provide( + Layer.mergeAll(GitVcsDriver.layer, TaskFolderStore.layer, ProjectionStoreV2.layer), + ), + ), + ), Layer.provide(PullRequestProviderRegistry.layer), Layer.provide(PullRequestFilesViewed.layer), Layer.provide(PullRequestReadCache.layer), diff --git a/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx b/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx index b4953100deccc..884741b614752 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx @@ -13,6 +13,7 @@ import { cn } from "~/lib/utils"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; +import { ButtonGroup } from "../ui/group"; import { Menu, MenuItem, @@ -213,6 +214,7 @@ export function PullRequestPrimaryAction({ statePresentation, pendingAction, perform, + onMergeAndDelete, resolveConflicts, }: { pullRequestKey: string; @@ -226,6 +228,7 @@ export function PullRequestPrimaryAction({ statePresentation: ReturnType | null; pendingAction: PullRequestAction | null; perform: PerformPullRequestAction; + onMergeAndDelete?: ((method: PullRequestMergeMethod) => void) | undefined; resolveConflicts: ReactNode; }) { const gt = useGT(); @@ -340,9 +343,9 @@ export function PullRequestPrimaryAction({ })} /> ) : primaryAction === "merge" ? ( - + + - - } - label={ - mergeBlockedReason ?? - (pendingAction === "merge" - ? gt("Merging...") - : inlineConfirm.isArmed("merge") - ? gt("Confirm merge?") - : selectedMergeMethodLabel) - } - /> + } + label={ + mergeBlockedReason ?? + (pendingAction === "merge" + ? gt("Merging...") + : inlineConfirm.isArmed("merge") + ? gt("Confirm merge?") + : selectedMergeMethodLabel) + } + /> + {onMergeAndDelete ? ( +

    + + } + > + + + + onMergeAndDelete(selectedMergeMethod)}> + Merge and delete branch + + + + ) : null} + ) : (primaryAction === "merged" || primaryAction === "closed") && statePresentation !== null ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx index c2f33a40e5937..0f33f3404bff3 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx @@ -74,6 +74,7 @@ vi.mock(import("~/state/use-atom-command"), async (original) => ({ useAtomCommand: (() => command) as never, })); +import { ConfirmDialogHost } from "~/components/ConfirmDialogHost"; import { createWorkspaceFocusController, workspaceAreaProps } from "~/lib/workspaceFocus"; import { PullRequestDetailPanel } from "./PullRequestDetailPanel"; @@ -297,3 +298,52 @@ it("keeps a screen reader's place when scrolling the description condenses the h // A programmatic focus() pulls the screen reader's browse cursor back to the header. expect(moves).not.toHaveBeenCalled(); }); + +it("asks before sending the pinned merge-and-delete action", async () => { + setup(); + shown.detail = { + ...detail, + headSha: "a".repeat(40), + mergeability: "mergeable", + mergeCapabilities: { merge: false, squash: true, rebase: false }, + capabilities: { + ...detail.capabilities, + actions: ["merge"], + mergeMethods: ["squash"], + mergeAndDeleteBranch: true, + }, + viewerPermissions: { ...detail.viewerPermissions, actions: ["merge"] }, + }; + command.mockResolvedValue({ _tag: "Success", value: undefined }); + const style = document.createElement("style"); + style.textContent = appCss; + document.head.append(style); + using _style = { [Symbol.dispose]: () => style.remove() }; + await using screen = await render( + <> + + {panel()} + , + ); + const choose = async () => { + await screen.getByRole("button", { name: "Merge options" }).click(); + await page.getByRole("menuitem", { name: "Merge and delete branch" }).click(); + }; + await choose(); + await page.getByRole("button", { name: "Cancel", exact: true }).click(); + expect(command).not.toHaveBeenCalled(); + await choose(); + await page.getByRole("button", { name: "Confirm", exact: true }).click(); + await vi.waitFor(() => + expect(command).toHaveBeenCalledWith( + expect.objectContaining({ + input: expect.objectContaining({ + action: "merge", + mergeMethod: "squash", + deleteBranchAfterMerge: true, + expectedHeadSha: shown.detail?.headSha, + }), + }), + ), + ); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 5678533a97ebc..3f49d8c074af1 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -904,6 +904,7 @@ export function PullRequestDetailPanel({ action: PullRequestAction, method?: PullRequestMergeMethod, updateMethod?: PullRequestUpdateMethod, + deleteBranchAfterMerge?: true, ) => { onActed?.(action, "sent"); const result = await runAction({ @@ -912,6 +913,7 @@ export function PullRequestDetailPanel({ ...reference, action, ...mergeHeadPin(action, shownHeadSha), + ...(deleteBranchAfterMerge ? { deleteBranchAfterMerge } : {}), ...(method ? { mergeMethod: method } : {}), ...(updateMethod ? { updateMethod } : {}), }, @@ -945,6 +947,13 @@ export function PullRequestDetailPanel({ ), }); } + if (deleteBranchAfterMerge && result.value?.branchCleanupNotice) { + toastManager.add({ + type: "warning", + title: gt("Branch cleanup incomplete"), + description: result.value.branchCleanupNotice, + }); + } if (action === "delete-branch") { toastManager.add({ type: "success", title: m(msg("Branch deleted")) }); } @@ -969,6 +978,25 @@ export function PullRequestDetailPanel({ return finishAction(action, method, updateMethod); }; + const mergeAndDeleteBranch = async (method: PullRequestMergeMethod) => { + if (!canWriteSourceControl || pendingAction !== null || detail === null) return; + setPendingAction("merge"); + const confirmed = await readLocalApi()?.dialogs.confirm( + gt( + "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed.", + { + branch: detail.headBranch, + }, + ), + { variant: "destructive" }, + ); + if (confirmed) { + await finishAction("merge", method, undefined, true); + } else { + setPendingAction(null); + } + }; + const performCommentAction = async (body: string, action: "close" | "reopen") => { if (!canWriteSourceControl || pendingAction !== null) return { commentPosted: false }; setPendingAction(action); @@ -1693,6 +1721,11 @@ export function PullRequestDetailPanel({ statePresentation={statePresentation} pendingAction={pendingAction} perform={perform} + onMergeAndDelete={ + detail.capabilities.mergeAndDeleteBranch && shownHeadSha && !stackOwnsMerge + ? mergeAndDeleteBranch + : undefined + } resolveConflicts={resolveConflictsControl} /> {checkoutControl} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7eb8c833696b7..95a7d8c5d6a41 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -13071,5 +13071,9 @@ "201490988858b511": "zurückgezogen von {by}", "99451a5d2d40440f": "Zurückgezogen von {by}.", "3ee30a50b70fffab": "Zurückgezogen von {by}: {reason}", - "92e129bf413a1220": "zurückgezogen" + "92e129bf413a1220": "zurückgezogen", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 1ead86f182c6d..988a9e83870be 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -13082,5 +13082,9 @@ "201490988858b511": "withdrawn by {by}", "99451a5d2d40440f": "Withdrawn by {by}.", "3ee30a50b70fffab": "Withdrawn by {by}: {reason}", - "92e129bf413a1220": "withdrawn" + "92e129bf413a1220": "withdrawn", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 614f377ec4dce..c6e9037701f9f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -13066,5 +13066,9 @@ "201490988858b511": "retirada por {by}", "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", - "92e129bf413a1220": "retirada" + "92e129bf413a1220": "retirada", + "824af344a2f36c1b": "Opciones de fusión", + "435c2a50997dea7b": "Fusionar y eliminar la rama", + "9ba1231a060b65d8": "Limpieza de la rama incompleta", + "d5ae55bd8630fd5d": "¿Fusionar y eliminar la rama de origen {branch} del repositorio remoto y de este proyecto? Si su worktree de T3 Code está limpio, también se eliminará." } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 6524e8111689d..3424c66870cff 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -13071,5 +13071,9 @@ "201490988858b511": "retirée par {by}", "99451a5d2d40440f": "Retirée par {by}.", "3ee30a50b70fffab": "Retirée par {by} : {reason}", - "92e129bf413a1220": "retirée" + "92e129bf413a1220": "retirée", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 9ecd6329d983a..b3dcbc83dea8b 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -13007,5 +13007,9 @@ "201490988858b511": "{by} が取り下げ", "99451a5d2d40440f": "{by} が取り下げました。", "3ee30a50b70fffab": "{by} が取り下げました: {reason}", - "92e129bf413a1220": "取り下げ済み" + "92e129bf413a1220": "取り下げ済み", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index f80975b14dfdf..39c797d578b70 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -13005,5 +13005,9 @@ "201490988858b511": "{by}에서 철회함", "99451a5d2d40440f": "{by}에서 철회했습니다.", "3ee30a50b70fffab": "{by}에서 철회했습니다: {reason}", - "92e129bf413a1220": "철회됨" + "92e129bf413a1220": "철회됨", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5463e5c668c76..b63c04e4e2475 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -13071,5 +13071,9 @@ "201490988858b511": "retirada por {by}", "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", - "92e129bf413a1220": "retirada" + "92e129bf413a1220": "retirada", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 93071eb85010f..65d7f88312d8e 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -13071,5 +13071,9 @@ "201490988858b511": "отозван: {by}", "99451a5d2d40440f": "Отозван: {by}.", "3ee30a50b70fffab": "Отозван ({by}): {reason}", - "92e129bf413a1220": "отозван" + "92e129bf413a1220": "отозван", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c7c0c24b3ead8..562c0a5e8fa25 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -13078,5 +13078,9 @@ "201490988858b511": "återkallad av {by}", "99451a5d2d40440f": "Återkallad av {by}.", "3ee30a50b70fffab": "Återkallad av {by}: {reason}", - "92e129bf413a1220": "återkallad" + "92e129bf413a1220": "återkallad", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 9505b2bf0684e..7e1f309e1db8a 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13085,5 +13085,9 @@ "201490988858b511": "已由 {by} 撤回", "99451a5d2d40440f": "已由 {by} 撤回。", "3ee30a50b70fffab": "已由 {by} 撤回:{reason}", - "92e129bf413a1220": "已撤回" + "92e129bf413a1220": "已撤回", + "824af344a2f36c1b": "Merge options", + "435c2a50997dea7b": "Merge and delete branch", + "9ba1231a060b65d8": "Branch cleanup incomplete", + "d5ae55bd8630fd5d": "Merge and delete the source branch {branch} from the remote and this project? Its clean T3 Code worktree will also be removed." } diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 311831de776f5..36c13c161076f 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -297,6 +297,7 @@ export const PullRequestCapabilities = Schema.Struct({ actions: ForwardCompatibleArray(PullRequestAction), mergeMethods: ForwardCompatibleArray(PullRequestMergeMethod), deleteBranch: Schema.optional(Schema.Boolean), + mergeAndDeleteBranch: Schema.optional(Schema.Literal(true)), /** * Absent where it cannot at all, which is every host that has not said otherwise — so a * provider that says nothing offers nothing. @@ -519,6 +520,8 @@ export const PullRequestPreview = Schema.Struct({ export type PullRequestPreview = typeof PullRequestPreview.Type; export const PullRequestSummary = Schema.Struct({ + /** Returned by merge actions when Git cleanup could not complete. */ + branchCleanupNotice: Schema.optional(TrimmedNonEmptyString), provider: SourceControlProviderKind, projectId: ProjectId, repository: TrimmedNonEmptyString, @@ -856,6 +859,7 @@ export const PullRequestActionInput = Schema.Struct({ updateMethod: Schema.optional(PullRequestUpdateMethod), /** Opt-in, because older clients decode the action's success as void and reject a summary. */ replyWithSummary: Schema.optional(Schema.Literal(true)), + deleteBranchAfterMerge: Schema.optional(Schema.Literal(true)), }); export type PullRequestActionInput = typeof PullRequestActionInput.Type; diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts index b329561c36360..0529e102aa49a 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts @@ -137,6 +137,7 @@ function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeReq url: pullRequest.url, author: pullRequest.author, headBranch: pullRequest.headBranch, + ...(pullRequest.fromFork ? { headRepositoryNameWithOwner: null } : {}), baseBranch: pullRequest.baseBranch, state: pullRequest.state, isDraft: pullRequest.isDraft, diff --git a/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts b/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts index 40bdcf72c7fbd..692c07a604a31 100644 --- a/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts +++ b/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts @@ -51,6 +51,7 @@ const RawPullRequestSchema = Schema.Struct({ /** `az repos pr list` fills this; `az repos pr show` returns null. */ labels: Schema.optional(Schema.NullOr(Schema.Array(RawLabelSchema))), sourceRefName: TrimmedNonEmptyString, + forkSource: Schema.optional(Schema.NullOr(Schema.Unknown)), targetRefName: TrimmedNonEmptyString, creationDate: TrimmedNonEmptyString, closedDate: Schema.optional(Schema.NullOr(Schema.String)), @@ -153,6 +154,7 @@ export interface AzureDevOpsPullRequest { readonly url: string; readonly author: PullRequestActor | null; readonly headBranch: string; + readonly fromFork?: true; readonly baseBranch: string; readonly state: PullRequestState; readonly isDraft: boolean; @@ -264,6 +266,7 @@ function toPullRequest( url, author: toActor(raw.createdBy), headBranch, + ...(raw.forkSource == null ? {} : { fromFork: true }), baseBranch, state: toState(raw), isDraft: raw.isDraft ?? false, diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts index a9faa2d4b48fc..028867b095499 100644 --- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts +++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts @@ -99,9 +99,7 @@ function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeReque author: pullRequest.author, headBranch: pullRequest.headBranch, ...(pullRequest.headSha ? { headSha: pullRequest.headSha } : {}), - ...(pullRequest.headRepositoryNameWithOwner - ? { headRepositoryNameWithOwner: pullRequest.headRepositoryNameWithOwner } - : {}), + headRepositoryNameWithOwner: pullRequest.headRepositoryNameWithOwner, baseBranch: pullRequest.baseBranch, state: pullRequest.state, isDraft: pullRequest.isDraft, diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts index a193b90e98627..00376586c966e 100644 --- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts +++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts @@ -1032,9 +1032,8 @@ export const make = Effect.gen(function* () { autoMergeEnabled: merging, headSha: pull.headOid, body: pull.description ?? "", - ...(pull.sourceRepo === null - ? {} - : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }), + headRepositoryNameWithOwner: + pull.sourceRepo === null ? null : `${pull.sourceRepo.owner}/${pull.sourceRepo.name}`, additions: changes?.additions ?? 0, deletions: changes?.deletions ?? 0, changedFiles: changes?.changedFiles ?? 0, diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index a2f4c4f38ddf9..2052f8f208563 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -2349,7 +2349,15 @@ export const make = Effect.gen(function* () { [mergeRequestDetail(input), labelPermission(input)], { concurrency: 2 }, ); - const labeled = { ...read, labels: colourLabels(read.labels, extras.labels) }; + const source = + read.maintainerCanModify === undefined || input.maintainerEdits === false + ? null + : yield* orWhenUnanswered(sourceBranch(input), null); + const labeled = { + ...read, + ...(source?.sourceProject ? { headRepositoryNameWithOwner: source.sourceProject } : {}), + labels: colourLabels(read.labels, extras.labels), + }; const viewerCanEditLabels = extras.viewerCanEditLabels; // Only a closed or merged merge request offers its branch for deletion, and only an open // fork's has maintainer edits to change, so each extra read is skipped elsewhere. diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 4678b3f50c54d..d7ef8a2571295 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -229,6 +229,7 @@ export interface GitLabMergeRequestListItem { } export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem { + readonly headRepositoryNameWithOwner?: string | null; readonly body: string; readonly changedFiles: number; readonly mergedAt: string | null; @@ -547,6 +548,9 @@ function toDetail(raw: Schema.Schema.Type): GitLab : raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true; return { ...listItem, + ...(raw.source_project_id != null && raw.source_project_id === raw.target_project_id + ? {} + : { headRepositoryNameWithOwner: null }), body: raw.description ?? "", changedFiles: toChangedFiles(raw.changes_count), mergedAt: trimmed(raw.merged_at), From 0278ccc56a05cfbe092490b9bdb6a89863d0f533 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Thu, 26 Nov 2026 10:59:25 -0300 Subject: [PATCH 81/87] feat(threads): show command and task progress in thread lists --- .../features/threads/thread-list-v2-items.tsx | 66 +++++++- apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + .../orchestration-v2/CommandOutputHub.test.ts | 16 +- .../src/orchestration-v2/CommandOutputHub.ts | 28 +++- .../src/orchestration-v2/ProjectionStore.ts | 143 ++++++++++++++---- .../src/orchestration-v2/ShellStream.test.ts | 12 +- .../src/orchestration-v2/ShellStream.ts | 7 +- .../ThreadInsightsQuery.test.ts | 12 ++ apps/web/src/components/ChatView.tsx | 7 +- .../src/components/Sidebar.browser.test.tsx | 96 ++++++++++++ .../components/chat/CommandProgressMeter.tsx | 20 ++- .../src/components/chat/useCommandProgress.ts | 6 - .../sidebar/SidebarThreadProgress.tsx | 50 ++++++ .../components/sidebar/SidebarThreadRow.tsx | 30 +++- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + packages/client-runtime/src/state/models.ts | 4 + packages/contracts/src/orchestrationV2.ts | 11 ++ 35 files changed, 460 insertions(+), 68 deletions(-) create mode 100644 apps/web/src/components/sidebar/SidebarThreadProgress.tsx diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index c6b0f0d535211..0d7481ac3fd71 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -13,6 +13,9 @@ import { RowPressable } from "../../components/ui/RowPressable"; import { CustomSnoozeSheet } from "./CustomSnoozeSheet"; import { appAtomRegistry } from "../../state/atom-registry"; import { threadArrangementOpenAtom } from "../../state/thread-order"; +import { Progress } from "../../components/ui/Progress"; +import { orchestrationEnvironment } from "../../state/orchestration"; +import { useEnvironmentQuery } from "../../state/query"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; import { useVisibleSecondClock } from "./use-visible-second-clock"; @@ -28,6 +31,7 @@ import { } from "@t3tools/client-runtime/state/models"; import { AuthOrchestrationOperateScope, + formatCommandProgress, type EnvironmentId, type EnvironmentMachineKind, } from "@t3tools/contracts"; @@ -896,7 +900,24 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { const timeLabel = pendingSync ? gt("Waiting to sync") : props.timeLabel && m(props.timeLabel); const snoozeWakeLabelText = props.snoozeWakeLabelText === undefined ? undefined : m(props.snoozeWakeLabelText); - const rowAccessibilityLabel = threadListV2RowAccessibilityLabel( + const commandProgress = useEnvironmentQuery( + thread.hasRunningCommand + ? orchestrationEnvironment.v2.commandProgress({ + environmentId: thread.environmentId, + input: { threadId: thread.id }, + }) + : null, + ); + const command = commandProgress.data?.items.find((item) => item.commandLabel); + const tasks = thread.taskProgress; + const taskLabel = tasks + ? gt("{total, plural, one {{done}/{total} task} other {{done}/{total} tasks}}", { + done: tasks.completed, + total: tasks.total, + }) + : null; + const commandCount = command ? formatCommandProgress(command) : null; + const baseAccessibilityLabel = threadListV2RowAccessibilityLabel( { title: thread.title, variant, @@ -917,6 +938,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { m, ); + const rowAccessibilityLabel = [ + baseAccessibilityLabel, + command?.commandLabel, + commandCount, + taskLabel, + ] + .filter(Boolean) + .join(", "); const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); const markThreadUnread = useAtomCommand(threadEnvironment.markUnread, { reportFailure: false }); const handleAcknowledgeWoke = useCallback(() => { @@ -1379,6 +1408,39 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { ? primaryAction.swipeHint : primaryAction.swipeSnoozeHint; + const progressTint = selected + ? selectedThreadRowColors.mutedForegroundClassName + : rowAppearance.mutedForegroundClassName; + const progressLines = (command || tasks) && ( + + {command ? ( + + + + {command.commandLabel} + + + {commandCount} + + ) : null} + {tasks ? ( + + {taskLabel} + + ) : null} + + ); const titleTextInset = props.project ? projectIconSize + 8 : 0; const cardContent = ( <> @@ -1506,6 +1568,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { )}
    + {progressLines ? {progressLines} : null} {props.searchMatch ? ( ) : null} + {progressLines} {props.searchMatch ? ( { const hub = yield* CommandOutputHub.CommandOutputHub; const threadId = yield* seedThread; yield* writeCommandItem(threadId, { status: "running", output: "snapshot 12/20" }); + const store = yield* ProjectionStore.ProjectionStoreV2; + assert.equal((yield* store.getThreadShell(threadId))?.hasRunningCommand, true); const frames = yield* Queue.unbounded(); yield* hub.subscribeProgress(threadId).pipe( Stream.runForEach((frame) => Queue.offer(frames, frame)), Effect.forkScoped, ); assert.deepStrictEqual(yield* Queue.take(frames), { - items: [{ itemId: ITEM_ID, completed: 12, total: 20 }], + items: [ + { itemId: ITEM_ID, commandLabel: "yes | head -n 1000000", completed: 12, total: 20 }, + ], }); yield* TestClock.adjust("1 second"); yield* writeCommandItem(threadId, { status: "running", output: "snapshot 15/20" }); assert.deepStrictEqual(yield* Queue.take(frames), { - items: [{ itemId: ITEM_ID, completed: 15, total: 20 }], + items: [ + { itemId: ITEM_ID, commandLabel: "yes | head -n 1000000", completed: 15, total: 20 }, + ], }); yield* TestClock.adjust("1 second"); yield* writeCommandItem(threadId, { @@ -341,6 +348,7 @@ layer("CommandOutputHub", (it) => { output: "snapshot 20/20", exitCode: 0, }); + assert.equal((yield* store.getThreadShell(threadId))?.hasRunningCommand, undefined); assert.deepStrictEqual(yield* Queue.take(frames), { items: [] }); }), ); @@ -401,7 +409,9 @@ layer("CommandOutputHub", (it) => { Effect.forkScoped, ); assert.deepEqual(yield* Queue.take(frames), { - items: [{ itemId: ITEM_ID, completed: 13, total: 20 }], + items: [ + { itemId: ITEM_ID, commandLabel: "yes | head -n 1000000", completed: 13, total: 20 }, + ], }); yield* writeRun("rolled_back"); yield* TestClock.adjust("1 second"); diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.ts b/apps/server/src/orchestration-v2/CommandOutputHub.ts index 7ef367286ecd4..b539a01c1cef6 100644 --- a/apps/server/src/orchestration-v2/CommandOutputHub.ts +++ b/apps/server/src/orchestration-v2/CommandOutputHub.ts @@ -2,7 +2,7 @@ import { isOrchestrationV2WorkActive, OrchestrationV2CommandOutputError, type OrchestrationV2CommandOutputFrame, - type OrchestrationV2CommandProgress, + OrchestrationV2CommandProgress, type OrchestrationV2CommandProgressFrame, type OrchestrationV2SubscribeCommandOutputInput, type OrchestrationV2TurnItem, @@ -75,6 +75,7 @@ export class CommandOutputHub extends Context.Service(); + const commandLabels = new Map(); const rolledBackRuns = new Set(); const rolledBackItems = new Set(); const itemRuns = new Map(); const observe = (item: OrchestrationV2TurnItem) => { if (item.type !== "command_execution") return; + if (item.status === "running") { + setBounded( + commandLabels, + item.id, + item.input.trim().replace(/\s+/g, " ").slice(0, 120), + MAX_LIVE_COMMANDS, + ); + } else { + commandLabels.delete(item.id); + } if (item.runId !== null && rolledBackRuns.has(item.runId)) { rolledBackItems.add(item.id); snapshots.delete(item.id); @@ -297,7 +309,7 @@ export const make = Effect.gen(function* () { Effect.forkScoped, ); yield* Queue.offer(wake, undefined); - let sent: string | undefined; + let sent: ReadonlyArray | undefined; let lastReadAt: number | undefined; const nextFrame = Effect.gen(function* () { while (true) { @@ -307,12 +319,12 @@ export const make = Effect.gen(function* () { yield* Effect.sleep(COMMAND_PROGRESS_FRAME_INTERVAL_MS - (now - lastReadAt)); } lastReadAt = yield* Clock.currentTimeMillis; - const items = threadProgress(threadId, snapshots, rolledBackItems); - const signature = items - .map((item) => `${item.itemId}:${item.completed}/${item.total}`) - .join("\n"); - if (signature !== sent) { - sent = signature; + const items = threadProgress(threadId, snapshots, rolledBackItems).map((item) => { + const commandLabel = commandLabels.get(item.itemId); + return commandLabel ? { ...item, commandLabel } : item; + }); + if (sent === undefined || !sameProgress(sent, items)) { + sent = items; return { items } satisfies OrchestrationV2CommandProgressFrame; } } diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 9fbf5e0288e07..22e5a59ced6b6 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1306,6 +1306,9 @@ type ShellThreadRow = { readonly pending_link_request_payload_json: string | null; readonly latest_user_message_at: string | null; readonly latest_user_authored_message_at: string | null; + readonly has_running_command: number; + readonly task_total: number | null; + readonly task_completed: number; readonly has_actionable_proposed_plan: number; }; @@ -1885,6 +1888,45 @@ const linkCardStillAsks = ( latestUserAuthoredMessageAt === null || !DateTime.isGreaterThan(latestUserAuthoredMessageAt, item.startedAt ?? item.updatedAt); +function latestTaskProgress(projection: OrchestrationV2ThreadProjection) { + const lists = projection.plans.filter( + (plan) => plan.kind === "todo_list" && plan.status !== "superseded", + ); + if (!lists.length) return undefined; + const runs = new Map( + projection.runs + .filter((run) => run.status !== "rolled_back") + .map((run) => [run.id, run.ordinal]), + ); + const items = new Map( + projection.turnItems + .filter((item) => item.type === "todo_list") + .map((item) => [item.planId, item]), + ); + const latest = lists + .filter((plan) => (plan.runId === null ? items.has(plan.id) : runs.has(plan.runId))) + .sort((left, right) => { + const runOrder = + (right.runId === null ? -1 : runs.get(right.runId)!) - + (left.runId === null ? -1 : runs.get(left.runId)!); + if (runOrder) return runOrder; + const a = items.get(left.id); + const b = items.get(right.id); + if (left.runId === null && right.runId === null) { + const startOrder = + (b?.startedAt ? DateTime.toEpochMillis(b.startedAt) : -1) - + (a?.startedAt ? DateTime.toEpochMillis(a.startedAt) : -1); + if (startOrder) return startOrder; + } + return (b?.ordinal ?? -1) - (a?.ordinal ?? -1) || right.id.localeCompare(left.id); + })[0]; + if (latest?.kind !== "todo_list" || latest.steps.length === 0) return undefined; + return { + completed: latest.steps.filter((step) => step.status === "completed").length, + total: latest.steps.length, + }; +} + export function threadShellFromProjection( projection: OrchestrationV2ThreadProjection, ): OrchestrationV2ThreadShell { @@ -1951,6 +1993,7 @@ export function threadShellFromProjection( pendingRuntimeRequest = waitingCard; } } + const taskProgress = latestTaskProgress(projection); const latestUserMessage = userMessages[0] ?? null; const pendingBackgroundTasks = derivePendingBackgroundWork({ latestRun, @@ -2026,6 +2069,14 @@ export function threadShellFromProjection( latestVisibleMessage: null, latestUserMessageAt: latestUserMessage?.updatedAt ?? null, latestUserAuthoredMessageAt, + ...(taskProgress && { taskProgress }), + ...(projection.turnItems.some( + (item) => + item.type === "command_execution" && + item.status === "running" && + (item.runId === null || + !projection.runs.some((run) => run.id === item.runId && run.status === "rolled_back")), + ) && { hasRunningCommand: true as const }), hasActionableProposedPlan: projection.plans.some( (plan) => plan.kind === "proposed_plan" && plan.status === "active", ), @@ -2158,6 +2209,8 @@ type ShellThreadState = { readonly pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null; readonly latestUserMessageAt: DateTime.Utc | null; readonly latestUserAuthoredMessageAt: DateTime.Utc | null; + readonly hasRunningCommand: boolean; + readonly taskProgress: OrchestrationV2ThreadShell["taskProgress"]; readonly hasActionableProposedPlan: boolean; readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"]; readonly providerInstanceHistory: OrchestrationV2ThreadShell["providerInstanceHistory"]; @@ -2339,6 +2392,8 @@ function shellFromState(input: { latestVisibleMessage: null, latestUserMessageAt: input.state.latestUserMessageAt, latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt, + ...(input.state.hasRunningCommand && { hasRunningCommand: true as const }), + ...(input.state.taskProgress && { taskProgress: input.state.taskProgress }), hasActionableProposedPlan: input.state.hasActionableProposedPlan, pendingBackgroundTasks: input.state.pendingBackgroundTasks, providerInstanceHistory: input.state.providerInstanceHistory, @@ -6091,32 +6146,33 @@ export const layer: Layer.Layer = "ProjectionStore.getLatestTodoList", )( function* (threadId) { - const owners = yield* latestTodoOwner(threadId); - if (owners[0] !== undefined) - return yield* getPlan(threadId, PlanId.make(owners[0].plan_id)); - // Native children have provider turns and items but no orchestration run. - const runless = yield* sql<{ readonly plan_id: string }>` - SELECT plan.plan_id - FROM orchestration_v2_projection_plans AS plan - INNER JOIN orchestration_v2_projection_turn_items AS item - ON item.thread_id = plan.thread_id - AND json_extract(item.payload_json, '$.planId') = plan.plan_id - WHERE plan.thread_id = ${threadId} AND plan.run_id IS NULL - AND plan.kind = 'todo_list' AND plan.status <> 'superseded' - AND item.type = 'todo_list' AND item.run_id IS NULL - ORDER BY json_extract(item.payload_json, '$.startedAt') DESC, - item.ordinal DESC, plan.plan_id DESC - LIMIT 1 + const [latest] = yield* sql<{ readonly plan_id: string | null }>` + SELECT ${latestTodoId(threadId)} AS plan_id `; - return runless[0] === undefined - ? undefined - : yield* getPlan(threadId, PlanId.make(runless[0].plan_id)); + return latest?.plan_id ? yield* getPlan(threadId, PlanId.make(latest.plan_id)) : undefined; }, (effect, threadId) => sql.withTransaction(effect).pipe(Effect.mapError(controlReadError(threadId))), ); - const latestTodoOwner = (threadId: ThreadId) => sql<{ + const latestTodoId = (threadId: ThreadId | Statement.Fragment) => sql`COALESCE( + (SELECT plan_id FROM (${latestTodoOwner(threadId)})), + ( + SELECT plan.plan_id + FROM orchestration_v2_projection_plans AS plan + INNER JOIN orchestration_v2_projection_turn_items AS todo_item + ON todo_item.thread_id = plan.thread_id + AND json_extract(todo_item.payload_json, '$.planId') = plan.plan_id + WHERE plan.thread_id = ${threadId} AND plan.run_id IS NULL + AND plan.kind = 'todo_list' AND plan.status <> 'superseded' + AND todo_item.type = 'todo_list' AND todo_item.run_id IS NULL + ORDER BY json_extract(todo_item.payload_json, '$.startedAt') DESC, + todo_item.ordinal DESC, plan.plan_id DESC + LIMIT 1 + ) + )`; + + const latestTodoOwner = (threadId: ThreadId | Statement.Fragment) => sql<{ readonly plan_id: string; readonly run_id: string; readonly provider_thread_id: string | null; @@ -6141,14 +6197,14 @@ export const layer: Layer.Layer = ) THEN ( -- Plan UUIDs cannot order replacements within a run. SELECT plan.plan_id - FROM orchestration_v2_projection_turn_items AS item + FROM orchestration_v2_projection_turn_items AS todo_item CROSS JOIN orchestration_v2_projection_plans AS plan - ON plan.plan_id = json_extract(item.payload_json, '$.planId') - WHERE item.run_id = owner.run_id AND item.thread_id = ${threadId} - AND item.type = 'todo_list' + ON plan.plan_id = json_extract(todo_item.payload_json, '$.planId') + WHERE todo_item.run_id = owner.run_id AND todo_item.thread_id = ${threadId} + AND todo_item.type = 'todo_list' AND plan.run_id = owner.run_id AND plan.thread_id = ${threadId} AND plan.kind = 'todo_list' AND plan.status <> 'superseded' - ORDER BY item.ordinal DESC + ORDER BY todo_item.ordinal DESC LIMIT 1 ) END, owner.plan_id) AS plan_id, owner.run_id, owner.provider_thread_id, ( @@ -8560,9 +8616,11 @@ export const layer: Layer.Layer = worktreePath, threadIds, listedOnly = false, + includeProgress = true, includeDeleted = false, }: ShellSnapshotOptions & { readonly listedOnly?: boolean; + readonly includeProgress?: boolean; // A retained fork still shows the history of a deleted source run. readonly includeDeleted?: boolean; } = {}, @@ -8710,8 +8768,29 @@ export const layer: Layer.Layer = WHERE plan.thread_id = t.thread_id AND plan.kind = 'proposed_plan' AND plan.status = 'active' - ) AS has_actionable_proposed_plan + ) AS has_actionable_proposed_plan, + ${ + includeProgress + ? sql`EXISTS ( + SELECT 1 FROM orchestration_v2_projection_turn_items command + WHERE command.thread_id = t.thread_id AND command.type = 'command_execution' + AND command.status = 'running' AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs owner WHERE owner.run_id = command.run_id + AND owner.status = 'rolled_back' + ) + ) AS has_running_command, + json_array_length(todo.payload_json, '$.steps') AS task_total, + (SELECT COUNT(*) FROM json_each(todo.payload_json, '$.steps') AS step + WHERE json_extract(step.value, '$.status') = 'completed') AS task_completed` + : sql`0 AS has_running_command, NULL AS task_total, 0 AS task_completed` + } FROM orchestration_v2_projection_threads t + ${ + includeProgress + ? sql`LEFT JOIN orchestration_v2_projection_plans todo + ON todo.plan_id = ${latestTodoId(sql`t.thread_id`)}` + : sql`` + } LEFT JOIN orchestration_v2_projection_runs active ON active.run_id = ( SELECT r.run_id FROM orchestration_v2_projection_runs r @@ -9387,6 +9466,10 @@ export const layer: Layer.Layer = ? null : DateTime.makeUnsafe(row.latest_user_message_at), latestUserAuthoredMessageAt, + hasRunningCommand: row.has_running_command === 1, + taskProgress: row.task_total + ? { completed: row.task_completed, total: row.task_total } + : undefined, hasActionableProposedPlan: row.has_actionable_proposed_plan === 1, pendingBackgroundTasks, providerInstanceHistory: providerInstanceHistoryForShell({ @@ -9587,10 +9670,10 @@ export const layer: Layer.Layer = const { threadRows, providerThreadRows, pendingTurnItemRows, sequenceRows } = yield* sql.withTransaction( Effect.gen(function* () { - const threadRows = yield* selectShellThreadRows( - threadId, - threadId === undefined ? { location: "active", listedOnly: true } : {}, - ); + const threadRows = yield* selectShellThreadRows(threadId, { + includeProgress: false, + ...(threadId === undefined && { location: "active", listedOnly: true }), + }); const ids = threadRows.map((row) => ThreadId.make(row.thread_id)); const providerThreadRows = ids.length === 0 ? [] : yield* selectShellProviderThreadRows(ids); diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index fbc610235dd01..2e5cfdb30561b 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -38,7 +38,7 @@ const emptyShellSnapshot = { } as OrchestrationV2ShellSnapshot; describe("subagent shell events", () => { - const stored = (threadId: string, type: string, itemType = "command_execution") => + const stored = (threadId: string, type: string, itemType = "file_change") => ({ event: { threadId, type, payload: { type: itemType } } }) as ApplicationStoredEvent; it("keeps regular threads and subagent state changes while omitting subagent transcript updates", () => { @@ -49,7 +49,13 @@ describe("subagent shell events", () => { expect( shouldPublishShellApplicationEvent(stored("child", "turn-item.updated"), subagents), ).toBe(false); - for (const itemType of ["secret_request", "link_request", "user_message"]) { + for (const itemType of [ + "secret_request", + "link_request", + "user_message", + "command_execution", + "todo_list", + ]) { expect( shouldPublishShellApplicationEvent( stored("child", "turn-item.updated", itemType), @@ -208,7 +214,7 @@ describe("omitIdleSubagentShells", () => { event: { threadId: "idle", type: "turn-item.updated", - payload: { type: "command_execution" }, + payload: { type: "file_change" }, }, } as ApplicationStoredEvent, omitted.subagentThreadIds, diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 5ee1005b16830..302189962c053 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -548,7 +548,12 @@ export function shouldPublishShellApplicationEvent( // Replay and the live tail overlap; keep known IDs so late events stay filtered. return true; } - if (event.type === "turn-item.updated" && turnItemCanChangeUserWait(event.payload)) { + if ( + event.type === "turn-item.updated" && + (turnItemCanChangeUserWait(event.payload) || + event.payload.type === "command_execution" || + event.payload.type === "todo_list") + ) { return true; } return !( diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts index 6f0a95c08aacb..0b71bb02a31ba 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -299,10 +299,17 @@ it.layer(layer)("ThreadInsightsQuery", (it) => { expect(yield* store.getLatestTodoList(root)).toBeUndefined(); const initial = yield* run(root, 1); yield* plan(initial, "z-first", false); + expect((yield* store.getThreadShell(root))?.taskProgress).toEqual({ completed: 0, total: 1 }); yield* plan(initial, "a-second", true); yield* plan(initial, "superseded", false, "superseded"); const rolledBack = yield* run(root, 2, "rolled_back"); yield* plan(rolledBack, "rolled-back", false); + expect((yield* store.getThreadShell(root))?.taskProgress).toEqual({ completed: 1, total: 1 }); + const projection = yield* store.getThreadProjection(root); + expect(ProjectionStore.threadShellFromProjection(projection).taskProgress).toEqual({ + completed: 1, + total: 1, + }); const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ threadId: root, }); @@ -319,6 +326,11 @@ it.layer(layer)("ThreadInsightsQuery", (it) => { yield* plan(owner, "z-first", false, "active", 1); yield* plan(owner, "a-latest", true, "active", 2); yield* plan(owner, "superseded-native", false, "superseded", 3); + const store = yield* ProjectionStore.ProjectionStoreV2; + expect((yield* store.getThreadShell(child))?.taskProgress).toEqual({ + completed: 1, + total: 1, + }); const query = yield* ThreadInsightsQuery.ThreadInsightsQuery; for (const threadId of [root, child]) { const result = yield* query.read({ threadId }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 9360e3e95e4c6..795747310e9ea 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -88,6 +88,7 @@ import { type ScopedThreadRef, type ThreadId, ProviderInteractionMode, + formatCommandProgress, resolveIdleCompaction, RuntimeMode, } from "@t3tools/contracts"; @@ -339,11 +340,7 @@ import { } from "./chat/PanelLayoutControls"; import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel"; -import { - formatCommandProgress, - truncateCommandLabel, - useCommandProgress, -} from "./chat/useCommandProgress"; +import { truncateCommandLabel, useCommandProgress } from "./chat/useCommandProgress"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { offersWorkspaceModes, diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 87f43d9f901f6..6b02057a89a47 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -10,6 +10,7 @@ import { type LocalApi, ProjectId, ThreadId, + TurnItemId, type ScopedThreadRef, } from "@t3tools/contracts"; import { isMacPlatform } from "@t3tools/shared/keybindings"; @@ -33,6 +34,7 @@ import { readLocalApi } from "../localApi"; import type { Project } from "../types"; import Sidebar from "./Sidebar"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; +import * as commandProgress from "./chat/useCommandProgress"; import { SortableThreadRow } from "./sidebar/SidebarThreadRow"; import { SidebarProvider } from "./ui/sidebar"; @@ -40,6 +42,7 @@ vi.mock(import("../state/olderSettledShelf"), async (original) => { const actual = await original(); return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) }; }); +vi.mock("./chat/useCommandProgress", { spy: true }); vi.mock("../state/entities", { spy: true }); vi.mock("../state/environments", { spy: true }); vi.mock("../hooks/useHandleNewThread", { spy: true }); @@ -264,6 +267,99 @@ function threadShell(projectId: ProjectId, index: number): EnvironmentThreadShel }); } +describe("sidebar progress", () => { + it.each([false, true])("updates a background chat in project mode %s", async (byProject) => { + using stack = new DisposableStack(); + const settings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(settings)); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + sidebarWorkingShelfEnabled: false, + boringSidebarEnabled: byProject, + }); + const repo = project("t3code"); + const open = threadShell(repo.id, 0); + const background = threadShell(repo.id, 1); + const running = { + ...background, + title: "Validate the sidebar", + hasRunningCommand: true, + taskProgress: { completed: 2, total: 4 }, + runtime: { + status: "running" as const, + activeRunId: null, + providerInstanceId: background.providerInstanceId, + providerName: null, + lastError: null, + updatedAt: background.updatedAt, + }, + }; + vi.mocked(useProjects).mockReturnValue([repo]); + vi.mocked(useQuietThreadShells).mockReturnValue([open, running]); + vi.mocked(useThreadRouteTarget).mockReturnValue({ + kind: "server", + threadRef: scopeThreadRef(open.environmentId, open.id), + }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: scopeProjectRef(repo.environmentId, repo.id), + defaultProjectFallbackReady: true, + handleNewThread: vi.fn(), + routeDraftId: null, + routeThreadRef: null, + }); + using _progress = vi + .spyOn(commandProgress, "useCommandProgress") + .mockImplementation((ref, enabled) => + enabled && ref?.threadId === background.id + ? [ + { + itemId: TurnItemId.make("cmd"), + commandLabel: "vp test run", + completed: 24, + total: 48, + }, + ] + : [], + ); + const style = document.createElement("style"); + style.textContent = appCss; + document.head.append(style); + stack.defer(() => style.remove()); + const tree = () => ( + + + + ); + await using screen = await render(tree()); + await expect.element(screen.getByText("vp test run").first()).toBeVisible(); + await expect.element(screen.getByText("24/48").first()).toBeVisible(); + await expect.element(screen.getByText("2/4 tasks").first()).toBeVisible(); + const card = screen + .getByText("vp test run") + .first() + .element() + .closest("[data-sidebar-row]")!; + card.style.width = "280px"; + const cardBounds = card.getBoundingClientRect(); + const counterBounds = screen.getByText("2/4 tasks").first().element().getBoundingClientRect(); + expect(counterBounds.bottom).toBeLessThanOrEqual(cardBounds.bottom); + vi.mocked(useQuietThreadShells).mockReturnValue([ + open, + { + ...running, + hasRunningCommand: false, + runtime: null, + taskProgress: { completed: 4, total: 4 }, + }, + ]); + await screen.rerender(tree()); + await expect.element(screen.getByText("vp test run")).not.toBeInTheDocument(); + await expect.element(screen.getByText("4/4 tasks").first()).toBeVisible(); + }); +}); + describe("sidebar render isolation", () => { // regression: #33100 Cmd+J re-rendered every sidebar row, which took hundreds of ms with many threads it("does not re-render thread rows when a quick Mod shortcut opens and focuses the terminal", async () => { diff --git a/apps/web/src/components/chat/CommandProgressMeter.tsx b/apps/web/src/components/chat/CommandProgressMeter.tsx index ded5ccc19b57a..132203aad9281 100644 --- a/apps/web/src/components/chat/CommandProgressMeter.tsx +++ b/apps/web/src/components/chat/CommandProgressMeter.tsx @@ -1,9 +1,14 @@ +import { cn } from "~/lib/utils"; import { useGT } from "gt-react"; -import type { OrchestrationV2CommandProgress } from "@t3tools/contracts"; +import { formatCommandProgress, type OrchestrationV2CommandProgress } from "@t3tools/contracts"; -import { formatCommandProgress } from "./useCommandProgress"; - -export function CommandProgressMeter({ progress }: { progress: OrchestrationV2CommandProgress }) { +export function CommandProgressMeter({ + progress, + compact = false, +}: { + progress: OrchestrationV2CommandProgress; + compact?: boolean; +}) { const gt = useGT(); return ( - + item.commandLabel); + const tasks = thread.taskProgress; + if (!command && !tasks) return null; + return ( + + {command ? ( + + + {command.commandLabel} + + + ) : null} + {tasks ? ( + + + {gt("{total, plural, one {{done}/{total} task} other {{done}/{total} tasks}}", { + done: tasks.completed, + total: tasks.total, + })} + + ) : null} + + ); +} diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 0be1b2cb3a127..cba7e5b53d55a 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -1,6 +1,7 @@ import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardTrigger } from "../ThreadHoverCard"; +import { SidebarThreadProgress } from "./SidebarThreadProgress"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; import { formatWorktreePathForDisplay } from "../../worktreeCleanup"; @@ -62,6 +63,7 @@ import { } from "lucide-react"; import { memo, + useId, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, @@ -731,6 +733,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP variant, variantAction, } = props; + const progressId = useId(); const threadRef = scopeThreadRef(thread.environmentId, thread.id); const threadKey = scopedThreadKey(threadRef); const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope); @@ -743,6 +746,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP (threads) => threads.has(thread.id), ); const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease(props.isActive); + const progressLines = + thread.taskProgress || (thread.hasRunningCommand && leaseLiveStatus) ? ( + + ) : null; const { revealRef } = props; const rowRef = (row: HTMLElement | null) => { const stopReveal = row === null ? undefined : revealRef?.(row, threadKey); @@ -1359,6 +1366,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP data-sidebar-row={threadKey} data-sidebar-parent={props.navigationParent} aria-label={accessibility.label} + aria-describedby={progressLines ? progressId : undefined} aria-current={accessibility.current} data-testid={inFolder ? "sidebar-row-folder" : "sidebar-row-slim"} aria-busy={isRegeneratingTitle || undefined} @@ -1366,7 +1374,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP rowSurfaceClassName, multiline ? "flex flex-col justify-center px-2.5 py-1.5" - : "flex h-9 items-center gap-2.5 px-2.5", + : "flex flex-col justify-center px-2.5", // Lines titles up with the folder name, past its chevron and icon. inFolder && "ps-9", )} @@ -1380,8 +1388,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP /> } > - {/* `contents` keeps one-line rows a single flex row. */} -
    +
    {inFolder ? null : ( + {progressLines} {multiline ? metaLine : null}
  • @@ -1573,6 +1581,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP data-sidebar-row={threadKey} data-sidebar-parent={props.navigationParent} aria-label={accessibility.label} + aria-describedby={progressLines ? progressId : undefined} aria-current={accessibility.current} data-testid="sidebar-row-card" aria-busy={isRegeneratingTitle || undefined} @@ -1589,8 +1598,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP >
    @@ -1762,6 +1771,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ) : null} {titleLineIcons}
    + {progressLines} {metaLine}
    @@ -1816,6 +1826,7 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props projectDisplayName: props.projectDisplayName, isActive: props.isRouteActive, }); + const progressId = useId(); const threadRef = scopeThreadRef(thread.environmentId, thread.id); // Results only drag out as chat context; the row keeps its own listbox attributes. const { listeners: dragListeners, setNodeRef: setDragNodeRef } = useDraggable({ @@ -1824,6 +1835,10 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease( props.isHighlighted || props.isRouteActive, ); + const progressLines = + thread.taskProgress || (thread.hasRunningCommand && leaseLiveStatus) ? ( + + ) : null; const isRegeneratingTitle = thread.titleRegeneration != null; const rowRef = (row: HTMLElement | null) => { setDragNodeRef(row); @@ -1913,7 +1928,9 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props tabIndex={-1} aria-selected={props.isHighlighted} aria-current={accessibility.current} - aria-describedby={`${props.resultId}-pr`} + aria-describedby={ + progressLines ? `${props.resultId}-pr ${progressId}` : `${props.resultId}-pr` + } aria-label={accessibility.label} {...dragListeners} onMouseMove={props.onHighlight} @@ -1987,6 +2004,7 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props + {progressLines} {props.searchMatch ? ( [number] @@ -343,6 +345,8 @@ export function presentThreadShell( : null, pendingSubagentRequest, pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0, + hasRunningCommand: thread.hasRunningCommand === true, + taskProgress: thread.taskProgress, hasActionableProposedPlan: thread.hasActionableProposedPlan, pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [], providerInstanceHistory: thread.providerInstanceHistory ?? [], diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 736bdaa6cfb6c..129b1e3f1ce74 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2462,6 +2462,10 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc), /** Excludes wakes and agent messages that advance latestUserMessageAt through the user role. */ latestUserAuthoredMessageAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), + hasRunningCommand: Schema.optionalKey(Schema.Literal(true)), + taskProgress: Schema.optionalKey( + Schema.Struct({ completed: NonNegativeInt, total: PositiveInt }), + ), hasActionableProposedPlan: Schema.Boolean, pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)).pipe( Schema.withDecodingDefault(Effect.succeed([])), @@ -4203,12 +4207,19 @@ export type OrchestrationV2SubscribeCommandProgressInput = /** A count a running command last printed, such as a test runner's `24/31` or a build's `42%`. */ export const OrchestrationV2CommandProgress = Schema.Struct({ + commandLabel: Schema.optionalKey(Schema.String), itemId: TurnItemId, completed: NonNegativeInt, total: PositiveInt, }); export type OrchestrationV2CommandProgress = typeof OrchestrationV2CommandProgress.Type; +export function formatCommandProgress(progress: OrchestrationV2CommandProgress): string { + return progress.total === 100 + ? `${progress.completed}%` + : `${progress.completed}/${progress.total}`; +} + /** Unpersisted: every running command in the thread that printed a count, replaced whole on each frame. */ export const OrchestrationV2CommandProgressFrame = Schema.Struct({ items: Schema.Array(OrchestrationV2CommandProgress), From a03d47d7c6ec230dfaca5344d1f44983ef16a9c9 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 27 Nov 2026 10:33:37 -0300 Subject: [PATCH 82/87] style(mobile): format the command progress label [skip ci] --- apps/mobile/src/features/threads/thread-list-v2-items.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index aef6f8b624144..d3ba6130b7331 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -1410,10 +1410,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { {command ? ( - + {command.commandLabel} From 07dca191877972e01ba78ee32d693a4e47b821fe Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 27 Nov 2026 15:23:23 -0300 Subject: [PATCH 83/87] feat(usage): persist analytics and subscription reports --- apps/mobile/src/App.tsx | 2 + .../mobile/src/features/usage/UsageReport.tsx | 504 ++++++++++++ .../src/features/usage/UsageRouteScreen.tsx | 117 ++- apps/mobile/src/i18n/translations/de.json | 41 +- apps/mobile/src/i18n/translations/en.json | 41 +- apps/mobile/src/i18n/translations/es.json | 41 +- apps/mobile/src/i18n/translations/fr.json | 41 +- apps/mobile/src/i18n/translations/ja.json | 41 +- apps/mobile/src/i18n/translations/ko.json | 41 +- apps/mobile/src/i18n/translations/pt-BR.json | 41 +- apps/mobile/src/i18n/translations/ru.json | 41 +- apps/mobile/src/i18n/translations/sv.json | 41 +- apps/mobile/src/i18n/translations/zh.json | 41 +- .../src/state/UsageArchiveCoordinator.tsx | 33 + apps/mobile/src/state/usage.ts | 30 +- apps/server/src/auth/RpcAuthorization.ts | 4 + .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 6 + apps/server/src/persistence/Migrations.ts | 4 + .../Migrations/120_UsageArchive.ts | 15 + .../121_UsageSubscriptionPayments.ts | 9 + .../reconcileV2PreviewMigration.test.ts | 4 + apps/server/src/server.ts | 4 + apps/server/src/usage/UsageArchive.test.ts | 127 ++++ apps/server/src/usage/UsageArchive.ts | 406 ++++++++++ .../server/src/usage/UsageArchivePeer.test.ts | 63 ++ apps/server/src/usage/UsageArchivePeer.ts | 118 +++ apps/server/src/usage/UsageArchiveWorker.ts | 41 + apps/server/src/usage/UsageService.test.ts | 7 + apps/server/src/usage/UsageService.ts | 74 +- apps/server/src/usage/usageAggregation.ts | 18 +- apps/server/src/ws.ts | 19 +- .../settings/KeybindingsSettings.logic.ts | 2 +- apps/web/src/components/usage/UsagePage.tsx | 275 ++++--- .../usage/UsageProviderChart.test.ts | 5 + .../components/usage/UsageProviderChart.tsx | 68 +- .../usage/UsageReport.browser.test.tsx | 87 +++ apps/web/src/components/usage/UsageReport.tsx | 716 ++++++++++++++++++ .../usage/usagePagePreferences.test.ts | 19 +- .../components/usage/usagePagePreferences.ts | 4 +- .../src/components/usage/usageShortcuts.ts | 15 +- apps/web/src/i18n/translations/de.json | 60 +- apps/web/src/i18n/translations/en.json | 60 +- apps/web/src/i18n/translations/es.json | 60 +- apps/web/src/i18n/translations/fr.json | 60 +- apps/web/src/i18n/translations/ja.json | 60 +- apps/web/src/i18n/translations/ko.json | 60 +- apps/web/src/i18n/translations/pt-BR.json | 60 +- apps/web/src/i18n/translations/ru.json | 60 +- apps/web/src/i18n/translations/sv.json | 60 +- apps/web/src/i18n/translations/zh.json | 60 +- apps/web/src/routes/__root.tsx | 2 + .../web/src/state/UsageArchiveCoordinator.tsx | 33 + apps/web/src/state/usage.ts | 33 +- docs/user/usage.md | 10 +- packages/client-runtime/package.json | 4 + packages/client-runtime/src/state/server.ts | 46 +- .../client-runtime/src/state/usageArchive.ts | 301 ++++++++ .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/environment.ts | 1 + packages/contracts/src/rpc.ts | 67 +- packages/contracts/src/usage.ts | 59 +- packages/shared/package.json | 4 + packages/shared/src/usageMerge.ts | 36 + packages/shared/src/usagePayments.test.ts | 119 +++ packages/shared/src/usagePayments.ts | 198 +++++ 66 files changed, 4423 insertions(+), 299 deletions(-) create mode 100644 apps/mobile/src/features/usage/UsageReport.tsx create mode 100644 apps/mobile/src/state/UsageArchiveCoordinator.tsx create mode 100644 apps/server/src/persistence/Migrations/120_UsageArchive.ts create mode 100644 apps/server/src/persistence/Migrations/121_UsageSubscriptionPayments.ts create mode 100644 apps/server/src/usage/UsageArchive.test.ts create mode 100644 apps/server/src/usage/UsageArchive.ts create mode 100644 apps/server/src/usage/UsageArchivePeer.test.ts create mode 100644 apps/server/src/usage/UsageArchivePeer.ts create mode 100644 apps/server/src/usage/UsageArchiveWorker.ts create mode 100644 apps/web/src/components/usage/UsageReport.browser.test.tsx create mode 100644 apps/web/src/components/usage/UsageReport.tsx create mode 100644 apps/web/src/state/UsageArchiveCoordinator.tsx create mode 100644 packages/client-runtime/src/state/usageArchive.ts create mode 100644 packages/shared/src/usagePayments.test.ts create mode 100644 packages/shared/src/usagePayments.ts diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 7193fcb9b7af8..6a143f5c51f02 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -78,6 +78,7 @@ import { } from "./lib/foundation-fast-refresh"; import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme"; import { installUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc"; +import { UsageArchiveCoordinator } from "./state/UsageArchiveCoordinator"; import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator"; import { ConnectDeviceApprovalCoordinator } from "./features/connection/ConnectDeviceApprovalCoordinator"; import { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage"; @@ -302,6 +303,7 @@ function AppContent() { <> + n + d.total, 0); + if (!peak) return null; + const base = days.map(() => 0); + return ( + + {PROVIDER_ORDER.map((provider, p) => { + let running = 0; + const point = (i: number, v: number) => + `${(300 * i) / Math.max(1, days.length - 1)},${height * (1 - v / peak)}`; + const bottom = base.map((v, i) => point(i, v)).reverse(); + const top = data.map((d, i) => { + running += d.values[p]?.value ?? 0; + base[i] = (base[i] ?? 0) + running; + return point(i, base[i]!); + }); + return ( + + ); + })} + + ); +} +export function Action({ + label, + press, + disabled = false, +}: { + label: string; + press: () => void; + disabled?: boolean; +}) { + return ( + + {label} + + ); +} +export function Field({ + label, + value, + change, + numeric = false, +}: { + label: string; + value: string; + change: (v: string) => void; + numeric?: boolean; +}) { + return ( + + {label} + + + ); +} +function PaymentEditor({ month: initial, close }: { month: string; close: () => void }) { + const gt = useGT(), + { book, id, label } = useAtomValue(usagePayments.state), + [destination] = useState(id), + [month, setMonth] = useState(initial), + [draft, setDraft] = useState>({}), + [busy, setBusy] = useState(false), + [error, setError] = useState(false); + const save = async () => { + const patch: Record = {}; + for (const [key, value] of Object.entries(draft)) { + const [m, p] = key.split("/"); + if (!m || !p) return; + const changes = paymentPatch(m, { [p]: value }); + if (!changes) { + setError(true); + return; + } + Object.assign(patch, changes); + } + setBusy(true); + try { + if (destination && (await usagePayments.save(destination, patch))) close(); + else setError(true); + } finally { + setBusy(false); + } + }; + return ( + + + {gt("Monthly payments")} · {label ?? destination} + + {gt("Enter amounts in USD. Empty means unknown. Zero means a free month.")} + + {/^[0-9]{4}-(0[1-9]|1[0-2])$/.test(month) && + PROVIDER_ORDER.map((p) => { + const key = month + "/" + p, + cents = book[key]?.cents; + return ( + setDraft({ ...draft, [key]: v })} + /> + ); + })} + {error && {gt("Check the amounts and connection, then try again.")}} + + void save()} + disabled={busy || !Object.keys(draft).length} + /> + + + + ); +} +type Share = { provider: UsageProviderKind; value: number }; +function Shares({ + title, + rows, + format, +}: { + title: string; + rows: readonly Share[]; + format: (n: number) => string; +}) { + const colors = useProviderColors(), + total = rows.reduce((n, r) => n + r.value, 0), + circ = 2 * Math.PI * 54; + return ( + + {title} + + + {usagePieSlices(rows, total).map(({ row: r, start: offset, fraction }) => { + const length = circ * fraction, + start = circ * offset; + return ( + + ); + })} + + {format(total)} + + {rows.map((r) => ( + + + {PROVIDER_LABEL[r.provider]} + + {format(r.value)} · {formatPercent(total ? r.value / total : 0)} + + + ))} + + ); +} +const receipts = Atom.make((get) => + [...get(environmentPresentations.presentationsAtom)].flatMap(([id, p]) => + p.connection.phase === "connected" && p.serverConfig?.environment.capabilities.usageArchive + ? AsyncResult.getOrElse( + get(serverEnvironment.archiveReceipts({ environmentId: id, input: {} })), + () => [], + ) + .filter((c) => c.environmentId !== id) + .map((c) => ({ ...c, destination: p.entry.target.label })) + : [], + ), +); +export function MobileUsageSync({ + environments, +}: { + environments: readonly EnvironmentUsageStatus[]; +}) { + const gt = useGT(), + locale = useLocale(), + copies = useAtomValue(receipts); + return ( + + {gt("Usage synchronization")} + {environments.map((e) => ( + + + {e.label} · {e.isConnected ? gt("Online") : gt("Offline")} + + {copies + .filter((c) => c.environmentId === e.environmentId) + .map((c) => ( + + {c.destination} · {new Date(c.readAt).toLocaleString(locale)} + + ))} + + ))} + + ); +} +export function MobileUsageReport({ + report, + window: summary, + selection, +}: { + report: boolean; + window: UsageSummaryInput; + selection: ReadonlySet | null; +}) { + const gt = useGT(), + locale = useLocale(), + [w, setWindow] = useState(() => usagePeriod("year")), + [preset, setPreset] = useState("year"), + [from, setFrom] = useState(w.sinceDay), + [to, setTo] = useState(w.untilDay), + [basis, setBasis] = useState<"api" | "subscription">("api"), + [edit, setEdit] = useState(false), + [mode, setMode] = useState<"interval" | "cumulative">("cumulative"); + const selected = report ? w : summary, + sub = !report || basis === "subscription", + { book, writers, id, targets, label } = useAtomValue(usagePayments.state); + const dailyWindow: UsageSummaryInput = { + savedHistory: true, + sinceDay: selected.sinceDay, + untilDay: selected.untilDay, + timeZone: selected.timeZone, + }; + const data = useUsage(dailyWindow, selection), + money = (v: number) => formatUsd(v, locale); + const bill = subscriptionUsage( + book, + selected, + data.environments.flatMap((e) => + e.summary ? [{ environmentId: e.environmentId, label: e.label, summary: e.summary }] : [], + ), + selection, + ); + const isHourly = selected.resolution === "hour", + days = isHourly + ? enumerateHourStarts(selected.sinceTime!, selected.untilTime!) + : enumerateDays(selected.sinceDay, selected.untilDay), + daily = isHourly ? bill.hourly.map((r) => ({ ...r, day: r.hourStart })) : bill.daily; + const valid = + validUsageDay(from) && validUsageDay(to) && from <= to && to <= makeWindow(1).untilDay; + if (edit) + return setEdit(false)} />; + return ( + + {report && ( + <> + + + {( + [ + ["7", gt("7 days")], + ["30", gt("30 days")], + ["90", gt("90 days")], + ["year", gt("Last year")], + ["custom", gt("Custom")], + ] as const + ).map(([v, label]) => ( + { + setPreset(v); + if (v !== "custom") { + const r = usagePeriod(v); + setWindow(r); + setFrom(r.sinceDay); + setTo(r.untilDay); + } + }} + /> + ))} + + {preset === "custom" && ( + <> + + setFrom(/^\d+$/.test(v) && Number(v) > 0 ? moveUsageDay(to, 1 - Number(v)) : "") + } + /> + + + + setWindow({ ...w, sinceDay: UsageDay.make(from), untilDay: UsageDay.make(to) }) + } + /> + { + const r = { ...makeWindow(1), sinceDay: UsageDay.make("1970-01-01") }; + setWindow(r); + setFrom(r.sinceDay); + setTo(r.untilDay); + }} + /> + + )} + + )} + + {selected.sinceDay} – {selected.untilDay} + + {sub && ( + <> + + {gt("Payment environment")} · {label ?? gt("Select an environment")} + + {targets.length > 1 && ( + + {targets.map((t) => ( + usagePayments.select(t.id)} + /> + ))} + + )} + setEdit(true)} + /> + + {gt("Full payments for the included months")} ·{" "} + {bill.providers.size ? money(bill.paid) : gt("Not entered")} + + + {gt("Subscription cost for the period")} ·{" "} + {bill.providers.size ? money(bill.costUsd) : gt("Not entered")} + + {gt("Monthly payments are prorated by calendar day.")} + {bill.missing.size > 0 && ( + + {gt("Missing monthly payments")} · {[...bill.missing].join(", ")} + + )} + + )} + {!data.environments.some((e) => e.canReadDiagnostics) ? ( + {gt("Connect an environment to see usage.")} + ) : data.isPending ? ( + {gt("Scanning provider transcripts…")} + ) : report ? ( + <> + ({ + provider: p.provider, + value: p.totalTokens, + }))} + format={formatTokens} + /> + {!sub || bill.providers.size ? ( + ({ provider, value: p.costUsd })) + : data.merged.providers.map((p) => ({ provider: p.provider, value: p.costUsd })) + } + format={money} + /> + ) : ( + {gt("No payments entered for this period.")} + )} + {sub && + [...bill.providers].map(([provider, amount]) => ( + + {PROVIDER_LABEL[provider]} + + {gt("Full payments for the included months")} · {money(amount.paid)} + + + {gt("Subscription cost for the period")} · {money(amount.costUsd)} + + + ))} + + ) : ( + <> + + {mode === "cumulative" ? ( + + ) : ( + + )} + {gt("Subscription by model")} + {bill.models.map((m) => ( + + {m.model} · {money(m.costUsd)} + + ))} + {bill.unassigned > 0 && ( + + {gt("No attributable usage")} · {money(bill.unassigned)} + + )} + + )} + + ); +} diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx index 599c80e1bc853..012db59709871 100644 --- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx +++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx @@ -42,6 +42,7 @@ import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-con import { useUsage, type EnvironmentUsageStatus } from "../../state/usage"; import { SettingsSection } from "../settings/components/SettingsSection"; import { usageAxisDayLabel, usageAxisHourLabel } from "./usageAxisLabels"; +import { MobileUsageReport, MobileUsageSync, CumulativeChart, Action, Field } from "./UsageReport"; import { UsageDailyChart } from "./UsageDailyChart"; import { toggleUsageEnvironment } from "./usageEnvironmentSelection"; import { useRefreshLimits } from "./UsageLimitsSection"; @@ -49,9 +50,10 @@ import { UsageLimitsSection } from "./UsageLimitsPooled"; import type { UsageChartMetric } from "./usageChartData"; import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders"; -type UsageView = UsageChartMetric | "limits"; +type UsageView = UsageChartMetric | "limits" | "subscription"; const VIEW_OPTIONS = [ - { value: "cost", label: msg("Cost", { $context: "usage view tab" }) }, + { value: "cost", label: msg("API cost") }, + { value: "subscription", label: msg("Subscription") }, { value: "tokens", label: msg("Tokens", { $context: "usage view tab" }) }, { value: "limits", label: msg("Limits", { $context: "usage view tab, subscription limits" }) }, ] as const satisfies readonly { value: UsageView; label: string }[]; @@ -97,6 +99,9 @@ function UsageScreen(props: { }) { const gt = useGT(); const m = useMessages(); + const [section, setSection] = useState<"summary" | "report" | "sync">("summary"); + const [custom, setCustom] = useState(false), + [draftDays, setDraftDays] = useState("37"); const viewOptions = VIEW_OPTIONS.map((option) => ({ ...option, label: m(option.label) })); const windowOptions = WINDOW_OPTIONS.map((option) => ({ ...option, @@ -137,7 +142,7 @@ function UsageScreen(props: { const isFocused = useIsFocused(); const limits = useRefreshLimits( selectedEnvironmentIds, - isFocused && view === "limits" && !headerOnly, + isFocused && section === "summary" && view === "limits" && !headerOnly, ); const sourceMessages = usageSourceMessages( selectedEnvironments.flatMap((environment) => environment.summary?.sources ?? []), @@ -163,7 +168,7 @@ function UsageScreen(props: { const [refreshingUsage, setRefreshingUsage] = useState(false); const refreshingRef = useRef(false); - const showingLimits = view === "limits"; + const showingLimits = section === "summary" && view === "limits"; const metric: UsageChartMetric = view === "tokens" ? "tokens" : "cost"; const progress = usageProgress( selectedEnvironments, @@ -174,6 +179,7 @@ function UsageScreen(props: { m, ); const selectWindow = (days: number) => { + setCustom(false); setWindowSelection({ days, window: makeWindow(days, undefined, days === 1 ? "hour" : "day"), @@ -267,42 +273,91 @@ function UsageScreen(props: { } > - {wide ? ( - - {showingLimits ? ( - - ) : ( + + {section === "summary" && + (wide ? ( + + {showingLimits ? ( + + ) : ( + + )} - )} + + ) : ( + ))} + {section === "summary" && !showingLimits && ( + + {view === "subscription" && !wide && ( + + )} + setCustom(!custom)} /> + {custom && ( + <> + + 36525 + } + press={() => selectWindow(Number(draftDays))} + /> + + )} - ) : ( - )} - {showingLimits ? ( + {section === "sync" ? ( + + ) : section === "report" || view === "subscription" ? ( + + ) : showingLimits ? ( period.totalTokens > 0); + const gt = useGT(); + const [mode, setMode] = useState<"interval" | "cumulative">("interval"); const [fillHeight, setFillHeight] = useState(0); const height = props.fill ? Math.max(fillHeight, props.height) : props.height; const chart = hasActivity ? ( - + mode === "cumulative" ? ( + + ) : ( + + ) ) : ( @@ -490,6 +551,14 @@ function ChartCard(props: { )} + {props.fill ? ( // Absolute so the measured slot can shrink again when the neighbour gets shorter. + startUsageReplication( + appAtomRegistry, + environmentPresentations.presentationsAtom, + environmentShell, + environmentSession, + serverEnvironment, + ), + [], + ); + return null; +} diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.ts index 4fac1e794f77d..1fdac3541dba1 100644 --- a/apps/mobile/src/state/usage.ts +++ b/apps/mobile/src/state/usage.ts @@ -1,3 +1,5 @@ +import { withUsageCopies } from "@t3tools/client-runtime/state/usage-archive"; +import type { UsageArchiveCopy } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { AuthDiagnosticsReadScope, @@ -34,6 +36,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) => const input = JSON.parse(windowKey) as UsageSummaryInput; const presentations = get(environmentPresentations.presentationsAtom); + const copies: UsageArchiveCopy[] = []; const statuses: EnvironmentUsageStatus[] = []; for (const [environmentId, presentation] of presentations) { const sessionResult = get(environmentSession.sessionStateAtom(environmentId)); @@ -55,11 +58,24 @@ const usageByWindowAtom = Atom.family((windowKey: string) => }); continue; } + if ( + presentation.connection.phase === "connected" && + presentation.serverConfig?.environment.capabilities.usageArchive + ) { + const saved = get(serverEnvironment.archiveRead({ environmentId, input })); + copies.push( + ...AsyncResult.getOrElse(saved, () => []).filter( + (copy) => copy.environmentId !== environmentId, + ), + ); + } const result = get( serverEnvironment.usageSummary({ environmentId, input: usageSummaryInput( - input, + input.savedHistory && !presentation.serverConfig?.environment.capabilities.usageArchive + ? { ...input, savedHistory: false } + : input, get(serverEnvironment.usageModelFilterAtom(environmentId)), ), }), @@ -75,7 +91,15 @@ const usageByWindowAtom = Atom.family((windowKey: string) => summary, }); } - return statuses; + return withUsageCopies(statuses, copies, (copy) => ({ + environmentId: copy.environmentId, + label: copy.label, + isPending: false, + isConnected: false, + canReadDiagnostics: true, + error: null, + summary: copy.summary, + })); }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)), ); @@ -112,6 +136,7 @@ export function useUsage( const windowKey = useMemo( () => JSON.stringify({ + savedHistory: input.savedHistory, sinceDay: input.sinceDay, untilDay: input.untilDay, timeZone: input.timeZone, @@ -120,6 +145,7 @@ export function useUsage( untilTime: input.untilTime, }), [ + input.savedHistory, input.sinceDay, input.untilDay, input.timeZone, diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 722a4f9d8fa79..9e12786318fbf 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -128,6 +128,10 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverGetProcessResourceHistory]: AuthDiagnosticsReadScope, [WS_METHODS.serverGetResourceTelemetryHistory]: AuthDiagnosticsReadScope, [WS_METHODS.serverRetryResourceTelemetry]: AuthDiagnosticsReadScope, + [WS_METHODS.usagePaymentsRead]: AuthSettingsWriteScope, + [WS_METHODS.usageArchiveStatus]: AuthDiagnosticsReadScope, + [WS_METHODS.usageArchiveExport]: AuthDiagnosticsReadScope, + [WS_METHODS.usageArchiveRead]: AuthDiagnosticsReadScope, [WS_METHODS.serverGetUsageSummary]: AuthDiagnosticsReadScope, [WS_METHODS.serverRefreshUsageRates]: AuthDiagnosticsReadScope, [WS_METHODS.serverSignalProcess]: AuthEnvironmentMaintainScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index a7be8b20d3daa..ad4ce0c09bf4f 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -257,6 +257,7 @@ export const make = Effect.gen(function* () { usageLimitSources: true, providerWorkspaceSnapshotsOnDemand: true, modelCatalogRefresh: true, + usageArchive: true, usagePriceOverrides: true, usageModelAliases: true, threadPinning: true, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 786312662b10e..8a18f452eb258 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -104,6 +104,12 @@ const RPC_AGGREGATES = { [WS_METHODS.serverCheckOtlpEndpoint]: "server", [WS_METHODS.serverListTextGeneratorModels]: "server", [WS_METHODS.serverPrepareTriage]: "server", + [WS_METHODS.usagePaymentsRead]: "server", + [WS_METHODS.usagePaymentsUpdate]: "server", + [WS_METHODS.usageArchiveStatus]: "server", + [WS_METHODS.usageArchiveExport]: "server", + [WS_METHODS.usageArchiveImport]: "server", + [WS_METHODS.usageArchiveRead]: "server", [WS_METHODS.serverGetUsageSummary]: "server", [WS_METHODS.serverRefreshUsageRates]: "server", [WS_METHODS.serverSignalProcess]: "server", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 5d29aa358584e..4ed3adbb68429 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -129,6 +129,8 @@ import Migration0115 from "./Migrations/115_WorkflowRunTags.ts"; import Migration0116 from "./Migrations/116_ForkHistoryMembership.ts"; import Migration0117 from "./Migrations/117_WorkflowMailSender.ts"; import Migration0118 from "./Migrations/118_WorkflowPools.ts"; +import Migration0121 from "./Migrations/121_UsageSubscriptionPayments.ts"; +import Migration0120 from "./Migrations/120_UsageArchive.ts"; import Migration0119 from "./Migrations/119_WorkflowRunSubject.ts"; const migrationEntries = [ @@ -252,6 +254,8 @@ const migrationEntries = [ [117, "WorkflowMailSender", Migration0117], [118, "WorkflowPools", Migration0118], [119, "WorkflowRunSubject", Migration0119], + [120, "UsageArchive", Migration0120], + [121, "UsageSubscriptionPayments", Migration0121], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/120_UsageArchive.ts b/apps/server/src/persistence/Migrations/120_UsageArchive.ts new file mode 100644 index 0000000000000..0e417dce1c721 --- /dev/null +++ b/apps/server/src/persistence/Migrations/120_UsageArchive.ts @@ -0,0 +1,15 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE usage_archive ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, origin TEXT NOT NULL, day TEXT NOT NULL, source TEXT NOT NULL, + read_at TEXT NOT NULL, payload TEXT NOT NULL, + UNIQUE (origin, day, source) + )`; + yield* sql`CREATE INDEX usage_archive_day_idx ON usage_archive(day)`; + yield* sql`CREATE TABLE usage_archive_sync ( + origin TEXT PRIMARY KEY, label TEXT NOT NULL, read_at TEXT NOT NULL, cursor INTEGER NOT NULL DEFAULT 0, full_at TEXT, retry_at TEXT + )`; +}); diff --git a/apps/server/src/persistence/Migrations/121_UsageSubscriptionPayments.ts b/apps/server/src/persistence/Migrations/121_UsageSubscriptionPayments.ts new file mode 100644 index 0000000000000..0e82c13c6730e --- /dev/null +++ b/apps/server/src/persistence/Migrations/121_UsageSubscriptionPayments.ts @@ -0,0 +1,9 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE usage_subscription_payments ( + provider_month TEXT PRIMARY KEY, cents INTEGER NOT NULL CHECK(cents>=0), updated_at TEXT NOT NULL + )`; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 20289dd44997d..2774665c35331 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -99,6 +99,8 @@ describe("V2 preview upgrade", () => { [117, "WorkflowMailSender"], [118, "WorkflowPools"], [119, "WorkflowRunSubject"], + [120, "UsageArchive"], + [121, "UsageSubscriptionPayments"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -241,6 +243,8 @@ describe("V2 preview upgrade", () => { [117, "WorkflowMailSender"], [118, "WorkflowPools"], [119, "WorkflowRunSubject"], + [120, "UsageArchive"], + [121, "UsageSubscriptionPayments"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 01d0c06870766..af3ea90583b75 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -233,6 +233,8 @@ import { MuseUsageHome } from "@t3tools/provider-muse/server"; import * as CursorAccountReader from "@t3tools/provider-cursor/server/CursorAccountReader"; import * as CursorUsageAccounts from "@t3tools/provider-cursor/server/CursorUsageAccounts"; import * as UsageService from "./usage/UsageService.ts"; +import { archivePeerRoute } from "./usage/UsageArchivePeer.ts"; +import { usageArchiveWorker } from "./usage/UsageArchiveWorker.ts"; import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts"; import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts"; import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts"; @@ -938,6 +940,7 @@ const layerMakeRoutes = Layer.mergeAll( ServerHttp.layerAttachmentUploadRoute, GuestHttp.layer, LinkThreadHttp.layer, + archivePeerRoute, DeviceHubProxy.layer, ServerBrowserStream.routeLayer, PreviewTunnel.routeLayer, @@ -1436,6 +1439,7 @@ const layerMakeServer = Layer.unwrap( layerRoutes, layerHttpListening, layerDesktopReadySignal, + usageArchiveWorker.pipe(Layer.provide(PeerLinks.layer)), layerRuntimeState.pipe(Layer.provide(layerLauncher)), layerTailscaleServe, layerCloudDesiredLinkReconcile, diff --git a/apps/server/src/usage/UsageArchive.test.ts b/apps/server/src/usage/UsageArchive.test.ts new file mode 100644 index 0000000000000..61877ca855dc2 --- /dev/null +++ b/apps/server/src/usage/UsageArchive.test.ts @@ -0,0 +1,127 @@ +import { assert, it } from "@effect/vitest"; +import { + EnvironmentId, + UsageDay, + USAGE_CONTRACT_VERSION, + type UsageSummary, +} from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as FileSystem from "effect/FileSystem"; +import paymentMigration from "../persistence/Migrations/121_UsageSubscriptionPayments.ts"; +import migration from "../persistence/Migrations/120_UsageArchive.ts"; +import { makeUsageArchive } from "./UsageArchive.ts"; + +it.effect("reopens the destination archive without its source and counts a retried page once", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem, + dir = yield* fs.makeTempDirectoryScoped(); + const origin = EnvironmentId.make("laptop"), + target = EnvironmentId.make("desktop"), + day = UsageDay.make("2026-11-27"); + const window = { sinceDay: day, untilDay: day, timeZone: "UTC" }; + const snapshot: UsageSummary = { + ...window, + contractVersion: USAGE_CONTRACT_VERSION, + readAt: "2026-11-27T15:00:00.000Z", + pricing: { status: "cached", source: "fixture", fetchedAt: null, knownModels: 0 }, + scanDurationMs: 0, + sources: [ + { + fingerprint: { + provider: "codex", + hostId: "laptop", + resolvedHomePath: "source", + volumeId: "disk", + }, + status: "ok", + distinctSessions: 1, + scannedFiles: 1, + skippedFiles: 0, + malformedRecords: 0, + message: null, + }, + ], + buckets: ["11:00", "11:01"].map((time) => ({ + day, + hourStart: "2026-11-27T" + time + ":00.000Z", + provider: "codex", + model: "test-model", + sourcePath: "source", + totals: { + uncachedInputTokens: 10, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 2, + reasoningTokens: 1, + }, + sessions: 1, + archiveSessions: ["private-session"], + records: 1, + costUsd: 1, + cacheSavingsUsd: 0, + costSource: "modelPriced", + unpricedRecords: 0, + })), + }; + const open = (id: EnvironmentId) => + Effect.gen(function* () { + return makeUsageArchive( + yield* SqlClient.SqlClient, + { archiveSummary: () => Effect.succeed(snapshot) }, + { + getEnvironmentId: Effect.succeed(id), + getDescriptor: Effect.succeed({ environmentId: id, label: id }), + }, + ); + }); + const page = yield* Effect.gen(function* () { + yield* migration; + yield* paymentMigration; + const src = yield* open(origin); + yield* src.updatePayments({ "2026-11/codex": 3050, "2026-11/claude": 0 }); + yield* src.updatePayments({ "2026-11/claude": null }); + assert.equal((yield* src.payments)["2026-11/codex"]?.cents, 3050); + assert.notProperty(yield* src.payments, "2026-11/claude"); + return yield* src.changes({ cursor: 0, capture: true }); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dir + "/source.sqlite" }))); + assert.equal(page.days.length, 1); + assert.notInclude(JSON.stringify(page), "private-session"); + const dest = () => NodeSqliteClient.layer({ filename: dir + "/dest.sqlite" }); + yield* Effect.gen(function* () { + yield* migration; + yield* paymentMigration; + const api = yield* open(target); + yield* api.receive(page); + yield* api.receive(page); + }).pipe(Effect.provide(dest())); + const result = yield* Effect.gen(function* () { + const api = yield* open(target); + assert.deepStrictEqual(yield* api.payments, {}); + return yield* api.read(window); + }).pipe(Effect.provide(dest())); + const relayed = yield* Effect.gen(function* () { + const api = yield* open(target); + return yield* api.changes({ cursor: 0, capture: false, origin }); + }).pipe(Effect.provide(dest())); + assert.equal(relayed.environmentId, origin); + assert.equal(relayed.cursor, page.cursor); + yield* Effect.gen(function* () { + yield* migration; + yield* paymentMigration; + const third = yield* open(EnvironmentId.make("third")); + yield* third.receive(relayed); + yield* third.receive(page); + assert.deepStrictEqual(yield* third.payments, {}); + assert.equal((yield* third.read(window))[0]?.summary.buckets[0]?.costUsd, 2); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dir + "/third.sqlite" }))); + assert.equal(result.length, 1); + assert.equal(result[0]?.summary.sources[0]?.distinctSessions, 1); + assert.equal(result[0]?.summary.buckets[0]?.costUsd, 2); + assert.equal(result[0]?.summary.buckets[0]?.totals.uncachedInputTokens, 20); + }).pipe(Effect.provide(Layer.merge(NodeServices.layer, NodeCrypto.layer))), +); diff --git a/apps/server/src/usage/UsageArchive.ts b/apps/server/src/usage/UsageArchive.ts new file mode 100644 index 0000000000000..f45b2f1891b5a --- /dev/null +++ b/apps/server/src/usage/UsageArchive.ts @@ -0,0 +1,406 @@ +import { + EnvironmentId, + USAGE_CONTRACT_VERSION, + UsageArchiveDay, + UsageDay, + UsageReadError, + type UsageArchiveCopy, + type UsageArchivePage, + type UsageBucket, + type UsageSource, + type UsageSummary, + type UsageSummaryInput, +} from "@t3tools/contracts"; +import * as Digest from "effect/crypto/Digest"; +import * as Hex from "effect/encoding/Hex"; +import * as DateTime from "effect/DateTime"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import type * as SqlClient from "effect/sql/SqlClient"; +import { keepsUsageRecord } from "./usageAggregation.ts"; +import type { UsageService } from "./UsageService.ts"; +import type { ServerEnvironment } from "../environment/ServerEnvironment.ts"; + +const DAY = 86_400_000; +const StoredDay = Schema.Struct({ + revision: UsageArchiveDay.fields.revision, + day: UsageDay, + source: UsageArchiveDay.fields.source, + buckets: UsageArchiveDay.fields.buckets, + modelFilter: UsageArchiveDay.fields.modelFilter, +}); +const payloadSchema = Schema.fromJsonString(StoredDay); +const encodeDay = Schema.encodeSync(payloadSchema); +const decodeDay = Schema.decodeUnknownSync(payloadSchema); +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); +const pair = Schema.encodeSync(Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String]))); +const fail = (cause: unknown) => + new UsageReadError({ + reason: "scanFailed", + detail: "Could not update the usage archive.", + cause, + }); +const sourceKey = (source: UsageSource) => JSON.stringify(source.fingerprint); +const dayAt = (ms: number) => UsageDay.make(iso(ms).slice(0, 10)); +const numberFields = [ + "costUsd", + "cacheSavingsUsd", + "fastCostUsd", + "ultrafastCostUsd", + "speedPremiumUsd", + "records", + "unpricedRecords", + "unpricedTokens", +] as const; + +function archiveWindow(input: UsageSummaryInput, readAt: string) { + const formatter = new Intl.DateTimeFormat("en-CA", { + timeZone: input.timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + }); + const hourly = input.resolution === "hour"; + const since = Date.parse(input.sinceTime ?? ""), + until = Date.parse(input.untilTime ?? ""); + const sources = new Map }>(); + const grouped = new Map }>(); + const add = (chunk: UsageArchiveDay) => { + const key = sourceKey(chunk.source); + let source = sources.get(key); + if (!source) { + source = { source: chunk.source, sessions: new Set() }; + sources.set(key, source); + } + const checkFilter = + input.modelFilter && JSON.stringify(input.modelFilter) !== JSON.stringify(chunk.modelFilter); + if (chunk.source.status === "partial") source.source = chunk.source; + for (const b of chunk.buckets) { + if (checkFilter && !keepsUsageRecord(input.modelFilter, b)) continue; + const ms = Date.parse(b.hourStart ?? ""); + if (!Number.isFinite(ms) || (hourly && (ms < since || ms >= until))) continue; + const day = UsageDay.make(formatter.format(ms)); + if (day < input.sinceDay || day > input.untilDay) continue; + const hourStart = hourly + ? iso(since + Math.floor((ms - since) / 3_600_000) * 3_600_000) + : undefined; + const id = JSON.stringify([key, day, hourStart, b.model, b.costSource]); + const { archiveSessions = [], hourStart: _hour, ...base } = b; + let cell = grouped.get(id); + if (!cell) { + cell = { + bucket: { + ...base, + day, + ...(hourStart ? { hourStart } : {}), + totals: { ...b.totals }, + ...(b.categoryCostUsd ? { categoryCostUsd: { ...b.categoryCostUsd } } : {}), + }, + sessions: new Set(), + }; + grouped.set(id, cell); + } else { + const prev = cell.bucket; + const totals = { ...prev.totals }; + for (const k of Object.keys(totals) as Array) totals[k] += b.totals[k]; + const merged = { ...prev, totals }; + for (const k of numberFields) merged[k] = (prev[k] ?? 0) + (b[k] ?? 0); + if (b.categoryCostUsd) { + const category = { ...b.categoryCostUsd }; + for (const k of Object.keys(category) as Array) + category[k] += prev.categoryCostUsd?.[k] ?? 0; + merged.categoryCostUsd = category; + } + cell.bucket = merged; + } + for (const session of archiveSessions) { + source.sessions.add(session); + cell.sessions.add(session); + } + } + }; + const finish = (): UsageSummary => ({ + contractVersion: USAGE_CONTRACT_VERSION, + readAt, + timeZone: input.timeZone, + sinceDay: input.sinceDay, + untilDay: input.untilDay, + buckets: [...grouped.values()].map((c) => ({ ...c.bucket, sessions: c.sessions.size })), + sources: [...sources.values()].map((s) => ({ ...s.source, distinctSessions: s.sessions.size })), + pricing: { status: "cached", source: "usage-archive", fetchedAt: null, knownModels: 0 }, + scanDurationMs: 0, + }); + return { add, finish }; +} + +export function makeUsageArchive( + sql: SqlClient.SqlClient, + usage: Pick, + environment: { + getEnvironmentId: ServerEnvironment["Service"]["getEnvironmentId"]; + getDescriptor: Effect.Effect<{ environmentId: EnvironmentId; label: string }>; + }, +) { + const saveDay = Effect.fn("UsageArchive.saveDay")(function* ( + origin: EnvironmentId, + chunk: UsageArchiveDay, + ) { + let entry = chunk; + if (chunk.source.status === "partial") { + const [old] = yield* sql<{ + payload: string; + }>`SELECT payload FROM usage_archive WHERE origin=${origin} AND day=${chunk.day} AND source=${sourceKey(chunk.source)}`; + if (old) { + const key = (b: UsageBucket) => JSON.stringify([b.hourStart, b.model, b.costSource]); + const cells = new Map(decodeDay(old.payload).buckets.map((b) => [key(b), b])); + for (const b of chunk.buckets) { + const saved = cells.get(key(b)); + if (!saved || b.records >= saved.records) cells.set(key(b), b); + } + entry = { ...chunk, buckets: [...cells.values()] }; + } + } + const payload = encodeDay(entry); + yield* sql`INSERT INTO usage_archive(origin,day,source,read_at,payload) + VALUES(${origin},${chunk.day},${sourceKey(chunk.source)},${chunk.readAt},${payload}) + ON CONFLICT(origin,day,source) DO UPDATE SET seq=CASE WHEN usage_archive.payload != excluded.payload THEN (SELECT COALESCE(MAX(seq),0)+1 FROM usage_archive) ELSE usage_archive.seq END, + read_at=excluded.read_at,payload=excluded.payload + WHERE usage_archive.read_at < excluded.read_at`; + }); + const status = sql<{ + origin: string; + label: string; + read_at: string; + cursor: number; + firstDay: string | null; + }>`SELECT s.*,(SELECT MIN(day) FROM usage_archive a WHERE a.origin=s.origin) AS firstDay FROM usage_archive_sync s ORDER BY origin`.pipe( + Effect.map((rows) => + rows.map((r) => ({ + environmentId: EnvironmentId.make(r.origin), + label: r.label, + readAt: r.read_at, + cursor: r.cursor, + ...(r.firstDay ? { firstDay: UsageDay.make(r.firstDay) } : {}), + })), + ), + Effect.mapError(fail), + ); + const capture = Effect.fn("UsageArchive.capture")(function* () { + const { environmentId, label } = yield* environment.getDescriptor; + const [previous] = yield* sql<{ + read_at: string; + full_at: string | null; + retry_at: string | null; + }>`SELECT read_at,full_at,retry_at FROM usage_archive_sync WHERE origin=${environmentId}`; + const digest = yield* Digest.Digest; + const began = iso(yield* Clock.currentTimeMillis); + const retryPending = previous?.retry_at != null; + const catchUp = !retryPending || began >= previous.retry_at!; + const watermark = catchUp ? previous?.full_at : previous?.read_at; + const sinceDay = watermark + ? dayAt(Math.max(0, Date.parse(watermark) - DAY)) + : UsageDay.make("1970-01-01"); + const summary = yield* usage.archiveSummary(sinceDay); + const cells = new Map(); + const sources = new Map( + summary.sources + .filter((s) => (s.status === "ok" || s.status === "partial") && !s.refreshing) + .map((s) => [JSON.stringify([s.fingerprint.provider, s.fingerprint.resolvedHomePath]), s]), + ); + const hashes = new Map(); + for (const b of summary.buckets) { + const source = sources.get(pair([b.provider, b.sourcePath ?? ""])); + if (!source) continue; + const key = sourceKey(source) + b.day; + let cell = cells.get(key); + if (!cell) { + cell = { + day: b.day, + source: { + ...source, + scannedFiles: 0, + skippedFiles: 0, + distinctSessions: 0, + malformedRecords: 0, + message: null, + }, + buckets: [], + }; + cells.set(key, cell); + } + const sessions: string[] = []; + for (const id of b.archiveSessions ?? []) { + let hash = hashes.get(id); + if (!hash) { + hash = Hex.encode(yield* digest.digest(Digest.sha256, new TextEncoder().encode(id))); + hashes.set(id, hash); + } + sessions.push(hash); + } + cell.buckets.push({ ...b, archiveSessions: sessions }); + } + yield* sql.withTransaction( + Effect.gen(function* () { + for (const cell of cells.values()) + yield* saveDay(environmentId, { + ...cell, + readAt: began, + ...(summary.modelFilter ? { modelFilter: summary.modelFilter } : {}), + }); + const complete = + catchUp && + !summary.sources.some( + (s) => s.refreshing || s.status === "failed" || s.status === "partial", + ); + const retry = complete + ? null + : catchUp + ? iso(Date.parse(began) + 15 * 60_000) + : (previous?.retry_at ?? null); + yield* sql`INSERT INTO usage_archive_sync(origin,label,read_at,full_at,retry_at) + VALUES(${environmentId},${label},${began},${complete ? began : (previous?.full_at ?? null)},${retry}) + ON CONFLICT(origin) DO UPDATE SET read_at=excluded.read_at,full_at=excluded.full_at,retry_at=excluded.retry_at,label=excluded.label + WHERE excluded.read_at>=usage_archive_sync.read_at`; + }), + ); + }, Effect.mapError(fail)); + const changes = Effect.fn("UsageArchive.changes")(function* (input: { + cursor: number; + capture: boolean; + origin?: EnvironmentId; + }) { + const self = yield* environment.getDescriptor; + const environmentId = input.origin ?? self.environmentId; + const local = environmentId === self.environmentId; + if (input.capture && local) yield* capture(); + const [head] = yield* sql<{ + read_at: string; + label: string; + cursor: number; + }>`SELECT read_at,label,cursor FROM usage_archive_sync WHERE origin=${environmentId}`; + const seq = local ? sql`seq` : sql`json_extract(payload,'$.revision')`; + const rows = yield* sql<{ + revision: number; + payload: string; + read_at: string; + }>`SELECT ${seq} AS revision,payload,read_at FROM usage_archive WHERE origin=${environmentId} AND ${seq}>${input.cursor} AND ${seq}<=${local ? Number.MAX_SAFE_INTEGER : (head?.cursor ?? 0)} ORDER BY ${seq} LIMIT 13`; + const page: (typeof rows)[number][] = []; + let size = 0; + for (const row of rows) { + if (page.length >= 12 || (page.length && size + row.payload.length > 512 * 1024)) break; + page.push(row); + size += row.payload.length; + } + return { + environmentId, + label: head?.label ?? self.label, + readAt: head?.read_at ?? page.at(-1)?.read_at ?? iso(0), + from: input.cursor, + cursor: page.at(-1)?.revision ?? input.cursor, + more: rows.length > page.length, + days: page.map((row) => ({ + ...decodeDay(row.payload), + readAt: row.read_at, + revision: row.revision, + })), + }; + }, Effect.mapError(fail)); + const receive = Effect.fn("UsageArchive.receive")(function* (page: UsageArchivePage) { + if (page.environmentId === (yield* environment.getEnvironmentId) || page.cursor < page.from) + return yield* fail("Invalid usage archive origin or cursor"); + return yield* sql.withTransaction( + Effect.gen(function* () { + const [prev] = yield* sql<{ + cursor: number; + read_at: string; + }>`SELECT cursor,read_at FROM usage_archive_sync WHERE origin=${page.environmentId}`; + if ((prev?.cursor ?? 0) !== page.from) return prev?.cursor ?? 0; + for (const cell of page.days) yield* saveDay(page.environmentId, cell); + yield* sql`INSERT INTO usage_archive_sync(origin,label,read_at,cursor) VALUES(${page.environmentId},${page.label},${page.more ? (prev?.read_at ?? iso(0)) : page.readAt},${page.cursor}) + ON CONFLICT(origin) DO UPDATE SET label=excluded.label,read_at=excluded.read_at,cursor=excluded.cursor`; + return page.cursor; + }), + ); + }, Effect.mapError(fail)); + const read = Effect.fn("UsageArchive.read")(function* ( + input: UsageSummaryInput, + onlyLocal = false, + ) { + const own = yield* environment.getEnvironmentId; + const since = Date.parse(input.sinceDay + "T00:00:00Z"), + until = Date.parse(input.untilDay + "T00:00:00Z"); + if (!Number.isFinite(since) || !Number.isFinite(until) || since > until) + return yield* fail("Invalid usage window"); + if (input.resolution === "hour") { + const start = Date.parse(input.sinceTime ?? ""), + end = Date.parse(input.untilTime ?? ""); + if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start || end - start > DAY) + return yield* new UsageReadError({ + reason: "invalidWindow", + detail: "Expected a valid 24-hour usage window.", + }); + } + const entries = (yield* status).filter((entry) => (entry.environmentId === own) === onlyLocal); + const result: UsageArchiveCopy[] = []; + for (const entry of entries) { + const collector = yield* Effect.try({ + try: () => archiveWindow(input, entry.readAt), + catch: fail, + }); + let day = "", + source = ""; + while (true) { + const rows = yield* sql<{ + day: string; + source: string; + payload: string; + read_at: string; + }>`SELECT day,source,payload,read_at FROM usage_archive + WHERE origin=${entry.environmentId} AND day BETWEEN ${dayAt(since - DAY)} AND ${dayAt(until + DAY)} + AND (day,source)>(${day},${source}) ORDER BY day,source LIMIT 32`; + for (const row of rows) { + yield* Effect.try({ + try: () => collector.add({ ...decodeDay(row.payload), readAt: row.read_at }), + catch: fail, + }); + } + if (rows.length < 32) break; + const last = rows[rows.length - 1]!; + day = last.day; + source = last.source; + } + result.push({ ...entry, summary: collector.finish() }); + } + return result; + }, Effect.mapError(fail)); + const payments = sql<{ + provider_month: string; + cents: number; + updated_at: string; + }>`SELECT * FROM usage_subscription_payments`.pipe( + Effect.map((rows) => + Object.fromEntries( + rows.map((r) => [r.provider_month, { cents: r.cents, updatedAt: r.updated_at }]), + ), + ), + Effect.mapError(fail), + ); + const updatePayments = Effect.fn("UsageArchive.updatePayments")(function* ( + patch: Readonly>, + ) { + const at = DateTime.formatIso(yield* DateTime.now); + yield* sql.withTransaction( + Effect.forEach( + Object.entries(patch), + ([key, cents]) => + cents === null + ? sql`DELETE FROM usage_subscription_payments WHERE provider_month=${key}` + : sql`INSERT INTO usage_subscription_payments(provider_month,cents,updated_at) VALUES(${key},${cents},${at}) + ON CONFLICT(provider_month) DO UPDATE SET cents=excluded.cents,updated_at=excluded.updated_at`, + { discard: true }, + ), + ); + }, Effect.mapError(fail)); + return { status, capture, changes, receive, read, payments, updatePayments }; +} diff --git a/apps/server/src/usage/UsageArchivePeer.test.ts b/apps/server/src/usage/UsageArchivePeer.test.ts new file mode 100644 index 0000000000000..f8974f16ead3f --- /dev/null +++ b/apps/server/src/usage/UsageArchivePeer.test.ts @@ -0,0 +1,63 @@ +import { expect, it } from "@effect/vitest"; +import { AuthSessionId, USAGE_ARCHIVE_PEER_PATH } from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpRouter } from "effect/http"; +import { EnvironmentAuth } from "../auth/EnvironmentAuth.ts"; +import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; +import { descriptorOf } from "../peer/PeerLinks.testkit.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import migration from "../persistence/Migrations/120_UsageArchive.ts"; +import { UsageService } from "./UsageService.ts"; +import { archivePeerRoute } from "./UsageArchivePeer.ts"; + +it("serves only usage to a full-access peer, including when no GUI is open", async () => { + const descriptor = descriptorOf("origin", "Origin"); + const db = Layer.effectDiscard(migration).pipe( + Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })), + ); + const app = archivePeerRoute.pipe( + HttpRouter.provideRequest( + Layer.mergeAll( + db, + NodeCrypto.layer, + ServerSettingsService.layerTest({ linkedEnvironmentsEnabled: true }), + Layer.mock(ServerEnvironment)({ + getDescriptor: Effect.succeed(descriptor), + getEnvironmentId: Effect.succeed(descriptor.environmentId), + }), + Layer.mock(UsageService)({}), + Layer.mock(EnvironmentAuth)({ + authenticateMcpClient: (req) => + Effect.succeed({ + sessionId: AuthSessionId.make("test-client"), + label: "peer", + peerLink: req.headers["x-test-client"] !== "ordinary", + access: + req.headers["x-test-client"] === "limited" ? "approval-required" : "full-access", + }), + }), + ), + ), + ); + const { handler, dispose } = HttpRouter.toWebHandler(app, { disableLogger: true }); + try { + const request = (headers: Record) => + handler(new Request("http://localhost" + USAGE_ARCHIVE_PEER_PATH, { headers })); + expect((await request({ "x-test-client": "ordinary" })).status).toBe(403); + expect((await request({ "x-test-client": "limited" })).status).toBe(403); + expect((await request({ origin: "http://localhost" })).status).toBe(403); + const response = await request({}); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ + environmentId: "origin", + days: [], + cursor: 0, + more: false, + }); + } finally { + await dispose(); + } +}); diff --git a/apps/server/src/usage/UsageArchivePeer.ts b/apps/server/src/usage/UsageArchivePeer.ts new file mode 100644 index 0000000000000..a114d3e3f4053 --- /dev/null +++ b/apps/server/src/usage/UsageArchivePeer.ts @@ -0,0 +1,118 @@ +import { USAGE_ARCHIVE_PEER_PATH, UsageArchivePage, type EnvironmentId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { LINK_EXPIRES_AT_HEADER } from "../mcp/McpInvocationContext.ts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import { + HttpClient, + HttpClientRequest, + HttpRouter, + HttpServerRequest, + HttpServerResponse, +} from "effect/http"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import { EnvironmentAuth } from "../auth/EnvironmentAuth.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; +import { PeerLinks } from "../peer/PeerLinks.ts"; +import { UsageService } from "./UsageService.ts"; +import { makeUsageArchive } from "./UsageArchive.ts"; + +const empty = (status: number) => + HttpServerResponse.empty({ status, headers: { "cache-control": "no-store" } }); + +export const archivePeerRoute = HttpRouter.add( + "GET", + USAGE_ARCHIVE_PEER_PATH, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + if (request.headers.origin !== undefined) return empty(403); + const settings = yield* ServerSettingsService; + const limit = settings.managedPolicy?.limits?.maxRuntimeMode; + if ( + (limit && limit !== "full-access") || + !(yield* settings.getSettings).linkedEnvironmentsEnabled + ) + return empty(403); + const auth = yield* EnvironmentAuth; + const caller = yield* auth.authenticateMcpClient(request).pipe(Effect.option); + if (Option.isNone(caller)) return empty(401); + if (!caller.value.peerLink || caller.value.access !== "full-access") return empty(403); + const cursor = Number(new URLSearchParams(request.url.split("?")[1]).get("cursor") ?? 0); + if (!Number.isSafeInteger(cursor) || cursor < 0) return empty(400); + const archive = makeUsageArchive( + yield* SqlClient.SqlClient, + yield* UsageService, + yield* ServerEnvironment, + ); + const page = yield* archive.changes({ cursor, capture: false }); + return HttpServerResponse.jsonUnsafe(page, { + headers: { + "cache-control": "no-store", + ...(caller.value.linkExpiresAt + ? { [LINK_EXPIRES_AT_HEADER]: DateTime.formatIso(caller.value.linkExpiresAt) } + : {}), + }, + }); + }).pipe(Effect.orElseSucceed(() => empty(500))), +); + +export const replicateLinkedUsage = Effect.fn("UsageArchive.replicateLinked")(function* ( + archive: ReturnType, +) { + const links = yield* PeerLinks; + if (!(yield* links.enabled)) return; + const http = yield* HttpClient.HttpClient; + const stored = yield* archive.status; + const pull = Effect.fn("UsageArchive.pullPeer")(function* (id: EnvironmentId) { + const saved = yield* links.get(id); + if (Option.isNone(saved) || saved.value.access !== "full-access") return; + const remote = yield* links.resolve(id); + if (!remote.capabilities.usageArchive) return; + let cursor = stored.find((row) => row.environmentId === id)?.cursor ?? 0; + while (true) { + const request = HttpClientRequest.get(remote.url + USAGE_ARCHIVE_PEER_PATH).pipe( + HttpClientRequest.setUrlParam("cursor", String(cursor)), + HttpClientRequest.setHeader("authorization", "Bearer " + remote.token), + ); + const response = yield* http + .execute(request) + .pipe( + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), + Effect.timeout("10 seconds"), + ); + if (response.status !== 200) return; + const page = yield* response.json.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(UsageArchivePage)), + Effect.timeout("15 seconds"), + ); + if ( + page.environmentId !== id || + page.from !== cursor || + !(yield* links.enabled) || + Option.isNone(yield* links.get(id)) + ) + return; + const expiry = response.headers[LINK_EXPIRES_AT_HEADER]; + if (expiry) { + const renewed = DateTime.make(expiry); + if (Option.isSome(renewed)) yield* links.recordExpiry(id, renewed.value); + } + if ( + page.days.length || + !stored.some((r) => r.environmentId === id && r.readAt === page.readAt) + ) { + const next = yield* archive.receive(page); + if (next <= cursor || !page.more) return; + cursor = next; + } else return; + } + }); + yield* Effect.forEach( + yield* links.names, + (peer) => pull(peer.environmentId).pipe(Effect.ignore), + { concurrency: 2, discard: true }, + ); +}); diff --git a/apps/server/src/usage/UsageArchiveWorker.ts b/apps/server/src/usage/UsageArchiveWorker.ts new file mode 100644 index 0000000000000..0bfced76358e6 --- /dev/null +++ b/apps/server/src/usage/UsageArchiveWorker.ts @@ -0,0 +1,41 @@ +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; +import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; +import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; +import { UsageService } from "./UsageService.ts"; +import { replicateLinkedUsage } from "./UsageArchivePeer.ts"; +import { makeUsageArchive } from "./UsageArchive.ts"; + +export const usageArchiveWorker = Layer.effectDiscard( + Effect.gen(function* () { + const archive = makeUsageArchive( + yield* SqlClient.SqlClient, + yield* UsageService, + yield* ServerEnvironment, + ); + const orchestrator = yield* OrchestratorV2; + const pending = yield* Queue.sliding(1); + yield* Effect.forever( + replicateLinkedUsage(archive).pipe(Effect.ignore, Effect.andThen(Effect.sleep("15 seconds"))), + ).pipe(Effect.forkScoped); + yield* orchestrator.streamDomainEvents.pipe( + Stream.filter((e) => e.type === "provider-turn.updated" && e.payload.completedAt != null), + Stream.runForEach(() => Queue.offer(pending, undefined)), + Effect.forkScoped, + ); + yield* Effect.forever( + Effect.sleep("15 minutes").pipe(Effect.andThen(Queue.offer(pending, undefined))), + ).pipe(Effect.forkScoped); + yield* Queue.offer(pending, undefined); + yield* Effect.forever( + Queue.take(pending).pipe( + Effect.andThen(Effect.sleep("2 seconds")), + Effect.andThen(archive.capture()), + Effect.catchCause((cause) => Effect.logWarning("Usage archive capture failed", { cause })), + ), + ).pipe(Effect.forkScoped); + }), +); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 0189bb3b97471..a86d050a1dcb2 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -3888,6 +3888,13 @@ describe("UsageService", () => { const service = yield* UsageService.make; const first = yield* service.readSummary(window); assert.strictEqual(totalOutputTokens(first), 15); + const archived = yield* service.archiveSummary(window.sinceDay); + assert.strictEqual(totalOutputTokens(archived), 15); + assert.isTrue( + archived.buckets.some( + (bucket) => bucket.day < "2025-01-01" && bucket.hourStart !== undefined, + ), + ); yield* service.awaitPersisted; yield* Effect.promise(() => Promise.all(files.map((file) => NodeFSP.rm(file.path)))); const restarted = yield* UsageService.make; diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index bd4f2e62fbbfa..1d2f43e7db252 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -9,6 +9,7 @@ import { type UsageSummary, type UsageSummaryInput, UsageReadError, + UsageDay, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; @@ -166,6 +167,9 @@ const decodeCachedSources = Schema.decodeUnknownOption( export class UsageService extends Context.Service< UsageService, { + readonly archiveSummary: ( + sinceDay: UsageSummaryInput["sinceDay"], + ) => Effect.Effect; readonly readSummary: (input: UsageSummaryInput) => Effect.Effect; readonly refreshRates: Effect.Effect; readonly priceTurnRecords: ( @@ -837,6 +841,7 @@ export const make = Effect.gen(function* () { input: UsageSummaryInput, settings: ServerSettingsValue, provisional: boolean, + archiveMinutes = false, ) { if (input.sinceDay > input.untilDay) { return yield* new UsageReadError({ @@ -860,7 +865,7 @@ export const make = Effect.gen(function* () { const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value); const untilTimeMs = DateTime.toEpochMillis(untilTime.value); const durationMs = untilTimeMs - sinceTimeMs; - if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) { + if (durationMs <= 0 || (!archiveMinutes && durationMs > MAX_HOURLY_WINDOW_MS)) { return yield* new UsageReadError({ reason: "invalidWindow", detail: "Hourly usage window must be greater than zero and at most 24 hours", @@ -887,6 +892,7 @@ export const make = Effect.gen(function* () { ? 0 : Math.max(0, startedAtMs - settings.usageHistoryRetentionDays * 24 * 60 * 60 * 1000); + const scanCutoffMs = archiveMinutes ? 0 : retentionCutoffMs; const inWindow = usageTimestampFilter({ ...input, ...hourlyWindow }); const windowEndMs = hourlyWindow?.untilTimeMs ?? @@ -894,7 +900,7 @@ export const make = Effect.gen(function* () { const awaitRefresh = input.awaitRefresh === true; const collect = Effect.gen(function* () { - const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe( + const resolved = yield* resolveTranscriptDirs(settings, scanCutoffMs, awaitRefresh).pipe( Effect.provideContext(readerContext), ); // A window no complete scan has read would show partial totals, so every directory must cover it. @@ -909,14 +915,7 @@ export const make = Effect.gen(function* () { const [, scanned] = yield* Effect.all( [ fromMemory ? loadSavedRates : provisional ? ensureRates(false) : Effect.void, - collectDirs( - resolved, - windowStartMs, - settings, - retentionCutoffMs, - awaitRefresh, - fromMemory, - ), + collectDirs(resolved, windowStartMs, settings, scanCutoffMs, awaitRefresh, fromMemory), ], { concurrency: 2 }, ); @@ -932,7 +931,7 @@ export const make = Effect.gen(function* () { const sources: UsageSource[] = []; // Deleted transcripts' saved usage still aggregates and deduplicates normally. - const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs); + const retainedSinceMs = Math.max(windowStartMs, scanCutoffMs); // Saved paths are files below a scanned root, so their folder decides; folders repeat thousands of times. const withinDir = (dir: string) => { const foldersWithin = new Map(); @@ -1025,6 +1024,7 @@ export const make = Effect.gen(function* () { timeZone: input.timeZone, sinceDay: input.sinceDay, untilDay: input.untilDay, + archiveMinutes, resolution: input.resolution ?? "day", ...hourlyWindow, rates, @@ -1240,15 +1240,10 @@ export const make = Effect.gen(function* () { input.modelFilter ?? null, ]); - const readSummary = Effect.fn("UsageService.readSummary")(function* ( - requested: UsageSummaryInput, + const sharedScan = Effect.fn("UsageService.sharedScan")(function* ( + key: string, + scan: Effect.Effect, ) { - const { modelFilter: requestedFilter, ...unfiltered } = requested; - const modelFilter = canonicalModelFilter(requestedFilter); - const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter }; - const settings = yield* readSettings; - const provisional = input.provisional === true && input.awaitRefresh !== true; - const key = scanKey(input, settings, provisional); const deferred = yield* Effect.uninterruptible( Effect.gen(function* () { const existing = inflightScans.get(key); @@ -1259,7 +1254,7 @@ export const make = Effect.gen(function* () { inflightScans.set(key, created); // Detach so caller departure cannot cancel shared scans; finished scans warm the cache. // Register writes before releasing waiters, but start writing after delivering their summary. - yield* readWindow(input, settings, provisional).pipe( + yield* scan.pipe( Effect.onExit((exit) => Effect.sync(() => inflightScans.delete(key)).pipe( Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void), @@ -1274,6 +1269,18 @@ export const make = Effect.gen(function* () { return yield* Deferred.await(deferred); }); + const readSummary = Effect.fn("UsageService.readSummary")(function* ( + requested: UsageSummaryInput, + ) { + const { modelFilter: requestedFilter, ...unfiltered } = requested; + const modelFilter = canonicalModelFilter(requestedFilter); + const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter }; + const settings = yield* readSettings; + const provisional = input.provisional === true && input.awaitRefresh !== true; + const key = scanKey(input, settings, provisional); + return yield* sharedScan(key, readWindow(input, settings, provisional)); + }); + const priceTurnRecords = Effect.fn("UsageService.priceTurnRecords")(function* ( records: readonly PricedRecord[], ) { @@ -1287,7 +1294,32 @@ export const make = Effect.gen(function* () { return priceTurnUsage(rates, { ...record, model }, overrides); }); }); - return { readSummary, refreshRates, priceTurnRecords, awaitPersisted } as const; + const archiveSummary = Effect.fn("UsageService.archiveSummary")(function* ( + sinceDay: UsageSummaryInput["sinceDay"], + ) { + const now = yield* Clock.currentTimeMillis; + const until = DateTime.formatIso(DateTime.makeUnsafe(now + 1)); + const settings = yield* readSettings; + return yield* sharedScan( + encodeUsageRecordKey(["archive", sinceDay, settings]), + scanSummary( + { + sinceDay, + untilDay: UsageDay.make(until.slice(0, 10)), + timeZone: "UTC", + resolution: "hour", + sinceTime: sinceDay + "T00:00:00Z", + untilTime: until, + awaitRefresh: true, + ...(settings.usageModelFilter ? { modelFilter: settings.usageModelFilter } : {}), + }, + settings, + false, + true, + ).pipe(Effect.map((result) => result.summary)), + ); + }); + return { readSummary, archiveSummary, refreshRates, priceTurnRecords, awaitPersisted } as const; }); export const layer = Layer.effect(UsageService, make); diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index a42b48dd775f1..6faeb4b89697a 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -73,6 +73,7 @@ export interface AggregateOptions { readonly rateModel?: (provider: UsageRecord["provider"], model: string) => string | undefined; readonly modelFilter?: UsageModelFilter; readonly resolution?: UsageResolution; + readonly archiveMinutes?: boolean; readonly sinceTimeMs?: number; readonly untilTimeMs?: number; } @@ -121,7 +122,10 @@ export function resolveModelAliases( } /** Matches original IDs, so an alias cannot pull excluded usage into a kept model. */ -function keepsUsageRecord(filter: UsageModelFilter | undefined, record: UsageRecord): boolean { +export function keepsUsageRecord( + filter: UsageModelFilter | undefined, + record: Pick, +): boolean { if (filter === undefined) return true; const model = record.model.trim(); const matches = (selector: UsageModelSelector) => @@ -321,7 +325,10 @@ export class UsageAggregator { const hourIndex = this.#hourlyWindow === null ? -1 - : Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS); + : Math.floor( + (record.timestampMs - this.#hourlyWindow.sinceTimeMs) / + (this.#options.archiveMinutes ? 60_000 : HOUR_MS), + ); return this.#bucketFor(day, hourIndex, record.provider, record.model, source); } @@ -401,7 +408,11 @@ export class UsageAggregator { } const window = this.#hourlyWindow; const hourStart = - window === null ? "" : new Date(window.sinceTimeMs + hourIndex * HOUR_MS).toISOString(); + window === null + ? "" + : new Date( + window.sinceTimeMs + hourIndex * (this.#options.archiveMinutes ? 60_000 : HOUR_MS), + ).toISOString(); const key = `${day}\u0000${hourStart}\u0000${provider}\u0000${model}\u0000${source}`; let bucket = this.#buckets.get(key); if (bucket === undefined) { @@ -465,6 +476,7 @@ export class UsageAggregator { unpricedRecords: bucket.unpricedRecords, unpricedTokens: bucket.unpricedTokens, sessions: bucket.sessions.size, + ...(this.#options.archiveMinutes ? { archiveSessions: [...bucket.sessions] } : {}), }); } buckets.sort( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ce647d46405b1..f1a1b9ada166e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -268,6 +268,7 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import { commandFeatureUsage, featureUsage } from "./telemetry/FeatureUsage.ts"; import type { TelemetryOwner } from "./telemetry/Identify.ts"; import * as UsageService from "./usage/UsageService.ts"; +import { makeUsageArchive } from "./usage/UsageArchive.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as TriageService from "./triage/TriageService.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; @@ -1625,6 +1626,7 @@ export const layerWsRpc = ( ), ); const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + const usageArchive = makeUsageArchive(sql, usage, serverEnvironment); const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; const rpcClientIds = yield* Ref.make(new Set()); yield* Effect.addFinalizer(() => @@ -2915,7 +2917,22 @@ export const layerWsRpc = ( processResourceMonitor.readHistory(input), [WS_METHODS.serverGetResourceTelemetryHistory]: (input) => resourceTelemetry.readHistory(input), - [WS_METHODS.serverGetUsageSummary]: (input) => usage.readSummary(input), + [WS_METHODS.usagePaymentsRead]: () => usageArchive.payments, + [WS_METHODS.usagePaymentsUpdate]: ({ payments }) => usageArchive.updatePayments(payments), + [WS_METHODS.usageArchiveStatus]: () => usageArchive.status, + [WS_METHODS.usageArchiveExport]: (input) => usageArchive.changes(input), + [WS_METHODS.usageArchiveImport]: (input) => usageArchive.receive(input), + [WS_METHODS.usageArchiveRead]: (input) => usageArchive.read(input), + [WS_METHODS.serverGetUsageSummary]: (input) => + input.savedHistory + ? usageArchive + .read(input, true) + .pipe( + Effect.flatMap(([own]) => + own ? Effect.succeed(own.summary) : usage.readSummary(input), + ), + ) + : usage.readSummary(input), [WS_METHODS.serverRefreshUsageRates]: (_input) => usage.refreshRates, [WS_METHODS.serverRetryResourceTelemetry]: (_input) => resourceTelemetry.retry, [WS_METHODS.serverCheckOtlpEndpoint]: (input) => otlpEndpointCheck.check(input), diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 4b44c66ad3c71..3d5707721dfb2 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -33,7 +33,7 @@ const usageCommandOrder = new Map( ].map((command, index) => [command, index]), ); -const firstUsageCommand = METRIC_OPTIONS[0].command; +const firstUsageCommand = "usage.cost"; function compareCommands( left: KeybindingCommand, diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index f4aa54b160eb2..2ec16c852991b 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -1,3 +1,6 @@ +import { usagePeriod } from "@t3tools/shared/usagePayments"; +import { Input } from "../ui/input"; +import { UsageReport, UsageSyncStatus } from "./UsageReport"; import { ChatGptUsageButton } from "../settings/ChatGptUsageButton"; import { usesChatGptSharing } from "@t3tools/shared/usageLimits"; import { RefreshIcon } from "~/components/ui/refresh-icon"; @@ -91,7 +94,7 @@ import { tokenTypeSegments, } from "./usageBreakdown"; import { - METRIC_OPTIONS, + DISPLAY_METRIC_OPTIONS as METRIC_OPTIONS, WINDOW_OPTIONS, resolveUsageShortcut, type UsageMetric, @@ -113,7 +116,7 @@ function isUsageMetric(value: string | null | undefined): value is UsageMetric { } function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] { - return WINDOW_OPTIONS.some((option) => option.days === value); + return Number.isInteger(value) && value >= 1 && value <= 36525; } const providerLabel = (provider: UsageProviderKind) => PROVIDER_PRESENTATION[provider].label; @@ -176,7 +179,17 @@ function UsageModelDialogHost({ } export function UsagePage() { + const [section, setSection] = useState<"summary" | "report" | "sync">("summary"); + const [reportWindow, setReportWindow] = useState(() => usagePeriod("year")); const [preferences, setPreferences] = useState(readUsagePagePreferences); + const [customDays, setCustomDays] = useState( + String( + WINDOW_OPTIONS.some((o) => o.days === preferences.windowDays) ? 37 : preferences.windowDays, + ), + ); + const [customOpen, setCustomOpen] = useState( + !WINDOW_OPTIONS.some((o) => o.days === preferences.windowDays), + ); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const hour12 = usePrimarySettings((settings) => resolveHour12(settings.timestampFormat)); const gt = useGT(); @@ -185,6 +198,7 @@ export function UsagePage() { const shortcutTitle = ( option: (typeof METRIC_OPTIONS)[number] | (typeof WINDOW_OPTIONS)[number], ) => { + if (option.command === null) return m(option.label); const shortcut = shortcutLabelForCommand(keybindings, option.command, { context: { usagePageOpen: true }, }); @@ -201,7 +215,7 @@ export function UsagePage() { ), })); const metric = preferences.metric; - const showingLimits = metric === "limits"; + const showingLimits = section === "summary" && metric === "limits"; const [isRefreshing, setIsRefreshing] = useState(false); const [limitsNow, setLimitsNow] = useState(() => Date.now()); const refreshingRef = useRef(false); @@ -210,7 +224,10 @@ export function UsagePage() { const [selectedEnvironmentIds, setSelectedEnvironmentIds] = useState | null>(null); const hiddenProviders = new Set(preferences.hiddenProviders); - const { days: windowDays, window } = windowSelection; + const { days: windowDays } = windowSelection; + const range = section === "report" ? reportWindow : windowSelection.window; + const archived = section === "report" || metric === "subscription"; + const window = archived ? { ...range, savedHistory: true } : range; const isPast24Hours = windowDays === 1; const { merged: answeredUsage, @@ -242,7 +259,8 @@ export function UsagePage() { setPreferences(nextPreferences); saveUsagePagePreferences(nextPreferences); }; - const selectWindow = (days: number) => { + const selectWindow = (days: number, custom = false) => { + setCustomOpen(custom); if (!isUsageWindowDays(days)) return; updatePreferences({ windowDays: days }); setWindowSelection({ @@ -290,6 +308,7 @@ export function UsagePage() { modalActionsRef.current?.close(); return; } + if (section !== "summary" || !command) return; const metricOption = METRIC_OPTIONS.find((option) => option.command === command); const periodOption = WINDOW_OPTIONS.find((option) => option.command === command); if (!metricOption && !periodOption) return; @@ -408,114 +427,128 @@ export function UsagePage() { /> - {!showingLimits ? ( + {section === "summary" && !showingLimits ? ( {windowLabel} ) : null} -
    - {/* Limits are always current, so they have no period. The period sits before the metric + {section === "summary" && ( +
    + {/* Limits are always current, so they have no period. The period sits before the metric tabs so dropping it never moves them. */} - {showingLimits ? null : ( + {showingLimits ? null : ( + { + const value = next[0]; + if (value === "custom") setCustomOpen(true); + else if (value) selectWindow(Number(value)); + }} + > + {WINDOW_OPTIONS.map((option) => ( + + {m(option.label)} + + ))} + {gt("Custom")} + + )} { const value = next[0]; - if (value) selectWindow(Number(value)); + if (isUsageMetric(value)) selectMetric(value); }} > - {WINDOW_OPTIONS.map((option) => ( - + {METRIC_OPTIONS.map((option) => ( + {m(option.label)} ))} - )} - { - const value = next[0]; - if (isUsageMetric(value)) selectMetric(value); - }} - > - {METRIC_OPTIONS.map((option) => ( - - {m(option.label)} - - ))} - - -
    -
    - {showingLimits ? null : ( - + value === "custom" ? setCustomOpen(true) : selectWindow(Number(value)) + } + > + + + {customOpen ? gt("Custom") : windowOptionLabel && m(windowOptionLabel)} + + + + {WINDOW_OPTIONS.map((option) => ( + + {m(option.label)} + + ))} + {gt("Custom")} + + + )} + - )} - - -
    + + +
    + )} ); @@ -529,7 +562,57 @@ export function UsagePage() { - {selectedEnvironments.length === 0 ? ( + { + if (value === "summary" || value === "report" || value === "sync") + setSection(value); + }} + > + {gt("Summary")} + {gt("Usage report")} + {gt("Synchronization")} + + {section === "summary" && !showingLimits && customOpen && ( +
    { + e.preventDefault(); + if (isUsageWindowDays(Number(customDays))) selectWindow(Number(customDays), true); + }} + > + + +
    + )} + {section === "sync" ? ( + + ) : section === "report" || metric === "subscription" ? ( +