From 48f6dc09119bd95cceb6a3b2936bf39f4a39d161 Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Mon, 23 Nov 2026 07:39:19 +0000 Subject: [PATCH] fix(fork): resolve upstream merge 9dc36169b4 (2026-11-22) Resolve the 24 conflicts of commit A (1640512383) and fix the breaks the merge brought. - Keep both sides in the server, settings, file preview and adapter conflicts; the fork's change sits on upstream's code. - Drop the fork's early port of Codex full-access approvals (#206): upstream shipped its own fix (#40773). - Re-port the fork's chat Markdown changes onto upstream's Words renderer (#27866) through apps/web/src/fork/forkMarkdown.ts and hooks in wordsHast.ts: single tilde in agent text, CJK bold, CJK link ends, board links, \eps in math, the Dashboard renderer; the sanitizer's board and t3-dashboard protocols move to markdownHast.ts. - CheckpointCaptureService takes upstream's commit id: #31349's lock and reread let only one attempt of a run commit a capture. Commit A keeps the per-attempt queued capture effect id; the fork steer test pins it and now models the order the lock allows. - Upstream's virtualized Markdown list (#40631) keeps no reading place for now: the fork's binding for it is dropped and will be rebuilt (orbitingflea/t3code#264). README notes this and the 1-64 MB text files loaded in parts. The fork's panel test follows upstream's routing of large text files. - Upstream code now loads the fork's chat Markdown and chunk reload guard in tests: the whiteboard hover handler is imported from boardChannel (no re-export from the Markdown pass), and the chunk reload build key lives in chunkReloadGuard.ts. - Workflow agent links decode the run-result shape of t3_thread_send; the fork's CLI commands join upstream's feedback command list; fork tests mock upstream's new services; agent context budget 67360. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- apps/server/src/cli/thread.ts | 4 - .../src/environment/ServerEnvironment.ts | 5 +- apps/server/src/feedback/FeedbackReport.ts | 2 + apps/server/src/fork/fyi/Fyi.test.ts | 3 +- apps/server/src/fork/fyi/Fyi.ts | 5 +- .../server/src/fork/generalRoleParity.test.ts | 4 + .../Adapters/ClaudeAdapterV2.ts | 7 - .../Adapters/CodexAdapterV2.test.ts | 30 ---- .../Adapters/CodexAdapterV2.ts | 21 +-- .../CheckpointCaptureService.ts | 8 - .../src/orchestration-v2/ProjectionStore.ts | 3 - .../ProviderSessionManager.ts | 77 +------- .../ProviderTurnStartService.ts | 34 +--- .../SteeringCompletion.integration.test.ts | 15 +- .../src/orchestration-v2/runtimeLayer.ts | 3 - .../src/provider/Drivers/AntigravityDriver.ts | 8 +- .../src/provider/agentContextBudget.json | 8 +- .../src/workflows/WorkflowAgentLinks.ts | 4 +- apps/web/src/components/ChatMarkdown.tsx | 165 +++--------------- .../components/ComposerPromptEditorTiptap.tsx | 2 +- .../chat/ComposerPendingUserInputPanel.tsx | 2 +- .../src/components/chat/MarkdownFileLink.tsx | 98 ++--------- apps/web/src/components/chat/MathTypeset.tsx | 50 ------ .../src/components/chat/ProposedPlanCard.tsx | 4 +- .../components/chat/TimelineWorkEntryRow.tsx | 8 +- .../components/chat/TimelineWorkGroupRows.tsx | 12 +- .../chat/UserMessageContextChips.tsx | 4 +- .../components/chat/timelineMinimapItems.ts | 19 +- .../composerContextPresentation.tsx | 4 +- .../src/components/files/FilePreviewPanel.tsx | 8 - .../fileReadingPosition.browser.test.tsx | 74 ++------ .../components/files/fileReadingTestKit.tsx | 11 +- .../settings/settingsSearch.test.ts | 3 - .../src/components/settings/settingsSearch.ts | 9 - .../useAvailableSettingsSearchItems.ts | 7 +- .../components/workflows/WorkflowRunFeed.tsx | 2 + apps/web/src/fork/chunkReloadBuild.ts | 10 -- apps/web/src/fork/cjkLinkEnd.test.tsx | 69 +++++--- apps/web/src/fork/cjkLinkEnd.ts | 153 +++++++++------- .../src/fork/dashboard/dashboardMarkdown.tsx | 42 ++--- apps/web/src/fork/forkMarkdown.test.ts | 97 ++++++++++ apps/web/src/fork/forkMarkdown.ts | 114 ++++++++++++ .../whiteboard/markdown-whiteboard.test.ts | 44 ++--- .../fork/whiteboard/markdown-whiteboard.ts | 80 +++++---- apps/web/src/lib/chunkReloadGuard.ts | 13 +- apps/web/src/markdown/wordsHast.ts | 14 +- fork/whiteboard/run-t3.md | 2 +- packages/contracts/src/environment.ts | 3 - packages/contracts/src/orchestratorMcp.ts | 2 +- packages/shared/src/markdownHast.ts | 2 + packages/shared/src/markdownPipeline.ts | 130 -------------- 52 files changed, 571 insertions(+), 929 deletions(-) delete mode 100644 apps/web/src/components/chat/MathTypeset.tsx delete mode 100644 apps/web/src/fork/chunkReloadBuild.ts create mode 100644 apps/web/src/fork/forkMarkdown.test.ts create mode 100644 apps/web/src/fork/forkMarkdown.ts diff --git a/README.md b/README.md index 45a1770d1200c..1496dbb2e6f70 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ This is a fork of T3 Code that integrates a few additional features, including: - **Compact when idle for Claude threads:** a choice in Settings → Providers → Advanced → Compact idle threads. Besides compacting before the prompt cache expires, it compacts a large idle Claude thread (default 400K tokens or more) a set time (default 15 minutes) after the last message or answer from a user or a bot, so the compaction runs while no one waits for a reply. The token counts and the wait are set right under the choice. - **Prune idle worker threads:** `t3 prune-worker-threads` deletes the messages, turn items, nodes, plans and runtime requests of idle worker threads. A worker thread is idle when it has no open run and, in the last 7 days, was not created, had no run requested or ended, and had no turn item or message updated. A worker thread is a subagent thread that an agent started. Subagent threads that a bot starts are workers too. Threads a person opens, bot threads themselves and a person's forks are never workers. An idle worker keeps its rows while recovery still needs the worker, or while a thread that keeps its own rows names the worker as parent or fork source. Pruned threads keep their thread row, runs, parent link and pull request links, so they still show up and open with no messages. The command runs only when you call it, so run it daily to keep worker transcripts from piling up. Other threads still grow the database. With `--dry-run`, the command only prints how many threads it would empty and how many rows it would delete. You can run the command while the server runs. - **One way to start subagents in Claude and Codex threads:** T3 Code starts Claude and Codex sessions without the provider's own subagent tools: Claude's `Agent`, `Workflow`, `SendMessage` and `ListAgents`, and Codex's `spawn_agent` with its other collaboration tools. The agent starts every subagent, same provider and model included, with T3 Code's `delegate_task` tool, so each child is a T3 Code thread that you can open and follow. -- **Files remember where you stopped reading:** a file in the right panel opens where you left it when you switch back to its tab, close and reopen it, or reload the app. This covers code, Markdown, PDFs, large text files, CSV and TSV tables, HTML pages, Word and PowerPoint files, the first sheet of an Excel or ODS spreadsheet, notebooks, Mermaid diagrams and chat attachments; video and audio come back paused at the time you left. If the file changed, it opens at the same place, or at its start or end when that place is gone. Places stay in this browser for 30 days. A link to a line still jumps to that line once. PDFs in the right panel open in T3 Code's own PDF viewer, also in Chrome and Edge on the desktop. Image zoom, fonts, archives, SQLite files, ODT, ODP, RTF and EPUB files, HTML attachments and the other sheets of a spreadsheet still open at the top. A place in a notebook cell after the first 20 opens at the end of cell 20. +- **Files remember where you stopped reading:** a file in the right panel opens where you left it when you switch back to its tab, close and reopen it, or reload the app. This covers code, Markdown source, PDFs, large text files, CSV and TSV tables, HTML pages, Word and PowerPoint files, the first sheet of an Excel or ODS spreadsheet, notebooks, Mermaid diagrams and chat attachments; video and audio come back paused at the time you left. If the file changed, it opens at the same place, or at its start or end when that place is gone. Places stay in this browser for 30 days. A link to a line still jumps to that line once. PDFs in the right panel open in T3 Code's own PDF viewer, also in Chrome and Edge on the desktop. Image zoom, fonts, archives, SQLite files, ODT, ODP, RTF and EPUB files, HTML attachments, the other sheets of a spreadsheet and rendered workspace Markdown still open at the top. Text files of 1 MB to 64 MB open in source view in parts after the first megabyte, so past 1 MB a saved place may not be restored and a line link may stop at the end of the text loaded so far. [Issue #264](https://github.com/orbitingflea/t3code/issues/264) tracks support for rendered workspace Markdown and these 1 MB to 64 MB text files. A place in a notebook cell after the first 20 opens at the end of cell 20. - **Reflink worktrees on Linux:** Settings → Worktrees → Reflink worktrees (on by default) clones new worktrees copy-on-write from a cache of recent checkouts on the worktree location's drive, so worktrees share disk space until files change. Drives that cannot clone, such as ext4, use Git's normal checkout. - **FYI messages between agents:** an agent can send another thread an FYI, a note of at most 16,000 characters that needs no action and starts no turn. The receiving agent gets it with its next turn; a running Claude Code thread gets it at its next tool call. An FYI counts as delivered only when the turn that carries it finishes: a turn that fails, is stopped, restarts or is reverted gives it back, so the agent may see it twice. When a thread has an FYI waiting and has been idle for 6 hours, T3 Code wakes it to deliver its FYIs, unless the thread is settled, archived, waiting for your answer or holds queued messages; a snoozed thread waits until its snooze ends. The 6 hours count from the thread's last turn, or from the reset of a usage limit that stopped it on the provider it still uses (or from the end of a snooze that ends after that reset), so an FYI to a thread that has been idle longer wakes it within minutes. A thread whose usage limit has no known reset time, or whose provider fails every turn, gets a failed wake every 6 hours while an FYI waits. A wake carries up to 16,000 characters of FYIs. The rest, and any that a wake gives back because it failed or you stopped it, get another wake after 6 more idle hours. A wake is a new turn, so **Resume** no longer continues a turn that ended before it. Settle or archive a thread to stop its wakes. The timeline marks these messages "FYI · waiting", "FYI · sent" while the turn that carries them runs, and "FYI" once it finished. - **Open server files by their path:** in a browser signed in to T3 Code at its own address, open `/` (such as `https://t3.example.com/home/ana/work/report.html`) to see that file read-only, for files under the server user's home folder and temp folder. A session needs the `filesystem:read` permission, and a signed-out browser gets a sign-in page. Text and code of any type show as plain text, and images, PDFs, audio and video show as themselves. A folder shows its `index.html`, or else a list of its files. Links ending in `:line` or `:line:col` open the file. Names that start with `.`, and T3 Code's own data folder, are not served. An HTML page runs in a sandboxed frame at the same address: its scripts run but cannot act as you in T3, and it loads files from its own folder and below for an hour, though its scripts cannot fetch them. A page directly in the home or temp folder loads no other files. An HTML page linked from another site, or any HTML page over plain HTTP, first shows an Open link. diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index f039536cbf724..3ba496d1a522b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -250,15 +250,11 @@ export type ThreadTools = ReturnType; * outside agent does, and revokes that session when the command ends. */ export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* ( -<<<<<<< origin/main - flags: { readonly baseDir: Option.Option; readonly json: boolean }, -======= flags: { readonly baseDir: Option.Option; readonly json: boolean; readonly clientLabel?: string; }, ->>>>>>> upstream/main run: (tools: ThreadTools) => Effect.Effect, ) { const logLevel = yield* GlobalFlag.LogLevel; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 223979c7e2808..504f00f81d254 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -311,11 +311,8 @@ export const make = Effect.gen(function* () { mcpHostedApproval: true, shellThreadFamilies: true, shellOlderSettled: true, -<<<<<<< origin/main - ...(yield* whiteboardPanelCapabilities()), -======= agentFeedback: true, ->>>>>>> upstream/main + ...(yield* whiteboardPanelCapabilities()), }, }; diff --git a/apps/server/src/feedback/FeedbackReport.ts b/apps/server/src/feedback/FeedbackReport.ts index f7c026700b0e8..0262fa6b01cfb 100644 --- a/apps/server/src/feedback/FeedbackReport.ts +++ b/apps/server/src/feedback/FeedbackReport.ts @@ -158,6 +158,8 @@ export const T3_CLI_COMMANDS: ReadonlyArray = [ "t3 thread start", "t3 thread send", "t3 thread show", + "t3 thread user-view", + "t3 prune-worker-threads", "t3 feedback", "t3 feedback list", "t3 workflow", diff --git a/apps/server/src/fork/fyi/Fyi.test.ts b/apps/server/src/fork/fyi/Fyi.test.ts index dde27d9a61803..056d83d63d820 100644 --- a/apps/server/src/fork/fyi/Fyi.test.ts +++ b/apps/server/src/fork/fyi/Fyi.test.ts @@ -116,7 +116,8 @@ describe("turnCarriesFyi", () => { ["a prose message", "Fix the flaky test", [], false, true], ["/compact", "/compact", [], false, false], ["a slash command after spaces", " /review", [], false, false], - ["a slash message with an image", "/look at this", [{}], false, true], + ["a slash message with an image", "/look at this", [{}], false, false], + ["a path", "/srv/app/notes.md has the plan", [], false, true], ["a goal command", "/goal ship it", [], true, false], ["a skill mention", "$deploy ship it", [], false, false], ["a skill mention with another sigil after spaces", " €review the plan", [], false, false], diff --git a/apps/server/src/fork/fyi/Fyi.ts b/apps/server/src/fork/fyi/Fyi.ts index aa7af4129dbee..a7406d7867fee 100644 --- a/apps/server/src/fork/fyi/Fyi.ts +++ b/apps/server/src/fork/fyi/Fyi.ts @@ -17,6 +17,8 @@ import { type TurnItemId, } from "@t3tools/contracts"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; + +import { isSlashCommandMessage } from "../../orchestration-v2/ContextHandoffDelivery.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -79,7 +81,8 @@ export function turnCarriesFyi(input: { !input.goalCommand && !input.resumesNatively && !(message.createdBy === "agent" && message.creationSource === "provider") && - !(message.attachments.length === 0 && message.text.trimStart().startsWith("/")) && + // A slash command reaches the provider verbatim, attachments or not, so it carries none. + !isSlashCommandMessage({ role: "user", text: message.text }) && !LEADING_SKILL_MENTION.test(message.text) ); } diff --git a/apps/server/src/fork/generalRoleParity.test.ts b/apps/server/src/fork/generalRoleParity.test.ts index 7abb7963aeca1..714b70bc839e2 100644 --- a/apps/server/src/fork/generalRoleParity.test.ts +++ b/apps/server/src/fork/generalRoleParity.test.ts @@ -47,6 +47,7 @@ import { ThreadDashboard } from "./threadDashboard/ThreadDashboard.ts"; import { UserView } from "./userView/UserView.ts"; import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; import * as EnvironmentTheme from "../environmentTheme.ts"; +import { FeedbackStore } from "../feedback/FeedbackStore.ts"; import { GitManager } from "../git/GitManager.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; import { IssueService } from "../issue/IssueService.ts"; @@ -91,6 +92,7 @@ import * as ServerSettings from "../serverSettings.ts"; import { SourceControlRepositoryService } from "../sourceControl/SourceControlRepositoryService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts"; +import { Workflows } from "../workflows/Workflows.ts"; import { TaskFolders } from "../workspace/TaskFolders.ts"; const projectId = ProjectId.make("project:general-role-parity"); @@ -693,6 +695,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(UserView)({}), Layer.mock(DisplayModeWrap)({ forgetNotesAfterCompaction: () => (ingest) => ingest }), Layer.mock(DocumentText)({}), + Layer.mock(FeedbackStore)({}), Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}), Layer.mock(GitVcsDriver.GitVcsDriver)({}), Layer.mock(GitManager)({}), @@ -730,6 +733,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(TaskFolders)({}), Layer.mock(ThreadSearch)({}), Layer.mock(VcsStatusBroadcaster)({}), + Layer.mock(Workflows)({}), ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); const decodeToolsList = Schema.decodeUnknownEffect( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 6ff7329910411..614a24c73cd20 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1696,14 +1696,10 @@ export const layerQueryRunner: Layer.Layer< ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), env: { ...(sdkOptions.env ?? hostEnvironment), -<<<<<<< origin/main ...claudeTerminalToolEnvironment, ...DELEGATE_ONLY_PROVIDERS.claudeAgent.hide.environment, - ...(input.resume -======= // The CLI would re-run a failed request by itself, then run the resume prompt as a second turn. ...(input.resume && !endsOnFailedRequest ->>>>>>> upstream/main ? { CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1", CLAUDE_CODE_RESUME_REASON: "user_resume", @@ -2559,15 +2555,12 @@ export function makeClaudeQueryOptions(input: { }, } as ClaudeSdkSettings); const deviceInstructions = input.mcpServers !== undefined && input.deviceToolsAvailable === true; -<<<<<<< origin/main const hooks = { ...input.hooks, ...(deviceInstructions ? { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] } : {}), ...(input.onStop === undefined ? {} : { Stop: [{ hooks: [input.onStop] }] }), }; -======= const agentFeedback = input.mcpServers === undefined ? "off" : (input.agentFeedback ?? "off"); ->>>>>>> upstream/main const options: ClaudeAgentSdkQueryOptions = { model: compiledSelection.apiModelId, // T3 names threads; a supplied title skips Claude's redundant naming request. diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 6299f41d611e8..aea174821f2a4 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2105,9 +2105,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); -<<<<<<< origin/main - it.effect("accepts dangerous-command approvals in full-access without asking", () => -======= it.effect.each([ { name: "dangerous command", networkApprovalContext: undefined, asks: false }, { @@ -2116,7 +2113,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { asks: true, }, ] as const)("full access asks about a $name: $asks", ({ networkApprovalContext, asks }) => ->>>>>>> upstream/main Effect.gen(function* () { const nativeThreadId = "command-approval-thread"; const nativeTurnId = "command-approval-turn"; @@ -2138,22 +2134,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { itemId: "exec-rm", command: "/bin/bash -lc 'rm -rf ./node_modules'", startedAtMs: 0, -<<<<<<< origin/main - }, - }, - }, - { type: "expect_outbound", frame: { id: 0, result: { decision: "accept" } } }, - { - type: "emit_inbound", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, - }, - }, -======= ...(networkApprovalContext === undefined ? {} : { networkApprovalContext }), }, }, @@ -2173,7 +2153,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, ] as const)), ->>>>>>> upstream/main ], }), (event) => @@ -2196,14 +2175,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { harness.firstTerminal.pipe(Effect.as(undefined)), Queue.take(pending), ); -<<<<<<< origin/main - assert.isUndefined(request, "Full access must not wait for a command approval"); - assert.equal(yield* Queue.size(pending), 0, "Full access must not show a command approval"); - assert.deepEqual( - harness.terminalEvents().map((event) => event.status), - ["completed"], - ); -======= assert.equal(request?.kind, asks ? "command" : undefined); if (!asks) { assert.deepEqual( @@ -2211,7 +2182,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { ["completed"], ); } ->>>>>>> upstream/main }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 46a4012ae146f..10b46bde3b866 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6128,12 +6128,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } -<<<<<<< origin/main - // Codex still asks for commands it deems dangerous under the granular full-access policy. - if ( - context.input.runtimePolicy.runtimeMode === "full-access" && - context.input.runtimePolicy.approvalPolicy === undefined -======= // T3's Full access policy is granular, under which Codex still asks before commands it // deems dangerous. Managed-network asks enforce the user's allowlist, so they still ask. if ( @@ -6142,7 +6136,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( context.input.runtimePolicy.sandboxPolicy === undefined && payload.networkApprovalContext == null && (payload.proposedNetworkPolicyAmendments ?? []).length === 0 ->>>>>>> upstream/main ) { return { decision: "accept", @@ -7873,17 +7866,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(yield* Ref.get(settledTurns)), ...(yield* Ref.get(activeTurns)), ]); -<<<<<<< origin/main - const started = yield* client.request( - "turn/start", - withCodexCommandNote(turnStartParams, turnInput.message.messageId, commandNote), - ); - if (commandNote !== undefined) yield* commandNote.delivered; -======= const started = yield* client - .request("turn/start", turnStartParams) + .request( + "turn/start", + withCodexCommandNote(turnStartParams, turnInput.message.messageId, commandNote), + ) .pipe(withAppServerDeadline("turn/start")); ->>>>>>> upstream/main + if (commandNote !== undefined) yield* commandNote.delivered; const previousTurn = previousTurns.get(started.turn.id) ?? (yield* Ref.get(activeTurns)).get(started.turn.id); diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index c6f9952627fc0..dd7f27079a4e5 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -208,15 +208,7 @@ export const layer: Layer.Layer< ], { concurrency: 2 }, ); -<<<<<<< origin/main - // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. - const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run; - const commandId = CommandId.make( - `command:effect:checkpoint.capture:${run.activeAttemptId ?? run.id}`, - ); -======= const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`); ->>>>>>> upstream/main const checkpointEvent = (payload: OrchestrationV2Checkpoint) => Effect.map(ids.allocate.event({ threadId: input.threadId, commandId }), (id) => ({ id, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 5000bfcdba995..d5ce6d6950f6e 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -102,11 +102,8 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; -<<<<<<< origin/main import { SEND_TO_USER_PAYLOAD_LIKE } from "@t3tools/shared/displayModes"; -======= import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; ->>>>>>> upstream/main import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import * as ShownHistory from "../fork/shownHistory/ShownHistory.ts"; import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b0d4893e77ca2..9c521fd6495dc 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2766,83 +2766,12 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => -<<<<<<< origin/main startBusyTurn( input, - runtime.startTurn(input).pipe(turnMetrics("send", input.modelSelection.model)), -======= - observeActivity( - providerSessionId, - ensureThreadAttached({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - }), - ).pipe( - // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. - Effect.andThen( - holdThreadLoaded({ - providerSessionId, - threadId: input.threadId, - providerThread: input.providerThread, - }), - ), - Effect.andThen( - Effect.acquireUseRelease( - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), - runtime, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.activity-failed", { - providerSessionId, - cause, - }).pipe(Effect.as(true)), - ), - // A release between attach and markBusy leaves nothing to mark: fail the - // start instead of running it on a runtime being torn down. - Effect.flatMap((marked) => - marked - ? Effect.void - : Effect.fail( - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause: "The provider session was released while the turn started.", - }), - ), - ), - ), - () => - agentFeedbackMode.pipe( - Effect.flatMap((agentFeedback) => - runtime.startTurn({ ...input, agentFeedback }), - ), - turnMetrics("send", input.modelSelection.model), - ), - (_, exit) => - Exit.isFailure(exit) - ? observeActivity( - providerSessionId, - markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), - ).pipe( - // A failed start can leave its native thread gone (Claude rejecting a - // resume), so the next start must ask the adapter to resume it again. - Effect.andThen( - forgetProviderThreadLoaded({ - providerSessionId, - threadId: input.threadId, - runtime, - }), - ), - ) - : Effect.void, - ), + agentFeedbackMode.pipe( + Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), + turnMetrics("send", input.modelSelection.model), ), ->>>>>>> upstream/main ), ...(compactThread === undefined ? {} diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 5365c8fb78706..69d7b3a89cb52 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1049,7 +1049,6 @@ export const layer: Layer.Layer< projection.providerTurns, projection.attempts, ); -<<<<<<< origin/main const turnFyi = yield* fyiDelivery.forTurn({ threadId: run.threadId, message: providerMessage, @@ -1058,13 +1057,11 @@ export const layer: Layer.Layer< (run.restartContinuationOfRunId !== undefined && !noteContinuation) || (manualResume && unsentResumeMessage === undefined), }); -======= let compactionMessageIdSet: ReadonlySet | undefined; const compactionMessageIds = () => (compactionMessageIdSet ??= new Set( projection.messages.filter(isSlashCommandMessage).map((candidate) => candidate.id), )); ->>>>>>> upstream/main const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, providerTurns: projection.providerTurns, @@ -1929,6 +1926,7 @@ export const layer: Layer.Layer< retryHandoff.attachments.length > 0 || sideChatHandoff !== undefined || restartNote !== "" || + turnFyi.text !== "" || noteContinuation; // Pending context turns the resume into a prompted turn, which needs no native resume. if ( @@ -1947,7 +1945,6 @@ export const layer: Layer.Layer< }); return; } -<<<<<<< origin/main const noteContext = DisplayModeWrap.noteContextAtTurnStart({ sameNativeThread, handoffCount: effectiveHandoffs.length, @@ -1958,9 +1955,6 @@ export const layer: Layer.Layer< wrapped = yield* displayModeWrap.wrapUserText({ ...wrapInput, context: noteContext }); userText = wrapped.text; } - const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); -======= ->>>>>>> upstream/main const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2130,14 +2124,11 @@ export const layer: Layer.Layer< ], }); }); -<<<<<<< origin/main const acceptingSession = DisplayModeWrap.deliveringNote(session, wrapped); -======= let inlineDeliveredHandoffs: ReadonlyArray = []; let promptDroppedOnTerminal = false; const inlineDeliveryLock = yield* Semaphore.make(1); const retryHandoffIds = new Set(retryHandoff.handoffs.map((handoff) => handoff.id)); ->>>>>>> upstream/main const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ @@ -2170,9 +2161,6 @@ export const layer: Layer.Layer< sideChatHandoff === undefined || compact || slashCommand ? "" : sideChatHandoff.summaryText; -<<<<<<< origin/main - const context = [delivery.context, sideChatContext, restartNote, turnFyi.text] -======= // Record inline handoffs before startTurn so an immediate dropped terminal can restore them. inlineDeliveredHandoffs = [ ...delivery.inlineHandoffs.map((handoff) => @@ -2182,8 +2170,7 @@ export const layer: Layer.Layer< ), ...(sideChatContext === "" || sideChatHandoff === undefined ? [] : [sideChatHandoff]), ]; - const context = [delivery.context, sideChatContext, restartNote] ->>>>>>> upstream/main + const context = [delivery.context, sideChatContext, restartNote, turnFyi.text] .filter((part) => part !== "") .join("\n\n"); const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput; @@ -2286,22 +2273,9 @@ export const layer: Layer.Layer< }), ), ); -<<<<<<< origin/main - const deliverySession = - effectiveHandoffs.length === 0 && - retryHandoff.handoffs.length === 0 && - retryHandoff.attachments.length === 0 && - sideChatHandoff === undefined && - restartNote === "" && - turnFyi.text === "" && - !noteContinuation - ? acceptingSession - : makeDeliverySession(acceptingSession, startWithHandoffs); -======= const deliverySession = carriesPendingContext - ? makeDeliverySession(session, startWithHandoffs) - : session; ->>>>>>> upstream/main + ? makeDeliverySession(acceptingSession, startWithHandoffs) + : acceptingSession; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 033d74a58c20b..4922d817c03c0 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1402,13 +1402,13 @@ it.effect("restarts the turn for an image when native steering takes text only", ); it.effect.each(["completed", "interrupted"] as const)( - "checkpoints a run that a steer restarted after its first answer was checkpointed (restart %s)", + "checkpoints a run that a steer restarted before its first answer was checkpointed (restart %s)", (restartEnd) => Effect.gen(function* () { const steerReadRunning = yield* Deferred.make(); const letSteerCommit = yield* Deferred.make(); const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `steer-restart-after-checkpoint-${restartEnd}`, + `steer-restart-before-checkpoint-${restartEnd}`, true, false, Effect.void, @@ -1480,10 +1480,7 @@ it.effect.each(["completed", "interrupted"] as const)( }) .pipe(Effect.forkScoped); yield* Deferred.await(steerReadRunning); - const firstCompleted = yield* runReaches("completed"); yield* endTurn(started[0]!, "completed"); - const firstCapture = yield* worker.drain().pipe(Effect.forkScoped); - yield* Fiber.join(firstCompleted); const restartRunning = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( (event) => @@ -1497,8 +1494,12 @@ it.effect.each(["completed", "interrupted"] as const)( ); yield* Deferred.succeed(letSteerCommit, undefined); yield* Fiber.join(steer); - yield* Fiber.join(firstCapture); - yield* worker.drain(); + // The first answer's capture finds the run restarting and retries until it gives up; the + // restarted attempt starts behind it on the thread's effect lane. + for (const delay of [0, 100, 200, 400, 800]) { + yield* TestClock.adjust(delay); + yield* worker.drain(); + } yield* Fiber.join(restartRunning); yield* (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock(threadId, Effect.void); assert.equal(started.length, 2); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 536e4e3451d08..d1f67723c6d72 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -65,16 +65,13 @@ import * as ThreadForkService from "./ThreadForkService.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; -<<<<<<< origin/main import * as DisplayModeWrap from "../fork/displayModeWrap/DisplayModeWrap.ts"; import * as FyiDelivery from "../fork/fyi/FyiDelivery.ts"; import * as FyiWakeWorker from "../fork/fyi/FyiWakeWorker.ts"; import * as ThreadDashboard from "../fork/threadDashboard/ThreadDashboard.ts"; import * as UserView from "../fork/userView/UserView.ts"; import * as SubThreads from "../fork/subThreads/SubThreads.ts"; -======= import * as FeedbackStore from "../feedback/FeedbackStore.ts"; ->>>>>>> upstream/main import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; import * as TaskFolderStore from "../workspace/TaskFolderStore.ts"; diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index e5b5e363e102a..093d8666b318c 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -603,10 +603,6 @@ export const AntigravityDriver: ProviderDriver< probeUsage: usage.probe, clearUsage: usage.clear, auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, -<<<<<<< origin/main - supportsTextGeneration: runtimeState.pipe( - Effect.flatMap((state) => isAntigravityTextGenerationAvailable(state.root)), -======= ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}), rememberRuntimeModes: (modes) => writeFileStringAtomically({ @@ -617,8 +613,8 @@ export const AntigravityDriver: ProviderDriver< Effect.provideService(Path.Path, path), Effect.catch(() => Effect.logWarning("Could not save Antigravity permission modes.")), ), - supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( ->>>>>>> upstream/main + supportsTextGeneration: runtimeState.pipe( + Effect.flatMap((state) => isAntigravityTextGenerationAvailable(state.root)), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), Effect.orElseSucceed(() => false), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 5f19fb99ce6d1..9ddc4254d9fea 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,11 +1,5 @@ { -<<<<<<< origin/main "claudeSystemAppendBytes": 5945, "codexAdditionalContextBytes": 7339, - "mcpToolListJsonBytes": 64688 -======= - "claudeSystemAppendBytes": 6245, - "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 61724 ->>>>>>> upstream/main + "mcpToolListJsonBytes": 67360 } diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 6a0836fc0162c..17afc658b2cd4 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -4,7 +4,7 @@ import { OrchestratorMcpFailure, OrchestratorMcpThreadInterruptResult, OrchestratorMcpThreadReadResult, - OrchestratorMcpThreadSendResult, + OrchestratorMcpThreadSendRunResult, OrchestratorMcpThreadWaitResult, } from "@t3tools/contracts"; import * as Duration from "effect/Duration"; @@ -170,7 +170,7 @@ export const make = Effect.gen(function* () { input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; if (input.thread !== undefined) { if (input.launch !== undefined) return yield* launchOnContinue; - const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendResult, { + const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendRunResult, { threadId: input.thread, message: input.prompt, mode: "queue", diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index eaf67d10224df..7dd8bd7ac2878 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -21,20 +21,7 @@ import { AuthOrchestrationOperateScope, SOURCE_CONTROL_MEDIA_ASSET, } from "@t3tools/contracts"; -<<<<<<< origin/main -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - ASSISTANT_MARKDOWN_REMARK_PLUGINS, - ASSISTANT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -======= import { chatMarkdownImageSource } from "@t3tools/shared/markdownHast"; ->>>>>>> upstream/main import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -100,24 +87,12 @@ import React, { useState, type ReactNode, } from "react"; -<<<<<<< origin/main -import type { - Components, - ExtraProps as ReactMarkdownExtraProps, - Options as ReactMarkdownOptions, -} from "react-markdown"; -import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; -import { postWhiteboardHover, remarkWhiteboardLinks } from "../fork/whiteboard/markdown-whiteboard"; +import { postWhiteboardHover } from "../fork/whiteboard/boardChannel"; import { chatAnchorPanelLinks } from "../fork/rightPanelSplit/chatAnchorLink"; import { openedSync } from "../fork/rightPanelSplit/linkSources"; import { type OpenedSurface, startPanelLinkDrag } from "../fork/rightPanelSplit/panelLinkDrag"; import { showBoardRef } from "../fork/whiteboard/boardChannel"; -import { remarkEndLinksAtCjkPunctuation } from "../fork/cjkLinkEnd"; import { DashboardLinkChip, parseDashboardHref } from "../fork/dashboard/dashboardLink"; -import type { Pluggable, PluggableList } from "unified"; -import { defaultUrlTransform } from "react-markdown"; -======= ->>>>>>> upstream/main import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; @@ -463,7 +438,7 @@ type MarkdownComponents = { // react-markdown's defaultUrlTransform: relative URLs, and absolute ones with a safe protocol. const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp)$/i; -function safeUrl(value: string): string { +export function safeUrl(value: string): string { const colon = value.indexOf(":"); const before = (character: string) => { const at = value.indexOf(character); @@ -538,13 +513,8 @@ function blockFileLinkSources( text: string, cwd: string | undefined, imageBaseDir: string | undefined, -<<<<<<< origin/main - peerPaths: readonly string[] = [], - hostFileOrigins: readonly string[] = [], -): string { -======= + hostFileOrigins: readonly string[], ): BlockFileLinkSources { ->>>>>>> upstream/main const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) .filter((href) => !parseComposerContextHref(href)) .map(decodeMarkdownLinkEscapes) @@ -553,9 +523,6 @@ function blockFileLinkSources( const spans = extractInlineCodeSpans(text).filter((span) => resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), ); -<<<<<<< origin/main - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)], peerPaths]); -======= return { hrefs, spans }; } @@ -569,12 +536,14 @@ function fileLinkSourcesKey( cwd: string | undefined, imageBaseDir: string | undefined, streamingBlocks: ReadonlyArray | null, + peerPaths: readonly string[] = [], + hostFileOrigins: readonly string[] = [], ): string { if (!streamingBlocks) { - const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir); - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir, hostFileOrigins); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)], peerPaths]); } - const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000`; + const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000${hostFileOrigins.join("\u0001")}\u0000`; const hrefs = new Set(); const spans = new Set(); const last = streamingBlocks.length - 1; @@ -583,7 +552,7 @@ function fileLinkSourcesKey( const key = config + block; let sources = index === last ? undefined : finishedBlockFileLinkSources.get(key); if (!sources) { - sources = blockFileLinkSources(block, cwd, imageBaseDir); + sources = blockFileLinkSources(block, cwd, imageBaseDir, hostFileOrigins); if (index !== last) { if (cachedBlockChars + key.length > MAX_CACHED_BLOCK_CHARS) { finishedBlockFileLinkSources.clear(); @@ -596,8 +565,7 @@ function fileLinkSourcesKey( for (const href of sources.hrefs) hrefs.add(href); for (const span of sources.spans) spans.add(span); } - return JSON.stringify([[...hrefs], [...spans]]); ->>>>>>> upstream/main + return JSON.stringify([[...hrefs], [...spans], peerPaths]); } function resolveFileLinkSources( @@ -624,30 +592,6 @@ function resolveFileLinkSources( return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; } -<<<<<<< origin/main -function useChatMarkdownState({ - text, - inline = false, - cwd, - agentDirectories, - threadRef, - pullRequestPanelRef, - environmentId: explicitEnvironmentId, - onTaskListChange, - isStreaming = false, - skills = EMPTY_MARKDOWN_SKILLS, - onUseArtifactTemplate, - onRunShellCommand, - imageBaseDir, - workspaceMutationId, - onImageExpand, - renderContextReference, - headingLevelOffset = 0, - sourceControlMedia = false, - sourceControlMediaRepository, - fileLinkPeerPaths, -}: ChatMarkdownProps) { -======= function useChatMarkdownState( { text, @@ -669,10 +613,10 @@ function useChatMarkdownState( headingLevelOffset = 0, sourceControlMedia = false, sourceControlMediaRepository, + fileLinkPeerPaths, }: ChatMarkdownProps, streamingBlocks: ReadonlyArray | null, ) { ->>>>>>> upstream/main const gt = useGT(); const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); @@ -870,13 +814,9 @@ function useChatMarkdownState( // Keyed by the file links found, not the text, so streamed text that adds none keeps the // renderer context, and every block reading it, unchanged. // A template literal marks the key as a string, so the compiler memoizes the maps on its value. -<<<<<<< origin/main // A file chip opens in a thread, so only a thread's links to its environment's files become chips. const hostFileOrigins = useHostFileOrigins(threadRef?.environmentId ?? null); - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, fileLinkPeerPaths, hostFileOrigins)}`; -======= - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; ->>>>>>> upstream/main + const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null, fileLinkPeerPaths, hostFileOrigins)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath); @@ -1035,20 +975,12 @@ function useChatMarkdownState( } return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); }; -<<<<<<< origin/main const openFileInPanel = ( fileLinkMeta: MarkdownFileLinkMeta, panelPath: string, ...options: [OpenFileOptions?] ): OpenedSurface | Promise => { if (!threadRef) return null; - const openAt = (path: string) => - openedSync(rightPanelHostRef(threadRef), () => - useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line, ...options), - ); -======= - const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { - if (!threadRef) return; // The panel reads relative paths from the thread's folder. A pull request body's `cwd` is the // checkout of its repository, which can be another folder. const shell = readThreadShell(threadRef); @@ -1058,16 +990,18 @@ function useChatMarkdownState( (project) => project.environmentId === environmentId && project.id === shell?.projectId, )?.workspaceRoot; const openAt = (path: string) => - useRightPanelStore - .getState() - .openFile( - threadRef, - cwd && panelRoot !== undefined && cwd !== panelRoot - ? resolveWorkspaceFilePath(path, cwd) - : path, - fileLinkMeta.line, - ); ->>>>>>> upstream/main + openedSync(rightPanelHostRef(threadRef), () => + useRightPanelStore + .getState() + .openFile( + threadRef, + cwd && panelRoot !== undefined && cwd !== panelRoot + ? resolveWorkspaceFilePath(path, cwd) + : path, + fileLinkMeta.line, + ...options, + ), + ); if ( fileLinkMeta.workspaceLookupPath === null || !cwd || @@ -2024,29 +1958,7 @@ const CHAT_MARKDOWN_COMPONENTS = { }, } satisfies MarkdownComponents; -<<<<<<< origin/main -const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; -const FORK_REMARK_PLUGINS = [remarkWhiteboardLinks, remarkEndLinksAtCjkPunctuation]; -// Shared lists, so every message with the same options shares a processor and its cache. -const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: [...CHAT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - breaks: [...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, ...FORK_REMARK_PLUGINS], - math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, ...FORK_REMARK_PLUGINS], -} satisfies Record; -const ASSISTANT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: [...ASSISTANT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - breaks: [...ASSISTANT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, ...FORK_REMARK_PLUGINS], - math: [REMARK_MATH, ...ASSISTANT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - mathBreaks: [ - REMARK_MATH, - ...ASSISTANT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - ...FORK_REMARK_PLUGINS, - ], -} satisfies Record; -======= const markdownOptions = new WeakMap>(); ->>>>>>> upstream/main /** One options object per configuration, so equal messages share a renderer and its cache. */ function wordsOptions( @@ -2055,7 +1967,7 @@ function wordsOptions( ): WordsHastOptions { let byFlags = markdownOptions.get(extensions); if (!byFlags) markdownOptions.set(extensions, (byFlags = new Map())); - const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}`; + const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}${+!!flags.agentText}${+!!flags.boardLinks}${+!!flags.inline}`; let options = byFlags.get(key); if (!options) byFlags.set(key, (options = { ...flags, extensions })); return options; @@ -2236,36 +2148,15 @@ function ChatMarkdown({ const bindMarkdownRef = (node: HTMLElement | null) => { markdownRef.current = node; }; -<<<<<<< origin/main - const sharedRemarkPlugins = ( - assistantReply ? ASSISTANT_MARKDOWN_REMARK_PLUGIN_SETS : CHAT_MARKDOWN_REMARK_PLUGIN_SETS - )[ - componentState.mathEnabled - ? lineBreaks - ? "mathBreaks" - : "math" - : lineBreaks - ? "breaks" - : "plain" - ]; - // The incremental parser keeps per-instance state, so its output is not shared. - const uncachedPlugins = incrementalParsing; - const remarkPlugins = incrementalParsing - ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] - : withExtraPlugins( - hasInsights - ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) - : sharedRemarkPlugins, - extraRemarkPlugins, - ); -======= const markdown = wordsOptions(extensions, { math: componentState.mathEnabled, breaks: lineBreaks, escapeHtml: !parseRawHtml, insights: renderInsights && text.includes("★ Insight"), + agentText: assistantReply, + boardLinks: true, + inline, }); ->>>>>>> upstream/main const blocks = streamingBlocks ?? [text]; return ( diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 897a78932efe5..9bd09d45046eb 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -126,7 +126,7 @@ import { primaryServerKeybindingsAtom } from "~/state/server"; import { hasCommandForKeyDown } from "~/shortcuts/dispatcher"; import { basenameOfPath } from "~/pierre-icons"; import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon"; -import { postWhiteboardHover } from "../fork/whiteboard/markdown-whiteboard"; +import { postWhiteboardHover } from "../fork/whiteboard/boardChannel"; import { FileTagChipContent } from "./chat/FileTagChip"; import { SkillChipPopover, skillPopoverDescription } from "./chat/SkillInlineText"; import { AssistantCitationChip } from "./chat/AssistantCitationChip"; diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index 1c26e54cf0375..c22e0d2f52927 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -268,7 +268,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( text={activeQuestion.question} cwd={cwd} threadRef={threadRef} - // Fork: selects the agent-text single-tilde list, so a question's "1~2" keeps its tilde. + // Fork: agent text, so a question's "1~2" keeps its tilde. assistantReply lineBreaks className={cn("pt-0.5 text-foreground/85", questionTextAlign)} diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index aa0e33330c29b..827469667f3b5 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -361,12 +361,24 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ const chip = hasPrimaryAction ? ( { + if (nativeDrag.draggable) nativeDrag.onDragStart(event); + else + startPanelLinkDrag( + event, + fileChipPanelLink(threadRef, panelPath, (path, options) => + onOpenInPanel(path, line, options), + ), + ); + }} kind={chipKind} dir="ltr" render={} + aria-label={labelPrefix === undefined ? undefined : `${labelPrefix}${label}`} className={MARKDOWN_FILE_LINK_CLASS_NAME} data-markdown-copy={copyMarkdown} onClick={(event) => { + if (leavesFileChipClickToBrowser(href, event)) return; event.preventDefault(); event.stopPropagation(); if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { @@ -388,6 +400,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ path={iconPath} environmentId={environmentId} label={label} + labelPrefix={labelPrefix} theme={theme} /> @@ -397,7 +410,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ kind={chipKind} dir="ltr" render={