From 90c028c6fc4a9ecd3af048cb52432e819af6487c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 12:06:15 -0800 Subject: [PATCH 1/7] fix(server): a slow disk no longer freezes the service while it writes a log line (#39857) --- apps/server/src/serviceLauncher.ts | 42 +++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 51662f7be3309..8dcd7886fce51 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -88,6 +88,42 @@ const runtimeSpawnArguments = (paths: ReturnType) => ({ args: ["serve"], }); +function isRegularFile(fd: number): boolean { + try { + return NodeFS.fstatSync(fd).isFile(); + } catch { + return false; + } +} + +const MAX_PENDING_OUTPUT_BYTES = 8 * 1024 * 1024; + +/** + * Node writes to a regular file synchronously, so a server whose output is the log file freezes + * while the filesystem stalls one append. It gets a pipe instead, drained here without backpressure; + * output beyond the cap is dropped while a write is stuck. + */ +function appendOutput(source: NodeJS.ReadableStream, fd: number): void { + let pending: Array = []; + let pendingBytes = 0; + let writing = false; + const flush = (): void => { + writing = pending.length > 0; + if (!writing) return; + const chunk = Buffer.concat(pending, pendingBytes); + pending = []; + pendingBytes = 0; + // Best effort, like the launcher's own diagnostics: a failed append drops that output. + NodeFS.write(fd, chunk, flush); + }; + source.on("data", (chunk: Buffer) => { + if (pendingBytes + chunk.length > MAX_PENDING_OUTPUT_BYTES) return; + pending.push(chunk); + pendingBytes += chunk.length; + if (!writing) flush(); + }); +} + /** * The unit or launch agent that `t3 service install` wrote. Its program names * the runtime that ran the install, and a remote update never replaces it, so @@ -1179,13 +1215,17 @@ export class Launcher { ...(update === undefined ? {} : { update }), }; const spawnArguments = runtimeSpawnArguments(paths); + const appendStdout = this.#output === undefined && isRegularFile(1); + const appendStderr = this.#output === undefined && isRegularFile(2); const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, { env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) }, stdio: this.#output === undefined - ? ["inherit", "inherit", "inherit", "ipc"] + ? ["inherit", appendStdout ? "pipe" : "inherit", appendStderr ? "pipe" : "inherit", "ipc"] : ["ignore", this.#output, this.#output, "ipc"], }); + if (child.stdout !== null) appendOutput(child.stdout, 1); + if (child.stderr !== null) appendOutput(child.stderr, 2); await new Promise((resolve, reject) => { const onError = (error: Error) => reject(error); child.once("error", onError); From 9294a9801e804646dbce0cad78fea1102e6c98ce Mon Sep 17 00:00:00 2001 From: Charles Bine <8898759+charlesbine@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:09:40 -0400 Subject: [PATCH 2/7] fix(acp,web): stop showing "Running Ran" for commandless ACP tool calls (#39837) Co-authored-by: Julius Marminge --- apps/mobile/src/lib/threadActivity.test.ts | 31 +++++ apps/mobile/src/lib/threadActivity.ts | 12 +- .../Adapters/AcpAdapterV2.test.ts | 116 ++++++++++++++++++ .../MessagesTimeline.active-tools.test.ts | 51 +++++++- .../components/chat/MessagesTimeline.logic.ts | 25 ++-- .../src/work-log/presentation.ts | 37 ++++++ packages/provider-acp/src/server/adapter.ts | 8 +- 7 files changed, 260 insertions(+), 20 deletions(-) diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 175ef5b4bab3c..f6880a2611b1b 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -740,6 +740,37 @@ describe("buildThreadFeed", () => { expect(summarizeToolGroup([activity.workEntry]).summary).toBe("Changed 3 files"); }); + it("labels a running command without command text by its status", () => { + const item: OrchestrationV2TurnItem = { + ...base("commandless", "2026-06-20T00:00:02.000Z", 1), + type: "command_execution", + title: "Ran command", + status: "running", + completedAt: null, + runId: null, + input: "", + }; + const feed = buildThreadFeed([ + projected({ ...userMessage(), runId: null }, 0), + projected(item, 1), + ]); + const activity = feed.flatMap((entry) => + entry.type === "activity-group" ? entry.activities : [], + )[0]!; + expect(workEntryRowLabel(activity.workEntry)).toBe("Running command"); + const presented = deriveThreadFeedPresentation( + feed, + null, + new Set(), + new Set(), + "2026-06-20T00:00:01.000Z", + true, + ); + expect(presented.find((entry) => entry.type === "activity-group")).toMatchObject({ + activities: [{ live: true, groupStandIn: { label: "Running command" } }], + }); + }); + it("anchors feedback before later committed turns", () => { const laterUser = { ...userMessage("2026-08-29T00:00:05.000Z"), diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 4254404a39a99..64364f9dcf97d 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -21,6 +21,7 @@ import { commandProgramName, } from "@t3tools/client-runtime/work-log/command-label"; import { + commandlessCommandLabel, contextCompactionLabel, liveThoughtLine, toolItemForDisplay, @@ -300,6 +301,12 @@ export function workEntryRowLabel( const presentation = resolveWorkEntryToolPresentation(entry, undefined, resolve); if (presentation) return presentation.displayName; if (entry.command?.trim()) return compactWorkEntryText(commandDisplayText(entry.command)); + const commandless = commandlessCommandLabel( + entry, + liveActivityToolStatus(entry.toolLifecycleStatus, false), + resolve, + ); + if (commandless) return commandless; const action = toolGroupAction(entry); const isToolRead = action === "read" && entry.itemType === "dynamic_tool"; if (action === "code-search" || action === "search") { @@ -2424,7 +2431,10 @@ function liveToolActivitySummary( ? resolve(msg("Stopped {program}", { program })) : resolve(msg("Ran {program}", { program })); } - return compactWorkEntryText(activity.detail ?? activity.summary); + return ( + commandlessCommandLabel(activity.workEntry, status, resolve) ?? + compactWorkEntryText(activity.detail ?? activity.summary) + ); } interface ThreadFeedBuild { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index a0aa6ed3130f8..f15217896e271 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -11980,6 +11980,122 @@ describe("AcpAdapterV2", () => { ); }).pipe(Effect.provide(layerTest)), ); + + it.effect("leaves command_execution input empty when the tool call carries no command", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const promptStarted = yield* Deferred.make(); + const promptGate = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("acp-test-empty-command-input"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Deferred.succeed(promptStarted, undefined).pipe( + Effect.andThen(Deferred.await(promptGate)), + ), + }), + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-empty-command-input"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-empty-command-input"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); + yield* Deferred.await(promptStarted); + + const sessionId = "mock-session-1"; + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "tool_call", + toolCallId: "call-exec-no-cmd", + title: "Run command", + kind: "execute", + status: "in_progress", + rawInput: {}, + }, + }); + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "tool_call", + toolCallId: "call-monitor-no-cmd", + title: "Monitor", + kind: "other", + status: "in_progress", + rawInput: { variant: "monitor" }, + }, + }); + yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); + + const commandItems: Array<{ + readonly nativeId: string | null | undefined; + readonly status: string; + readonly input: string; + }> = []; + let terminal = false; + while (!terminal) { + const event = yield* Queue.take(events); + if (event.type === "turn_item.updated" && event.turnItem.type === "command_execution") { + commandItems.push({ + nativeId: event.turnItem.nativeItemRef?.nativeId, + status: event.turnItem.status, + input: event.turnItem.input, + }); + } + if (event.type === "turn.terminal") { + terminal = true; + } + } + + assert.deepEqual(commandItems, [ + { nativeId: "call-exec-no-cmd", status: "running", input: "" }, + { nativeId: "call-monitor-no-cmd", status: "running", input: "" }, + { nativeId: "call-exec-no-cmd", status: "completed", input: "" }, + { nativeId: "call-monitor-no-cmd", status: "completed", input: "" }, + ]); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts b/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts index b689f11c66016..d05bbdcf32557 100644 --- a/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts @@ -1,6 +1,10 @@ import { RunId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { deriveMessagesTimelineRows, liveWorkEntryLabel } from "./MessagesTimeline.logic"; +import { + deriveMessagesTimelineRows, + liveWorkEntryLabel, + workEntryDisplayLabel, +} from "./MessagesTimeline.logic"; describe("long active tool groups", () => { it.each([false, true])( @@ -49,3 +53,48 @@ describe("long active tool groups", () => { }, ); }); + +describe("liveWorkEntryLabel for a command execution without a command", () => { + it.each([ + { + status: "inProgress" as const, + active: true, + toolTitle: "Ran command", + expected: "Running command", + }, + { + status: "inProgress" as const, + active: true, + toolTitle: "Command", + expected: "Running command", + }, + { + status: "failed" as const, + active: false, + toolTitle: "Ran command", + expected: "Failed command", + }, + { + status: "failed" as const, + active: false, + toolTitle: "Run command", + expected: "Failed command", + }, + ])( + "labels a $status entry titled $toolTitle as $expected", + ({ status, active, toolTitle, expected }) => { + const entry = { + id: "work-empty-command", + createdAt: "2026-10-12T00:00:00Z", + label: "Ran command", + toolTitle, + tone: "tool" as const, + itemType: "command_execution" as const, + command: "", + toolLifecycleStatus: status, + }; + expect(liveWorkEntryLabel(entry, undefined, active)).toBe(expected); + expect(workEntryDisplayLabel(entry, undefined)).toBe(expected); + }, + ); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 2192c3b7e6ae0..124062303e0cf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -20,6 +20,8 @@ import { commandProgramName, } from "@t3tools/client-runtime/work-log/command-label"; import { + commandlessCommandLabel, + genericCommandStatusLabel, liveActivityToolStatus, normalizeCompactToolLabel, resolveWorkEntryToolPresentation, @@ -157,6 +159,12 @@ export function workEntryDisplayLabel( const toolPresentation = resolveWorkEntryToolPresentation(entry, undefined, resolve); if (toolPresentation) return toolPresentation.displayName; if (entry.command?.trim()) return commandDisplayText(entry.command); + const commandless = commandlessCommandLabel( + entry, + liveActivityToolStatus(entry.toolLifecycleStatus, false), + resolve, + ); + if (commandless) return commandless; const action = toolGroupAction(entry); if (action === "code-search" || action === "search") { const searchLabel = @@ -271,17 +279,7 @@ export function liveWorkEntryLabel( if (command) { const program = commandProgramName(command); if (program == null) { - return resolve( - status === "inProgress" - ? msg("Running command") - : status === "failed" - ? msg("Failed command") - : status === "declined" - ? msg("Declined command") - : status === "stopped" - ? msg("Stopped command") - : msg("Ran command"), - ); + return genericCommandStatusLabel(status, resolve); } return resolve( status === "inProgress" @@ -295,7 +293,10 @@ export function liveWorkEntryLabel( : msg("Ran {program}", { program }), ); } - return workEntryDisplayLabel(entry, workspaceRoot, resolve); + return ( + commandlessCommandLabel(entry, status, resolve) ?? + workEntryDisplayLabel(entry, workspaceRoot, resolve) + ); } export function workEntryIsVisibleInGroup( diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index a838bc9794c65..676f147a3d7ef 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -255,6 +255,43 @@ export function liveActivityToolStatus(status: string | undefined, presentTense: return "completed"; } +export function genericCommandStatusLabel( + status: ReturnType, + resolve: MFunctionType = mFallback, +) { + return resolve( + status === "inProgress" + ? msg("Running command") + : status === "failed" + ? msg("Failed command") + : status === "declined" + ? msg("Declined command") + : status === "stopped" + ? msg("Stopped command") + : msg("Ran command"), + ); +} + +const GENERIC_COMMAND_TITLES = new Set(["Ran command", "Run command", "Command"]); + +export function commandlessCommandLabel( + entry: Pick< + WorkLogPresentationEntry, + "itemType" | "command" | "toolTitle" | "label" | "structuredPayload" + >, + status: ReturnType, + resolve: MFunctionType = mFallback, +): string | null { + if (entry.itemType !== "command_execution" || entry.command?.trim()) return null; + // The provider's own title, before a client substitutes its translated fallback. + const title = ( + entry.structuredPayload ? entry.structuredPayload.title : entry.toolTitle || entry.label + )?.trim(); + return !title || GENERIC_COMMAND_TITLES.has(normalizeCompactToolLabel(title)) + ? genericCommandStatusLabel(status, resolve) + : null; +} + export function resolveWorkEntryToolPresentation( entry: Pick< WorkLogPresentationEntry, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d25274bb9a4ce..a78c40556381f 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -4801,7 +4801,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( turnItem = { ...base, type: "command_execution", - input: toolCall.command ?? monitorCommand ?? toolCall.title ?? "Command", + input: toolCall.command ?? monitorCommand ?? "", ...(textFromUnknown(rawOutput) === undefined ? {} : { output: textFromUnknown(rawOutput) }), @@ -4850,11 +4850,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( turnItem = { ...base, type: "command_execution", - input: - toolCall.command ?? - monitorCommand ?? - toolCall.title ?? - (inputVariant === "monitor" ? "Monitor" : "Command"), + input: toolCall.command ?? monitorCommand ?? "", ...(textFromUnknown(rawOutput) === undefined ? {} : { output: textFromUnknown(rawOutput) }), From 1cb3a8c753047efc4fa00600105f5388de8fd7eb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 12:10:48 -0800 Subject: [PATCH 3/7] feat: read a linked environment's threads from the client (#39406) Co-authored-by: Claude Fable 5.2 --- apps/mobile/src/Stack.tsx | 5 + .../components/ComposerEditor.ios.test.tsx | 2 +- apps/mobile/src/components/ComposerEditor.tsx | 9 +- .../features/threads/LinkedThreadSheet.tsx | 383 ++++++++++++++++++ .../features/threads/ProviderSubagentBar.tsx | 6 +- .../features/threads/ReadOnlyComposerBar.tsx | 14 + .../features/threads/ThreadAgentsSheet.tsx | 42 +- .../src/features/threads/ThreadFeed.tsx | 32 +- .../threads/thread-subagent-group.tsx | 33 +- .../threads/threadAgentsPresentation.ts | 35 +- .../src/features/threads/useOpenThreadLink.ts | 45 ++ apps/mobile/src/i18n/translations/de.json | 25 +- apps/mobile/src/i18n/translations/en.json | 25 +- apps/mobile/src/i18n/translations/es.json | 25 +- apps/mobile/src/i18n/translations/fr.json | 25 +- apps/mobile/src/i18n/translations/ja.json | 25 +- apps/mobile/src/i18n/translations/ko.json | 25 +- apps/mobile/src/i18n/translations/pt-BR.json | 25 +- apps/mobile/src/i18n/translations/ru.json | 25 +- apps/mobile/src/i18n/translations/sv.json | 25 +- apps/mobile/src/i18n/translations/zh.json | 25 +- apps/mobile/src/lib/filePreview.test.ts | 2 + apps/mobile/src/state/entities.ts | 24 +- apps/mobile/src/state/linkedThread.ts | 53 +++ apps/mobile/src/state/peerLinks.ts | 5 +- apps/server/src/auth/RpcAuthorization.test.ts | 87 ++++ apps/server/src/auth/RpcAuthorization.ts | 6 + .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/eventStreamResponse.ts | 36 ++ apps/server/src/guest/http.ts | 34 +- .../src/observability/RpcInstrumentation.ts | 4 + apps/server/src/peer/PeerLinks.test.ts | 2 + apps/server/src/peer/PeerLinks.testkit.ts | 6 +- apps/server/src/peer/PeerLinks.ts | 17 + apps/server/src/peer/PeerMcpClient.test.ts | 2 + apps/server/src/peer/PeerThreadRelay.test.ts | 330 +++++++++++++++ apps/server/src/peer/PeerThreadRelay.ts | 275 +++++++++++++ apps/server/src/peer/linkThreadHttp.ts | 162 ++++++++ apps/server/src/server.ts | 7 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 15 + apps/web/src/closedViewStore.test.ts | 6 + apps/web/src/closedViewStore.ts | 6 + apps/web/src/components/ChatMarkdown.tsx | 7 +- apps/web/src/components/RightPanelTabs.tsx | 8 + .../src/components/chat/LinkedThreadPane.tsx | 173 ++++++++ .../chat/MarkdownThreadLink.browser.test.tsx | 96 ++++- .../components/chat/MarkdownThreadLink.tsx | 67 ++- .../components/chat/ProviderSubagentBar.tsx | 100 ++--- .../components/chat/ReadOnlyComposerBar.tsx | 37 ++ .../chat/ReadOnlyThreadTimeline.tsx | 143 +++++++ .../chat/RightPanelSurfaceContent.tsx | 10 + ...hreadRelationshipsControl.browser.test.tsx | 7 +- .../chat/ThreadRelationshipsControl.tsx | 34 +- .../src/components/chat/V2ItemInspector.tsx | 4 +- .../src/components/chat/V2LifecycleRow.tsx | 19 +- .../src/components/chat/timelineRowContext.ts | 3 +- apps/web/src/components/guest/GuestPage.tsx | 157 ++----- .../src/components/guest/guestStream.logic.ts | 91 +---- apps/web/src/i18n/translations/de.json | 40 +- apps/web/src/i18n/translations/en.json | 40 +- apps/web/src/i18n/translations/es.json | 40 +- apps/web/src/i18n/translations/fr.json | 40 +- apps/web/src/i18n/translations/ja.json | 40 +- apps/web/src/i18n/translations/ko.json | 40 +- apps/web/src/i18n/translations/pt-BR.json | 40 +- apps/web/src/i18n/translations/ru.json | 40 +- apps/web/src/i18n/translations/sv.json | 40 +- apps/web/src/i18n/translations/zh.json | 40 +- apps/web/src/linkedThreadSurface.ts | 55 +++ apps/web/src/reopenClosedView.ts | 3 + apps/web/src/rightPanelStore.test.ts | 80 +++- apps/web/src/rightPanelStore.ts | 66 ++- apps/web/src/state/linkedThreadView.ts | 139 +++++++ apps/web/src/state/peerLinks.ts | 5 +- docs/internals/environment-auth.md | 4 +- docs/internals/remote.md | 12 + docs/user/remote-access.md | 19 + packages/client-runtime/package.json | 8 + .../client-runtime/src/linkRequest.test.ts | 7 +- packages/client-runtime/src/linkRequest.ts | 13 +- .../client-runtime/src/linkedThread.test.ts | 160 ++++++++ packages/client-runtime/src/linkedThread.ts | 275 +++++++++++++ packages/client-runtime/src/rpc/client.ts | 1 + .../client-runtime/src/state/peerLinks.ts | 97 ++++- .../client-runtime/src/state/threadStream.ts | 94 +++++ packages/contracts/src/environment.ts | 3 + packages/contracts/src/peerLink.ts | 67 +++ packages/contracts/src/rpc.ts | 41 ++ packages/shared/src/threadLinksCopy.ts | 4 +- 90 files changed, 3945 insertions(+), 502 deletions(-) create mode 100644 apps/mobile/src/features/threads/LinkedThreadSheet.tsx create mode 100644 apps/mobile/src/features/threads/ReadOnlyComposerBar.tsx create mode 100644 apps/mobile/src/features/threads/useOpenThreadLink.ts create mode 100644 apps/mobile/src/state/linkedThread.ts create mode 100644 apps/server/src/eventStreamResponse.ts create mode 100644 apps/server/src/peer/PeerThreadRelay.test.ts create mode 100644 apps/server/src/peer/PeerThreadRelay.ts create mode 100644 apps/server/src/peer/linkThreadHttp.ts create mode 100644 apps/web/src/components/chat/LinkedThreadPane.tsx create mode 100644 apps/web/src/components/chat/ReadOnlyComposerBar.tsx create mode 100644 apps/web/src/components/chat/ReadOnlyThreadTimeline.tsx create mode 100644 apps/web/src/linkedThreadSurface.ts create mode 100644 apps/web/src/state/linkedThreadView.ts create mode 100644 packages/client-runtime/src/linkedThread.test.ts create mode 100644 packages/client-runtime/src/linkedThread.ts create mode 100644 packages/client-runtime/src/state/threadStream.ts diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 7a9a806f54f19..b9281945f11f6 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -69,6 +69,7 @@ import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; import { ThreadPullRequestsSheet } from "./features/threads/ThreadPullRequestsSheet"; import { ThreadAgentsSheet } from "./features/threads/ThreadAgentsSheet"; +import { LinkedThreadSheet } from "./features/threads/LinkedThreadSheet"; import { ThreadGuestShareSheet } from "./features/threads/ThreadGuestShareSheet"; import { ThreadBackgroundWorkSheet } from "./features/threads/ThreadBackgroundWorkSheet"; import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl"; @@ -784,6 +785,10 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: ThreadAgentsSheet, options: sheetRoute({ detent: 0.5, androidMaxDetent: 0.9 }), }), + LinkedThread: createNativeStackScreen({ + screen: LinkedThreadSheet, + options: sheetRoute({ detent: 0.9, android: "fullScreen" }), + }), ThreadGuestShare: createNativeStackScreen({ screen: ThreadGuestShareSheet, options: sheetRoute({ detent: 0.5 }), diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx index aa391b3c03bf3..0a8f515787fce 100644 --- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx +++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx @@ -117,7 +117,7 @@ vi.mock("./ui/Dialog", () => ({ alert: vi.fn() })); vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => children })); vi.mock("./ComposerContextSheet", () => ({ ComposerContextSheet: () => null })); vi.mock("./AssistantCitationSheet", () => ({ AssistantCitationSheet: () => null })); -vi.mock("../features/threads/useOpenLinkedThread", () => ({ useOpenLinkedThread: () => vi.fn() })); +vi.mock("../features/threads/useOpenThreadLink", () => ({ useOpenThreadLink: () => vi.fn() })); vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => [] })); vi.mock("../state/model-mentions", () => ({ useModelMentions: () => [] })); vi.mock("../state/preferences", async () => { diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index 8d3805234696b..39e12816cdf61 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -37,7 +37,7 @@ import { appAtomRegistry } from "../state/atom-registry"; import { enrichedModelDetails, enrichedModelReference } from "../lib/enrichedLinkPresentation"; import { useModelMentions } from "../state/model-mentions"; import { mobilePreferencesAtom } from "../state/preferences"; -import { useOpenLinkedThread } from "../features/threads/useOpenLinkedThread"; +import { useOpenThreadLink } from "../features/threads/useOpenThreadLink"; import { useLinkedEnvironments } from "../state/peerLinks"; import { ComposerContextSheet } from "./ComposerContextSheet"; import { AppText as Text } from "./ui/AppText"; @@ -186,7 +186,7 @@ export function ComposerEditor({ }), }) : ""; - const openLinkedThread = useOpenLinkedThread(); + const openThreadLink = useOpenThreadLink(environmentId ?? null); const selectedReference = selected ? collectComposerContextReferences(selected.source)[0] : undefined; @@ -338,10 +338,7 @@ export function ComposerEditor({ : {})} onOpenThread={(thread) => { setSelected(null); - openLinkedThread({ - environmentId: String(thread.environmentId), - threadId: String(thread.threadId), - }); + openThreadLink(thread); }} environmentId={environmentId ?? draft.project?.environmentId} projectId={draft.project?.projectId} diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx new file mode 100644 index 0000000000000..9cbc930548464 --- /dev/null +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -0,0 +1,383 @@ +import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { + isLinkedThreadWorking, + linkedThreadFailure, + type LinkedThreadFailure, + type LinkedThreadTarget, +} from "@t3tools/client-runtime/linked-thread"; +import { + toolCallLines, + turnItemDetailRevision, + turnItemOutputText, +} from "@t3tools/client-runtime/work-log/item-detail"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { T, useGT, useLocale, useMessages } from "gt-react-native"; +import { useRef, useState, useSyncExternalStore } from "react"; +import type * as React from "react"; +import { AppState, Pressable, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { ScreenContent } from "../../components/ui/ScreenContent"; +import { SheetHeader } from "../../components/ui/SheetHeader"; +import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; +import { useEnvironments } from "../../state/environments"; +import { + buildThreadFeed, + createThreadFeedCache, + formatItemFullDetail, + type ThreadFeedActivity, + type ThreadFeedEntry, +} from "../../lib/threadActivity"; +import { useLinkedThreadView } from "../../state/linkedThread"; +import { peerLinkEnvironment } from "../../state/peerLinks"; +import { useEnvironmentQuery } from "../../state/query"; +import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; +import { ReadOnlyComposerBar } from "./ReadOnlyComposerBar"; + +type LinkedThreadRouteParams = { + readonly viaEnvironmentId: string; + readonly environmentId: string; + readonly threadId: string; + readonly label: string; + readonly title?: string; +}; + +/** The route params that open a linked environment's thread read-only. */ +export const linkedThreadRouteParams = ( + thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, + linked: { readonly viaEnvironmentId: EnvironmentId; readonly label: string }, + title: string | null, +): LinkedThreadRouteParams => ({ + viaEnvironmentId: linked.viaEnvironmentId, + environmentId: thread.environmentId, + threadId: thread.threadId, + label: linked.label, + ...(title === null ? {} : { title }), +}); + +function ActivityRow(props: { + readonly activity: ThreadFeedActivity; + readonly target: LinkedThreadTarget; +}) { + const { activity, target } = props; + const gt = useGT(); + const [open, setOpen] = useState(false); + const row = activity.projectedItem; + // The stream leaves long output out; an open row reads its item in full through the link. + const fetched = useEnvironmentQuery( + open && activity.fetchesDetail + ? peerLinkEnvironment.threadItem({ + environmentId: target.viaEnvironmentId, + input: { + environmentId: target.environmentId, + threadId: row.sourceThreadId, + itemId: row.sourceItemId, + revision: turnItemDetailRevision(row.item), + }, + }) + : null, + ); + const fetchedItem = fetched.data?.item ?? null; + const shownItem = fetchedItem ?? row.item; + // A command or tool call reads as what was called, as on the thread screen; only an item with + // no call to show falls back to its full detail. + const call = !open + ? null + : shownItem.type === "command_execution" + ? toolCallLines({ command: shownItem.input }) + : shownItem.type === "dynamic_tool" + ? toolCallLines({ args: shownItem.input }) + : null; + const callText = call + ? (call.command ?? + call.args?.map(([key, value]) => `${key}: ${value}`).join("\n") ?? + call.argsText) + : null; + const body = !open + ? null + : call + ? callText + : fetchedItem + ? formatItemFullDetail(row, fetchedItem) + : (activity.getFullDetail() ?? activity.detail); + const output = !open + ? null + : !activity.fetchesDetail + ? turnItemOutputText(row.item) + : fetchedItem + ? (turnItemOutputText(fetchedItem) ?? gt("No output.")) + : fetched.error + ? gt("Couldn't load output: {error}", { error: fetched.error }) + : fetched.data + ? gt("Output is no longer available.") + : gt("Loading output…"); + return ( + setOpen(!open)} + className="active:opacity-70" + > + + {activity.summary} + + {body ? ( + + + {body} + + + ) : null} + {output ? ( + + + {output} + + + ) : null} + {open && fetched.error ? ( + + + + ) : null; + // A file or visual lives on the linked environment, which this client has no way to ask. + const renderHtmlRender = useStableCallback(() => ( +

+ {gt("Open this thread on {label} to see this visual.", { label })} +

+ )); + const working = projection !== null && isLinkedThreadWorking(projection); + const historyControls: MessagesTimelineHistoryControls | undefined = + view === null || view.thread.historyCursor === null + ? undefined + : { + hasMoreHistory: true, + loading: view.history.loading, + error: view.history.failed ? gt("Could not load earlier turns. Try again.") : null, + onLoadEarlier: view.loadEarlier, + }; + return ( +
+

+ {linkedThreadTitle( + { title: projection?.thread.title || surface.title }, + gt("Thread on {label}", { label }), + )} +

+ {projection === null ? ( + <> +
+ {failure === null ? ( +
+ + + Reading from {label}… + +
+ ) : ( + + {failure.title} + {failure.detail} + {retryAction} + + )} +
+ + + ) : ( + + {() => ( + <> + {failure === null ? null : ( +
+ + {failure.title} + + {failure.detail} Showing what was read before. + + {retryAction} + +
+ )} + + + )} +
+ )} +
+ ); +} diff --git a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx index 80e8cdf0dbd76..4455c29c7ea1e 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx @@ -1,19 +1,32 @@ import { RegistryContext } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../test/render"; +import { linkedThreadSurface } from "../../linkedThreadSurface"; +import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore"; import { MarkdownThreadLink } from "./MarkdownThreadLink"; +const HERE = scopeThreadRef(EnvironmentId.make("environment"), ThreadId.make("here")); +const panel = () => selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, HERE); + const state = vi.hoisted(() => ({ reply: null as unknown, remote: null as unknown, + cached: null as unknown, + linked: new Map(), + connected: [] as Array, })); vi.mock(import("../../state/entities"), () => ({ useThreadShell: ((ref: { environmentId: string } | null) => - ref?.environmentId === "remote" ? state.remote : null) as never, + ref?.environmentId === "remote" + ? state.remote + : ref?.environmentId === "saved-vm" + ? state.cached + : null) as never, useThreadRefs: (enabled = true) => enabled ? [{ environmentId: EnvironmentId.make("remote"), threadId: ThreadId.make("older-thread") }] @@ -25,7 +38,13 @@ vi.mock(import("../../state/environments"), () => ({ useEnvironmentIdentities: () => [ { environmentId: EnvironmentId.make("environment"), label: "Here" }, { environmentId: EnvironmentId.make("remote"), label: "Remote" }, + { environmentId: EnvironmentId.make("saved-vm"), label: "Saved VM" }, ], + useConnectedEnvironmentIds: () => state.connected as never, +})); +vi.mock(import("../../state/peerLinks"), () => ({ + useLinkedEnvironments: ((environmentId: string | null) => + environmentId === null ? new Map() : state.linked) as never, })); vi.mock(import("../ProjectFavicon"), () => ({ ProjectFavicon: () => ( @@ -46,6 +65,10 @@ function setup() { AsyncResult.AsyncResult, string> >(AsyncResult.initial()); state.reply = reply; + state.linked = new Map(); + state.cached = null; + state.connected = ["environment", "remote"]; + useRightPanelStore.setState({ byThreadKey: {} }); state.remote = { environmentId: EnvironmentId.make("remote"), id: ThreadId.make("older-thread"), @@ -161,3 +184,74 @@ it("names a thread on a machine this client has no connection to, without waitin .toBeVisible(); await expect.element(screen.getByRole("link")).not.toBeInTheDocument(); }); + +it.for([ + { name: "a machine only this environment links to", linkedId: "linked-vm" }, + { name: "a saved machine this client is not connected to", linkedId: "saved-vm" }, +])("opens a thread on $name as a read through the link", async ({ linkedId }) => { + const { registry } = setup(); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + state.linked = new Map([[linkedId, "fs-17"]]); + const environmentId = EnvironmentId.make("environment"); + const link = { environmentId: EnvironmentId.make(linkedId), threadId: ThreadId.make("there") }; + await using screen = await render( + + + , + ); + const chip = screen.getByRole("button", { name: "Thread, Thread on fs-17" }); + await chip.click(); + const surface = linkedThreadSurface({ + viaEnvironmentId: environmentId, + ...link, + label: "fs-17", + title: null, + }); + expect(panel()).toMatchObject({ isOpen: true, activeSurfaceId: surface.id, surfaces: [surface] }); + await chip.click(); + expect(panel().surfaces).toHaveLength(1); + expect(screen.router?.state.location.pathname).toBe("/"); +}); + +it("reads through the link when a disconnected machine's thread is only cached here", async () => { + const { registry } = setup(); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + state.linked = new Map([["saved-vm", "fs-17"]]); + state.cached = { id: ThreadId.make("there"), title: "Cached title", projectId: null }; + const environmentId = EnvironmentId.make("environment"); + const link = { environmentId: EnvironmentId.make("saved-vm"), threadId: ThreadId.make("there") }; + await using screen = await render( + + + , + ); + await screen.getByRole("button", { name: "Thread, Cached title" }).click(); + expect(panel().surfaces).toEqual([ + linkedThreadSurface({ + viaEnvironmentId: environmentId, + ...link, + label: "fs-17", + title: "Cached title", + }), + ]); +}); + +it("opens a linked machine's thread directly once this client is connected to it", async () => { + const { registry, reply } = setup(); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + state.linked = new Map([["saved-vm", "fs-17"]]); + state.connected = ["environment", "saved-vm"]; + registry.set(reply, AsyncResult.success({ there: { title: "Fix the build", projectId: null } })); + await using screen = await render( + + + , + ); + await expect.element(screen.getByText("Fix the build")).toBeVisible(); + await expect.element(screen.getByRole("button")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 1a0df30fe0518..1e4c823b458b4 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -1,5 +1,6 @@ -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; import { useGT, useMessages } from "gt-react"; +import { MessagesSquareIcon } from "lucide-react"; import { formatHostedThreadLink, guessThreadLinkRef, @@ -7,30 +8,53 @@ import { type ThreadLink, } from "@t3tools/shared/threadLinks"; import { unknownThreadLinkLabel } from "@t3tools/shared/threadLinksCopy"; +import { resolveLinkedThreadOpen } from "@t3tools/client-runtime/linked-thread"; import { configuredHostedAppUrl } from "../../hostedPairing"; import { useThreadRefs, useThreadShell } from "../../state/entities"; -import { useEnvironmentIdentities } from "../../state/environments"; +import { useConnectedEnvironmentIds, useEnvironmentIdentities } from "../../state/environments"; +import { useRightPanelStore } from "../../rightPanelStore"; +import { useLinkedEnvironments } from "../../state/peerLinks"; import { orchestrationEnvironment } from "../../state/orchestration"; import { useEnvironmentQuery } from "../../state/query"; +import { ContextChip, ContextChipLabel } from "../ContextChip"; import { UnresolvedChip } from "../contextChipParts"; import { ThreadContextChip } from "../ThreadContextChip"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; /** `label` is the link's written text; an autolink has none. */ export function MarkdownThreadLink(props: { readonly environmentId: EnvironmentId; + /** The thread the link is written in; a linked environment's thread opens in its right panel. */ + readonly threadRef?: ScopedThreadRef | undefined; readonly link: ThreadLink; readonly label: string | null; }) { const gt = useGT(); const messages = useMessages(); + const panelRef = props.threadRef; const candidates = threadLinkCandidates(props.link, props.environmentId); const writtenRef = candidates[0]!; const written = useThreadShell(writtenRef); - // A linked machine's threads are reachable only through its server, not from this client. - const reachable = useEnvironmentIdentities().some( + const saved = useEnvironmentIdentities().some( (environment) => environment.environmentId === writtenRef.environmentId, ); + const connected = useConnectedEnvironmentIds().includes(writtenRef.environmentId); + // A thread on a machine this client is not connected to still reads through the one that links to it. + const linkedLabel = useLinkedEnvironments( + connected || writtenRef.environmentId === props.environmentId ? null : props.environmentId, + ).get(writtenRef.environmentId); + // A shell cached from an earlier connection does not make the thread open there now. Outside a + // thread there is no panel to read it in, so the link behaves as it does without one. + const linked = + panelRef !== undefined && + resolveLinkedThreadOpen({ + environmentId: writtenRef.environmentId, + viaEnvironmentId: props.environmentId, + own: saved ? { connected } : undefined, + linked: linkedLabel !== undefined, + }) === "linked"; + const reachable = saved && !linked; const lookup = useEnvironmentQuery( written === null && reachable ? orchestrationEnvironment.threadLinkMetadata({ @@ -58,6 +82,41 @@ export function MarkdownThreadLink(props: { : null; const remote = useThreadShell(remoteRef); const resolved = target ?? (remoteRef && remote ? { ref: remoteRef, metadata: remote } : null); + if (linked && linkedLabel !== undefined) { + const knownTitle = props.label ?? written?.title ?? null; + const title = knownTitle ?? gt("Thread on {label}", { label: linkedLabel }); + return ( + + + useRightPanelStore.getState().openLinkedThread(panelRef, { + viaEnvironmentId: props.environmentId, + ...writtenRef, + label: linkedLabel, + title: knownTitle, + }) + } + /> + } + aria-label={gt("Thread, {title}", { title })} + > + + {title} + + } + /> + + {gt("Read the thread on {label}", { label: linkedLabel })} + + + ); + } if (missing && resolved === null) { const unknown = unknownThreadLinkLabel(props.link, props.environmentId, messages); return ; diff --git a/apps/web/src/components/chat/ProviderSubagentBar.tsx b/apps/web/src/components/chat/ProviderSubagentBar.tsx index 39c3c7cd2dc0f..315461296bade 100644 --- a/apps/web/src/components/chat/ProviderSubagentBar.tsx +++ b/apps/web/src/components/chat/ProviderSubagentBar.tsx @@ -11,6 +11,11 @@ import { tickTextContent } from "~/lib/tickTextContent"; import type { ProviderInstanceEntry } from "../../providerInstances"; import { Button } from "../ui/button"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; +import { + ReadOnlyComposerBar, + ReadOnlyComposerLead, + ReadOnlyComposerStatus, +} from "./ReadOnlyComposerBar"; export function ProviderSubagentBar(props: { readonly provider: ProviderInstanceEntry | null; @@ -33,55 +38,54 @@ export function ProviderSubagentBar(props: { messages, ); - // Sized by the composer, not the viewport: a docked side panel narrows the - // chat column on a wide window, and one row there squeezes out the model - // and status, so the status drops to its own line instead. return ( -
-
- - {props.provider ? ( - - ) : null} - {props.modelLabel} - {props.effortLabel === null ? null : ( - {props.effortLabel} - )} - - formatProviderSubagentStatus(status, nowMs, messages), - live, - )} - aria-hidden - className="min-w-0 max-w-full truncate text-muted-foreground tabular-nums @max-[560px]/composer-surface:text-xs" - /> -
- - {gt("{model} subagent: {status}", { model: modelDescription, status: announcement })} - - - Runs on its own - - {props.actions} - {props.onOpenParent ? ( - - ) : null} -
+ + Runs on its own + + {props.actions} + {props.onOpenParent ? ( + + ) : null} + + } + > + + {props.provider ? ( + + ) : null} + {props.modelLabel} + {props.effortLabel === null ? null : ( + {props.effortLabel} + )} + + formatProviderSubagentStatus(status, nowMs, messages), + live, + )} + aria-hidden + /> + ); } diff --git a/apps/web/src/components/chat/ReadOnlyComposerBar.tsx b/apps/web/src/components/chat/ReadOnlyComposerBar.tsx new file mode 100644 index 0000000000000..d2df437ae98c4 --- /dev/null +++ b/apps/web/src/components/chat/ReadOnlyComposerBar.tsx @@ -0,0 +1,37 @@ +import type { ComponentProps, ReactNode } from "react"; + +/** + * What stands where the composer would for a thread that takes no messages. `children` say what + * the thread is and how it is doing; `actions` sit at the trailing edge. + */ +export function ReadOnlyComposerBar(props: { + readonly children: ReactNode; + readonly actions?: ReactNode; +}) { + // Sized by the composer, not the viewport: a docked side panel narrows the + // chat column on a wide window, and one row there squeezes out the lead + // and status, so the status drops to its own line instead. + return ( +
+
+ {props.children} +
+ {props.actions} +
+ ); +} + +/** The bar's first line: an icon and what the thread is. */ +export function ReadOnlyComposerLead(props: { readonly children: ReactNode }) { + return {props.children}; +} + +/** The bar's second line, which drops under the lead in a narrow composer. */ +export function ReadOnlyComposerStatus(props: Omit, "className">) { + return ( + + ); +} diff --git a/apps/web/src/components/chat/ReadOnlyThreadTimeline.tsx b/apps/web/src/components/chat/ReadOnlyThreadTimeline.tsx new file mode 100644 index 0000000000000..1cb825e13461d --- /dev/null +++ b/apps/web/src/components/chat/ReadOnlyThreadTimeline.tsx @@ -0,0 +1,143 @@ +import type { LegendListRef } from "@legendapp/list/react"; +import { + deriveRunlessWorkStartedAt, + deriveThreadActivityRun, + deriveThreadStructureRuntime, +} from "@t3tools/client-runtime/state/thread-execution"; +import { createQuestionHistoryProjector } from "@t3tools/client-runtime/state/thread-requests"; +import { + EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; +import { useRef, useState, type ReactNode } from "react"; + +import { useIncrementalTimelineEntries } from "~/hooks/useIncrementalTimelineEntries"; +import { useTheme } from "~/hooks/useTheme"; +import { deriveActiveWorkStartedAt, derivePhase } from "~/session-logic"; +import type { ChatFileAttachment } from "~/types"; + +import type { ExpandedImagePreview } from "./ExpandedImagePreview"; +import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./MessagesTimeline"; +import { ScrollToEndButton } from "./TimelineOverlays"; +import type { TimelineRow, TurnItemSource } from "./timelineRowContext"; +import { useTimelineFollow } from "./useTimelineFollow"; + +// The timeline needs an environment id to key its rows. No environment answers to this one, so a +// row that would ask the thread's environment for something gets nothing. +const NO_ENVIRONMENT_ID = EnvironmentId.make("guest"); +const NO_TURN_DIFFS: ReadonlyArray = []; +const NO_OPTIMISTIC_MESSAGES: ReadonlyArray = []; +const ignore = () => {}; + +/** + * A thread's own timeline, built from its projection alone and read-only: every action that would + * reach the thread's environment (fork, revert, reply, diffs, files, other threads, shell, + * approvals) is left out, so its control does not render. The guest page and a linked + * environment's thread both show a thread this way. + */ +export function ReadOnlyThreadTimeline(props: { + /** Keys the list. It holds no ":" so the timeline finds no environment thread behind it. */ + readonly threadKey: string; + readonly projection: OrchestrationV2ThreadProjection; + readonly historyControls: MessagesTimelineHistoryControls | undefined; + /** Where expanded rows read an item's detail. */ + readonly turnItemSource: TurnItemSource; + /** Preview URLs for the messages' attachments, keyed by attachment id. */ + readonly attachmentUrls: ( + items: ReadonlyArray, + ) => ReadonlyMap; + readonly onImageExpand: (preview: ExpandedImagePreview) => void; + readonly onFileOpen: (file: ChatFileAttachment) => void; + readonly renderHtmlRender: (row: Extract) => ReactNode; + readonly renderFooter?: (items: ReadonlyArray) => ReactNode; + /** What stands below the timeline, where the composer would. */ + readonly children: (controls: { readonly scrollToEnd: () => void }) => ReactNode; +}) { + const { threadKey, projection } = props; + const listRef = useRef(null); + const { resolvedTheme } = useTheme(); + // The rest is what ChatView derives from the same projection. + const [projectQuestionHistory] = useState(() => createQuestionHistoryProjector()); + const items = projectQuestionHistory(projection); + const entries = useIncrementalTimelineEntries(threadKey, { + visibleTurnItems: items, + optimisticMessages: NO_OPTIMISTIC_MESSAGES, + attachmentUrlById: props.attachmentUrls(items), + attempts: projection.attempts, + nodes: projection.nodes, + plans: projection.plans, + }); + const activityRun = deriveThreadActivityRun(projection); + const runtime = deriveThreadStructureRuntime(projection); + const runlessWorkStartedAt = deriveRunlessWorkStartedAt(projection); + const isWorking = derivePhase(runtime) === "running" || runlessWorkStartedAt !== null; + const workStartedAt = + deriveActiveWorkStartedAt(activityRun, runtime, null) ?? runlessWorkStartedAt; + const runningRunId = runtime?.activeRunId ?? null; + const follow = useTimelineFollow({ + legendListRef: listRef, + composerTimelineInset: 0, + routeThreadKey: threadKey, + activeThreadKey: threadKey, + // Not a server thread: new turns follow the end instead of anchoring near the top. + isServerThread: false, + serverProjection: null, + threadStatus: "live", + activeActivityRun: activityRun, + activeRunningTurnId: runningRunId, + timelineEntries: entries, + timelineAnchorMessageId: null, + setTimelineAnchor: ignore, + }); + return ( + <> +
+ + {follow.showScrollToBottom ? ( + follow.scrollToEnd(true)} + /> + ) : null} +
+ {props.children({ scrollToEnd: () => follow.scrollToEnd(true) })} + + ); +} diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 80f27c8dce568..31d8b77826d97 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -12,6 +12,7 @@ import type { } from "@t3tools/contracts"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { lazy, Suspense } from "react"; +import { LinkedThreadPane } from "./LinkedThreadPane"; import SideChatPane from "./SideChatPane"; import type { ComposerImageAttachment, DraftId } from "../../composerDraftStore"; import type { ShortcutMatchContext } from "../../keybindings"; @@ -223,6 +224,15 @@ export function RightPanelSurfaceContent(props: { onClose={() => onCloseSurface(surface)} /> ); + case "linked-thread": + return ( + + ); case "device": return ( diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 1a0fb5bd406f8..914adf19777ad 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -45,6 +45,10 @@ vi.mock(import("../../state/environments"), () => ({ useEnvironment: (() => null) as never, useEnvironmentProviders: (() => new Map()) as never, })); +vi.mock(import("../../state/peerLinks"), () => ({ + peerLinkEnvironment: { readThread: {} } as never, + useLinkedEnvironments: (() => new Map()) as never, +})); vi.mock(import("../../lib/archivedThreadsState"), () => ({ useArchivedThreadSnapshots: (() => ({ snapshots: [{ environmentId: "environment", snapshot: { threads: state.archivedThreads } }], @@ -330,8 +334,9 @@ it("shows a remote subagent's full title in its tooltip even when its environmen await vi.waitFor(() => expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle), ); + // This client is not connected there, so the row reads the thread through this environment. expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain( - "Runs on Remote VM with a long machine name in the office. Connect to it to open the thread there.", + "Read the thread on Remote VM with a long machine name in the office", ); await row.click({ force: true }); diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index e8a5fc1fe60a0..1c29eb147fce4 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -37,6 +37,7 @@ import { type OrchestrationV2RemoteTaskChild, type OrchestrationV2Subagent, type OrchestrationV2ThreadShell, + type ScopedThreadRef, type ServerProvider, type ThreadId, } from "@t3tools/contracts"; @@ -62,6 +63,7 @@ import type { MessageResolver } from "~/i18n/messages"; import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; import { buildThreadRouteParams } from "../../threadRoutes"; +import { useLinkedThreadOpener } from "../../state/linkedThreadView"; import { useProjects, useQuietThreadProjection, @@ -279,18 +281,18 @@ function currentSubagent( } /** - * A task delegated to a linked environment. It has no thread here, so it opens - * the thread there, when this client is connected to that environment. + * A task delegated to a linked environment. It has no thread here, so it opens the thread there: + * in place when this client is connected to that environment, else read-only through this one. */ function RemoteSubagentRow(props: { readonly agent: RemoteSubagent; + /** The thread that delegated the task; its environment holds the link and its panel shows the read. */ + readonly parentRef: ScopedThreadRef; readonly provider: ServerProvider | undefined; readonly anyInstanceBadge: boolean; }) { const gt = useGT(); const m = useMessages(); - const navigate = useNavigate(); - const environment = useEnvironment(props.agent.remoteChild.environmentId); const { remoteChild } = props.agent; const status = props.agent.status; const failed = status === "failed"; @@ -298,27 +300,14 @@ function RemoteSubagentRow(props: { title: props.agent.title ?? gt("Subagent"), isSubagent: true, }); + const opener = useLinkedThreadOpener(props.parentRef, remoteChild, title); return (
  • { - if (environment === null) return; - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams( - scopeThreadRef(remoteChild.environmentId, remoteChild.threadId), - ), - }); - }} - /> + } > @@ -1086,6 +1073,7 @@ export function ThreadRelationshipsPanel(props: { thread?.projection.subagents.find((agent) => agent.id === props.subagentId) ?? null, ); const remote = props.remote ?? agent?.remoteChild; - const remoteEnvironment = useEnvironment(remote?.environmentId ?? null); const gt = useGT(); const m = useMessages(); - const navigate = useNavigate(); const threadId = props.threadId; - // A task in a linked environment opens there, if this client is connected to it. + // A task in a linked environment opens there, or read-only through this one. + const remoteOpener = useLinkedThreadOpener(props.parentRef, remote, props.title); const open = - threadId !== null - ? () => props.onOpenThread(threadId) - : remote !== undefined && remoteEnvironment !== null - ? () => - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(scopeThreadRef(remote.environmentId, remote.threadId)), - }) - : null; + threadId !== null ? () => props.onOpenThread(threadId) : (remoteOpener?.open ?? null); const liveStatus = agent?.status ?? props.status; const status = props.event ? props.event.status : liveStatus; const statusLabel = props.event?.label ?? m(subagentStatusVisual(liveStatus).label); diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 6a298fd6de049..2373193588f06 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -37,7 +37,8 @@ import { type HandoffTimelineRun } from "./V2LifecycleRow"; */ export interface TurnItemSource { readonly detail: TurnItemDetailSource; - readonly commandOutput: (target: { + /** Unset where output does not stream: a command row then shows the output its detail holds. */ + readonly commandOutput?: (target: { readonly threadId: ThreadId; readonly itemId: TurnItemId; }) => Atom.Atom>; diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsx index bf870dcb4b59c..fe045af73ac2c 100644 --- a/apps/web/src/components/guest/GuestPage.tsx +++ b/apps/web/src/components/guest/GuestPage.tsx @@ -1,5 +1,4 @@ import { - EnvironmentId, GUEST_MESSAGE_MAX_LENGTH, GUEST_HISTORY_ROUTE, GUEST_NAME_MAX_LENGTH, @@ -14,16 +13,9 @@ import { type ThreadGuestMessage, type ThreadGuestMessageStatus, } from "@t3tools/contracts"; -import type { LegendListRef } from "@legendapp/list/react"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; -import { - deriveRunlessWorkStartedAt, - deriveThreadActivityRun, - deriveThreadStructureRuntime, -} from "@t3tools/client-runtime/state/thread-execution"; -import { createQuestionHistoryProjector } from "@t3tools/client-runtime/state/thread-requests"; import { ArrowUpIcon, PaperclipIcon, XIcon } from "lucide-react"; import { useEffect, @@ -38,24 +30,21 @@ import { msg, T, useGT, useMessages } from "gt-react"; import { m } from "~/i18n/messages"; -import { useIncrementalTimelineEntries } from "~/hooks/useIncrementalTimelineEntries"; import { useNowMinute } from "~/hooks/useNowMinute"; import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; import { cn } from "~/lib/utils"; -import { deriveActiveWorkStartedAt, derivePhase } from "~/session-logic"; import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl"; import type { ExpandedImagePreview } from "../chat/ExpandedImagePreview"; import { GuestMessageAttachments } from "../chat/GuestMessageAttachments"; import { HostImageUrlContext } from "../chat/hostImageUrl"; import { PierreEntryIcon } from "../chat/PierreEntryIcon"; import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle"; -import { MessagesTimeline, type MessagesTimelineHistoryControls } from "../chat/MessagesTimeline"; +import type { MessagesTimelineHistoryControls } from "../chat/MessagesTimeline"; +import { ReadOnlyThreadTimeline } from "../chat/ReadOnlyThreadTimeline"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { getDisplayModelName, getTriggerDisplayModelName } from "../chat/providerIconUtils"; -import { ScrollToEndButton } from "../chat/TimelineOverlays"; import type { TimelineRow } from "../chat/timelineRowContext"; -import { useTimelineFollow } from "../chat/useTimelineFollow"; import { GuestHtmlRender } from "./GuestHtmlRender"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -410,17 +399,7 @@ function NameForm({ ); } -// The timeline needs an environment id to key its rows. Nothing behind it loads on this page; -// see isGuestPage. -const GUEST_ENVIRONMENT_ID = EnvironmentId.make("guest"); -const NO_TURN_DIFFS: ReadonlyArray = []; -const NO_OPTIMISTIC_MESSAGES: ReadonlyArray = []; -const ignore = () => {}; - -/** - * The owner's timeline, read-only: every action that would reach the owner's machine (fork, - * revert, diffs, files, other threads, shell) is left out, so its control does not render. - */ +/** The owner's timeline, read-only, with the guest's own messages and composer below it. */ function GuestThread({ view: { shareId, title, expiresAt, messages, model }, projection, @@ -432,124 +411,56 @@ function GuestThread({ readonly awaitingRowIds: GuestStreamState["awaitingRowIds"]; readonly historyControls: MessagesTimelineHistoryControls | undefined; }) { - // No ":" so the timeline finds no environment thread behind the key. - const threadKey = `guest-${shareId}`; - const listRef = useRef(null); - const { resolvedTheme } = useTheme(); - // The rest is what ChatView derives from the same projection. - const [projectQuestionHistory] = useState(() => createQuestionHistoryProjector()); - const items = projectQuestionHistory(projection); // Files load through the guest route. const [attachmentUrls] = useState(() => createGuestAttachmentUrls(shareId)); // Expanded rows read detail and command output through the guest routes. const [turnItemSource] = useState(() => guestTurnItemSource(shareId)); - const attachmentUrlById = attachmentUrls(items); - const entries = useIncrementalTimelineEntries(threadKey, { - visibleTurnItems: items, - optimisticMessages: NO_OPTIMISTIC_MESSAGES, - attachmentUrlById, - attempts: projection.attempts, - nodes: projection.nodes, - plans: projection.plans, - }); const openFile = useStableCallback((file: { readonly id: string }) => openInNewTab(guestAttachmentUrl(shareId, file.id)), ); const hostImageUrl = useStableCallback((path: string) => guestMediaUrl(shareId, path)); - const activityRun = deriveThreadActivityRun(projection); - const runtime = deriveThreadStructureRuntime(projection); - const runlessWorkStartedAt = deriveRunlessWorkStartedAt(projection); - const isWorking = derivePhase(runtime) === "running" || runlessWorkStartedAt !== null; - const workStartedAt = - deriveActiveWorkStartedAt(activityRun, runtime, null) ?? runlessWorkStartedAt; - const runningRunId = runtime?.activeRunId ?? null; - const follow = useTimelineFollow({ - legendListRef: listRef, - composerTimelineInset: 0, - routeThreadKey: threadKey, - activeThreadKey: threadKey, - // Not a server thread: new turns follow the end instead of anchoring near the top. - isServerThread: false, - serverProjection: null, - threadStatus: "live", - activeActivityRun: activityRun, - activeRunningTurnId: runningRunId, - timelineEntries: entries, - timelineAnchorMessageId: null, - setTimelineAnchor: ignore, - }); const renderHtmlRender = useStableCallback( (row: Extract) => ( ), ); - const unplaced = unplacedGuestMessages(messages, items, awaitingRowIds); return ( <>

    {title}

    -
    - - - {unplaced.map((message) => ( -
  • - -
  • - ))} - - ) - } - /> - - {follow.showScrollToBottom ? ( - follow.scrollToEnd(true)} - /> - ) : null} - -
    - follow.scrollToEnd(true)} /> -
    + + { + const unplaced = unplacedGuestMessages(messages, items, awaitingRowIds); + return unplaced.length === 0 ? null : ( +
      + {unplaced.map((message) => ( +
    1. + +
    2. + ))} +
    + ); + }} + > + {({ scrollToEnd }) => ( +
    + +
    + )} +
    +
    ); } diff --git a/apps/web/src/components/guest/guestStream.logic.ts b/apps/web/src/components/guest/guestStream.logic.ts index 639848e6dc591..cbb9231b2ef98 100644 --- a/apps/web/src/components/guest/guestStream.logic.ts +++ b/apps/web/src/components/guest/guestStream.logic.ts @@ -10,31 +10,23 @@ import { type GuestShareView, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ThreadHistoryPage, - type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, type ThreadGuestMessage, } from "@t3tools/contracts"; import { msg } from "gt-react"; import { m, type MessageResolver } from "~/i18n/messages"; -import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; import { - mergeOlderHistoryIntoProjection, - mergeOlderSubagentsIntoProjection, -} from "@t3tools/client-runtime/state/thread-history-merge"; -import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; + applyThreadHistoryPage, + applyThreadStreamItem, + initialThreadStreamState, + type ThreadStreamState, +} from "@t3tools/client-runtime/state/thread-stream"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -export interface GuestStreamState { +export interface GuestStreamState extends ThreadStreamState { readonly view: GuestShareView | null; - /** The thread as the owner's client holds it, built with the same reducer. */ - readonly projection: OrchestrationV2ThreadProjection | null; - readonly sequence: number; - /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */ - readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null; - /** Where "Load earlier turns" continues, or null once the whole thread is loaded. */ - readonly historyCursor: string | null; readonly ended: boolean; /** * Messages this page saw waiting that have no transcript row yet. Survives reconnects, and a @@ -44,11 +36,8 @@ export interface GuestStreamState { } export const initialGuestStreamState: GuestStreamState = { + ...initialThreadStreamState, view: null, - projection: null, - sequence: 0, - partial: null, - historyCursor: null, ended: false, awaitingRowIds: new Set(), }; @@ -95,10 +84,8 @@ export type GuestHistoryPageLoaded = { }; /** - * Applies the owner's thread stream the way the owner's client does (see - * EnvironmentThreadState in client-runtime): a snapshot replaces the thread, and later events - * pass through the same projection reducer, once each. Older pages merge in front, as they do in - * the owner's view. + * Applies the share's stream: its thread items go through the reducer every stream-only view of a + * thread shares, and the share's own state is tracked beside it. */ export function applyGuestStreamEvent( state: GuestStreamState, @@ -106,19 +93,15 @@ export function applyGuestStreamEvent( ): GuestStreamState { switch (event.type) { case "history-page": { - // A snapshot since the request replaced the thread and its cursor. - if (state.projection === null || state.historyCursor !== event.cursor) return state; + const next = applyThreadHistoryPage(state, event.cursor, event.page); + if (next === state) return state; return { ...state, - projection: mergeOlderSubagentsIntoProjection( - mergeOlderHistoryIntoProjection(state.projection, event.page.items), - event.page.subagents, - ), + ...next, awaitingRowIds: withoutPlaced( state.awaitingRowIds, event.page.items.map((row) => row.item), ), - historyCursor: event.page.hasMoreHistory ? event.page.nextCursor : null, }; } case "view": @@ -132,48 +115,18 @@ export function applyGuestStreamEvent( awaitingRowIds: withPendingFrom(state.awaitingRowIds, event.view), }; case "thread": { - const item = event.item; - if (item.kind === "snapshot") { - const projection = boundedSnapshotProjection(item); - return { - ...state, - projection, - sequence: item.snapshotSequence, - partial: - item.hasMoreHistory === true || (item.historyCursor ?? null) !== null - ? { latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null } - : null, - historyCursor: item.hasMoreHistory === true ? (item.historyCursor ?? null) : null, - awaitingRowIds: withoutPlaced( - state.awaitingRowIds, - projection.visibleTurnItems.map((row) => row.item), - ), - }; - } - if (item.kind === "synchronized" || item.sequence <= state.sequence) return state; - if (item.kind === "unknown-event") return { ...state, sequence: item.sequence }; - const projection = - applyOrchestrationV2ProjectionEvent( - state.projection, - item.event, - state.partial === null ? undefined : { partialTimeline: true, ...state.partial }, - ) ?? state.projection; - const turnItem = item.event.type === "turn-item.updated" ? item.event.payload : null; - const watermark = state.partial?.latestLocalTurnOrdinal ?? null; + const next = applyThreadStreamItem(state, event.item); + if (next === state) return state; + const placed = + event.item.kind === "snapshot" + ? (next.projection?.visibleTurnItems.map((row) => row.item) ?? []) + : event.item.kind === "event" && event.item.event.type === "turn-item.updated" + ? [event.item.event.payload] + : []; return { ...state, - projection, - sequence: item.sequence, - partial: - state.partial !== null && - turnItem !== null && - (watermark === null || turnItem.ordinal > watermark) - ? { latestLocalTurnOrdinal: turnItem.ordinal } - : state.partial, - awaitingRowIds: - turnItem === null - ? state.awaitingRowIds - : withoutPlaced(state.awaitingRowIds, [turnItem]), + ...next, + awaitingRowIds: withoutPlaced(state.awaitingRowIds, placed), }; } case "ended": diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index e8685533481d0..acdfd90c95938 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -94,6 +94,19 @@ "21be308917bd450e": "Verknüpfen fehlgeschlagen: {failure}", "acd01e781e2355cc": "Anfrage beendet", "97e4c50a99272f63": "Die Anfrage konnte nicht beantwortet werden. Versuche es erneut.", + "605a491783d18b3f": "Dieser Thread konnte nicht über {via} gelesen werden", + "50f19209548b70d9": "{via} braucht möglicherweise ein Update, bevor es verknüpfte Threads lesen kann.", + "3d624e57d675358c": "Verknüpfte Umgebungen ist auf {via} deaktiviert", + "01b2231effdb835f": "Aktiviere es in den Einstellungen → Labs von {via}, um Threads auf den damit verknüpften Rechnern zu lesen.", + "e767e8901a0a3f35": "{via} ist nicht mehr mit {label} verknüpft", + "df3cd6ccd77084b4": "Verknüpfe es erneut in den Einstellungen → Verbindungen von {via}, um seine Threads von hier aus zu lesen.", + "3920637506407ca0": "Die Verknüpfung von {via} zu {label} ist abgelaufen", + "80fec3c2b4fba678": "Verknüpfe es erneut in den Einstellungen → Verbindungen von {via} mit einem neuen Kopplungscode.", + "fec50d228dc9aa9b": "{label} hat das Lesen abgelehnt", + "cd63d78559603b12": "Dieser Thread ist nicht mehr auf {label}", + "bd29efc163476e72": "Möglicherweise wurde er dort gelöscht.", + "f7870ef3a4828ab1": "{label} braucht ein Update", + "eabbf064657519ee": "{label} antwortet {via} nicht", "f71597ae3afaef44": "{first} und {second}", "4047174839a16714": "{first} und {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2343,6 +2356,7 @@ "ac0de2a59d9c8860": "Gerät", "1354df9fb7278843": "Einen iOS-Simulator oder Android-Emulator ansehen.", "fdcd9643e2e63b15": "Stelle eine Nebenfrage, während dieser Thread weiterarbeitet.", + "1944f04b75ddf26d": "Thread auf {label}", "314cfeebf191ba0d": "Genehmigung nötig", "4e5b7363441a3831": "Eingabe nötig", "97af4e74a5f95e5e": "läuft", @@ -3604,6 +3618,22 @@ " verknüpft. Der Agent kann diese Verknüpfung so verwenden; ändere den Zugriff unter Einstellungen → Umgebungen." ], "000b0df227182d39": "Andere Adresse…", + "6bb5b1b35b2796ae": "Auf {label} über {via} · Arbeitet", + "a73b7ab25d6e9bdf": "Auf {label} über {via}", + "009e2ca841fdc1ef": "diese Umgebung", + "8cb2e5692c4f05ab": "Öffne diesen Thread auf {label}, um diese Darstellung zu sehen.", + "745a0b899008618c": "Frühere Runden konnten nicht geladen werden. Versuche es erneut.", + "0014ce0aaf1bd68a": "Schreibgeschützt", + "d0bda35aeec66684": [ + "Wird von ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " gelesen …" + ], + "c3e8cd9bf44e2f43": "Angezeigt wird, was zuvor gelesen wurde.", "eb6e0584cf4a2a1d": "Sprache: {language}", "d76c606a3c519b78": "Zeilenumbruch deaktivieren", "2b683498cee8c8a7": "Zeilen umbrechen", @@ -3631,6 +3661,7 @@ "6d329f7d3a50c7e7": "Tabelle kopieren", "6c71d251d9917587": "Als Markdown kopieren", "d510b122f84051a0": "Als CSV kopieren", + "2912e4ac3697686b": "Thread auf {label} lesen", "ced684880c2e1961": "{server} erlauben, {tool} auszuführen?", "b66fa23b5647b62d": "Diese Nachricht von {server} senden?", "bae7f74153fa8a05": "{names} von {server} speichern?", @@ -4163,7 +4194,6 @@ "309b160785f6c473": "Fork in diesem Chat öffnen", "6676cd4b8299663f": "Übergeordneten Thread in diesem Chat öffnen", "63e8c7a0ef0513b5": "Verwandte Threads", - "68060b380fe53942": "Läuft auf {label}. Verbinde dich damit, um den Thread dort zu öffnen.", "9996d9dac573001a": "Auf {label} öffnen", "15a601a94893277f": "Der übergeordnete Thread konnte nicht geöffnet werden", "5eb43f554a5b7a58": "Der übergeordnete Thread wurde gelöscht", @@ -5688,7 +5718,6 @@ "4333d220c55ba5e4": "Abfrage des Arbeitsbereichs fehlgeschlagen.", "422c1671dfcfe474": "''{path}'' existiert nicht.", "20194b81e50497ad": "Ordner kann nicht geladen werden.", - "745a0b899008618c": "Frühere Runden konnten nicht geladen werden. Versuche es erneut.", "0061fff77e36bd4f": "Der Server ist nicht erreichbar.", "04dfdd46e3dd4a2e": "Etwas ist schiefgelaufen. Versuche es erneut.", "084bb2d8127a508d": "Gesendet", @@ -5778,19 +5807,17 @@ "56ca98b79cc9ce49": "Aktivität ({count})", "ddc5e5413923c471": "Du kannst hier nicht kommentieren.", "516def6f5a881e00": "Schließt dieses Issue", - "0014ce0aaf1bd68a": "Schreibgeschützt", "fd93f4720ff70aaf": "Keine", "b6a29fff7c7c0808": "Niemand", "54420465784bb1bd": "Ältere Kommentare laden", "9d82ebf35bfb4043": "Hier ist noch nichts passiert.", - "1cf216566c1ee064": "Projekt nicht verfügbar", "b5ddadeb0810688c": "Status", "93c1fc19d9bf1db0": "Beteiligung", "d5a8b335d88b65bc": "{hidden} ausgeblendet", "2160067266a61dd8": "Beliebig", "cd4ec4acf33c65b9": "{count, plural, one {{count} Label} other {{count} Labels}}", "bfd20acb8b7dee6b": "Beliebig", - "ad208e3e32c85029": "Alle ausblenden", + "aead644e2cf1233f": "Alle anzeigen", "77ce79d865716719": "Keine passenden Projekte.", "af7eb4f9c7f0f575": "Filter", "08247dd39b0c85ff": "Zugewiesene Person", @@ -6465,7 +6492,6 @@ "64d0189be492147c": "Check-Details können nicht geöffnet werden", "600347ca50400a54": "Checks werden geladen…", "1b381201aba745c2": "Keine Checks gemeldet", - "aead644e2cf1233f": "Alle anzeigen", "a6d75a4380173c60": "Checks öffnen: {summary}", "be3d1766bad18693": "Checks: {summary}", "425e4a3d6c5c2867": "{count, plural, one {{count} fehlgeschlagen} other {{count} fehlgeschlagen}}", @@ -9747,6 +9773,7 @@ "51497bd401292062": "Gedrückt halten", "9d6cc6ac23312071": "Doppelt drücken", "f001fa7b329c8fbf": "Erfolgreiche ausblenden", + "ad208e3e32c85029": "Alle ausblenden", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Nur Status", "cf0f7fc3df26fa75": "Status und Nachrichten", @@ -9956,6 +9983,7 @@ "573ea5fdf293a9d6": "Alle Checkouts", "470ad8c54049d1e1": "Checkouts durchsuchen", "7e2dfdd9f97fc027": "Projektbereich", + "1cf216566c1ee064": "Projekt nicht verfügbar", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 05b83efc41fc5..bf9125e821f5d 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -94,6 +94,19 @@ "21be308917bd450e": "Could not link: {failure}", "acd01e781e2355cc": "Request ended", "97e4c50a99272f63": "Could not answer the request. Try again.", + "605a491783d18b3f": "Could not read this thread through {via}", + "50f19209548b70d9": "{via} may need an update before it can read linked threads.", + "3d624e57d675358c": "Linked environments is off on {via}", + "01b2231effdb835f": "Turn it on in {via}'s Settings → Labs to read threads on the machines it links to.", + "e767e8901a0a3f35": "{via} is no longer linked to {label}", + "df3cd6ccd77084b4": "Link it again in {via}'s Settings → Connections to read its threads from here.", + "3920637506407ca0": "The link from {via} to {label} expired", + "80fec3c2b4fba678": "Link it again in {via}'s Settings → Connections with a new pairing code.", + "fec50d228dc9aa9b": "{label} refused the read", + "cd63d78559603b12": "This thread is no longer on {label}", + "bd29efc163476e72": "It may have been deleted there.", + "f7870ef3a4828ab1": "{label} needs an update", + "eabbf064657519ee": "{label} is not answering {via}", "f71597ae3afaef44": "{first} and {second}", "4047174839a16714": "{first}, and {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2343,6 +2356,7 @@ "ac0de2a59d9c8860": "Device", "1354df9fb7278843": "Watch an iOS Simulator or Android Emulator.", "fdcd9643e2e63b15": "Ask a side question while this thread keeps working.", + "1944f04b75ddf26d": "Thread on {label}", "314cfeebf191ba0d": "needs approval", "4e5b7363441a3831": "needs input", "97af4e74a5f95e5e": "running", @@ -3603,6 +3617,22 @@ ". The agent can use that link as it is; change its access in Settings → Environments." ], "000b0df227182d39": "Another address…", + "6bb5b1b35b2796ae": "On {label} via {via} · Working", + "a73b7ab25d6e9bdf": "On {label} via {via}", + "009e2ca841fdc1ef": "this environment", + "8cb2e5692c4f05ab": "Open this thread on {label} to see this visual.", + "745a0b899008618c": "Could not load earlier turns. Try again.", + "0014ce0aaf1bd68a": "Read-only", + "d0bda35aeec66684": [ + "Reading from ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "Showing what was read before.", "eb6e0584cf4a2a1d": "Language: {language}", "d76c606a3c519b78": "Disable line wrap", "2b683498cee8c8a7": "Wrap lines", @@ -3630,6 +3660,7 @@ "6d329f7d3a50c7e7": "Copy table", "6c71d251d9917587": "Copy as Markdown", "d510b122f84051a0": "Copy as CSV", + "2912e4ac3697686b": "Read the thread on {label}", "ced684880c2e1961": "Allow {server} to run {tool}?", "b66fa23b5647b62d": "Send this message from {server}?", "bae7f74153fa8a05": "Save {names} from {server}?", @@ -4162,7 +4193,6 @@ "309b160785f6c473": "Open fork in this chat", "6676cd4b8299663f": "Open parent thread in this chat", "63e8c7a0ef0513b5": "Related threads", - "68060b380fe53942": "Runs on {label}. Connect to it to open the thread there.", "9996d9dac573001a": "Open on {label}", "15a601a94893277f": "Could not open the parent thread", "5eb43f554a5b7a58": "The parent thread was deleted", @@ -5689,7 +5719,6 @@ "4333d220c55ba5e4": "Workspace query failed.", "422c1671dfcfe474": "''{path}'' does not exist.", "20194b81e50497ad": "Unable to load folder.", - "745a0b899008618c": "Could not load earlier turns. Try again.", "0061fff77e36bd4f": "Could not reach the server.", "04dfdd46e3dd4a2e": "Something went wrong. Try again.", "084bb2d8127a508d": "Sent", @@ -5779,19 +5808,17 @@ "56ca98b79cc9ce49": "Activity ({count})", "ddc5e5413923c471": "You cannot comment here.", "516def6f5a881e00": "Closes this issue", - "0014ce0aaf1bd68a": "Read-only", "fd93f4720ff70aaf": "None", "b6a29fff7c7c0808": "None", "54420465784bb1bd": "Load older comments", "9d82ebf35bfb4043": "Nothing has happened here yet.", - "1cf216566c1ee064": "Unavailable project", "b5ddadeb0810688c": "State", "93c1fc19d9bf1db0": "Involvement", "d5a8b335d88b65bc": "{hidden} hidden", "2160067266a61dd8": "Any", "cd4ec4acf33c65b9": "{count, plural, one {{count} label} other {{count} labels}}", "bfd20acb8b7dee6b": "Anyone", - "ad208e3e32c85029": "Hide all", + "aead644e2cf1233f": "Show all", "77ce79d865716719": "No matching projects.", "af7eb4f9c7f0f575": "Filters", "08247dd39b0c85ff": "Assignee", @@ -6472,7 +6499,6 @@ "64d0189be492147c": "Unable to open check details", "600347ca50400a54": "Loading checks…", "1b381201aba745c2": "No checks reported", - "aead644e2cf1233f": "Show all", "a6d75a4380173c60": "Open checks: {summary}", "be3d1766bad18693": "Checks: {summary}", "425e4a3d6c5c2867": "{count, plural, one {{count} failed} other {{count} failed}}", @@ -9756,6 +9782,7 @@ "51497bd401292062": "Hold", "9d6cc6ac23312071": "Double press", "f001fa7b329c8fbf": "Hide successful", + "ad208e3e32c85029": "Hide all", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Status only", "cf0f7fc3df26fa75": "Status and messages", @@ -9965,6 +9992,7 @@ "573ea5fdf293a9d6": "All checkouts", "470ad8c54049d1e1": "Search checkouts", "7e2dfdd9f97fc027": "Project scope", + "1cf216566c1ee064": "Unavailable project", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 05ee7b77c7d7f..e0f52492df584 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -94,6 +94,19 @@ "21be308917bd450e": "No se pudo vincular: {failure}", "acd01e781e2355cc": "Solicitud finalizada", "97e4c50a99272f63": "No se pudo responder a la solicitud. Inténtalo de nuevo.", + "605a491783d18b3f": "No se pudo leer este hilo a través de {via}", + "50f19209548b70d9": "Puede que {via} necesite actualizarse para poder leer hilos vinculados.", + "3d624e57d675358c": "Entornos vinculados está desactivado en {via}", + "01b2231effdb835f": "Actívalo en Ajustes → Labs de {via} para leer hilos de las máquinas que vincula.", + "e767e8901a0a3f35": "{via} ya no está vinculado a {label}", + "df3cd6ccd77084b4": "Vuelve a vincularlo en Ajustes → Conexiones de {via} para leer sus hilos desde aquí.", + "3920637506407ca0": "El vínculo de {via} a {label} ha caducado", + "80fec3c2b4fba678": "Vuelve a vincularlo en Ajustes → Conexiones de {via} con un código de emparejamiento nuevo.", + "fec50d228dc9aa9b": "{label} rechazó la lectura", + "cd63d78559603b12": "Este hilo ya no está en {label}", + "bd29efc163476e72": "Puede que se haya eliminado allí.", + "f7870ef3a4828ab1": "{label} necesita una actualización", + "eabbf064657519ee": "{label} no responde a {via}", "f71597ae3afaef44": "{first} y {second}", "4047174839a16714": "{first} y {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2343,6 +2356,7 @@ "ac0de2a59d9c8860": "Dispositivo", "1354df9fb7278843": "Mira un simulador de iOS o un emulador de Android.", "fdcd9643e2e63b15": "Haz una pregunta aparte mientras este hilo sigue trabajando.", + "1944f04b75ddf26d": "Hilo en {label}", "314cfeebf191ba0d": "necesita aprobación", "4e5b7363441a3831": "necesita respuesta", "97af4e74a5f95e5e": "en curso", @@ -3603,6 +3617,22 @@ ". El agente puede usar ese vínculo tal cual; cambia su acceso en Ajustes → Entornos." ], "000b0df227182d39": "Otra dirección…", + "6bb5b1b35b2796ae": "En {label} a través de {via} · Trabajando", + "a73b7ab25d6e9bdf": "En {label} a través de {via}", + "009e2ca841fdc1ef": "este entorno", + "8cb2e5692c4f05ab": "Abre este hilo en {label} para ver este elemento visual.", + "745a0b899008618c": "No se pudieron cargar los turnos anteriores. Vuelve a intentarlo.", + "0014ce0aaf1bd68a": "Solo lectura", + "d0bda35aeec66684": [ + "Leyendo desde ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "Se muestra lo que se leyó antes.", "eb6e0584cf4a2a1d": "Lenguaje: {language}", "d76c606a3c519b78": "Desactivar ajuste de línea", "2b683498cee8c8a7": "Ajustar líneas", @@ -3630,6 +3660,7 @@ "6d329f7d3a50c7e7": "Copiar tabla", "6c71d251d9917587": "Copiar como Markdown", "d510b122f84051a0": "Copiar como CSV", + "2912e4ac3697686b": "Leer el hilo en {label}", "ced684880c2e1961": "¿Permitir que {server} ejecute {tool}?", "b66fa23b5647b62d": "¿Enviar este mensaje desde {server}?", "bae7f74153fa8a05": "¿Guardar {names} desde {server}?", @@ -4160,7 +4191,6 @@ "309b160785f6c473": "Abrir la bifurcación en este chat", "6676cd4b8299663f": "Abrir el hilo principal en este chat", "63e8c7a0ef0513b5": "Hilos relacionados", - "68060b380fe53942": "Se ejecuta en {label}. Conéctate para abrir el hilo allí.", "9996d9dac573001a": "Abrir en {label}", "15a601a94893277f": "No se pudo abrir el hilo principal", "5eb43f554a5b7a58": "El hilo principal se eliminó", @@ -5687,7 +5717,6 @@ "4333d220c55ba5e4": "Falló la consulta al espacio de trabajo.", "422c1671dfcfe474": "''{path}'' no existe.", "20194b81e50497ad": "No se puede cargar la carpeta.", - "745a0b899008618c": "No se pudieron cargar los turnos anteriores. Vuelve a intentarlo.", "0061fff77e36bd4f": "No se pudo acceder al servidor.", "04dfdd46e3dd4a2e": "Algo salió mal. Vuelve a intentarlo.", "084bb2d8127a508d": "Enviado", @@ -5777,19 +5806,17 @@ "56ca98b79cc9ce49": "Actividad ({count})", "ddc5e5413923c471": "No puedes comentar aquí.", "516def6f5a881e00": "Cierra esta issue", - "0014ce0aaf1bd68a": "Solo lectura", "fd93f4720ff70aaf": "Ninguna", "b6a29fff7c7c0808": "Nadie", "54420465784bb1bd": "Cargar comentarios anteriores", "9d82ebf35bfb4043": "Aquí no ha pasado nada todavía.", - "1cf216566c1ee064": "Proyecto no disponible", "b5ddadeb0810688c": "Estado", "93c1fc19d9bf1db0": "Participación", "d5a8b335d88b65bc": "{hidden} ocultos", "2160067266a61dd8": "Cualquiera", "cd4ec4acf33c65b9": "{count, plural, one {{count} etiqueta} other {{count} etiquetas}}", "bfd20acb8b7dee6b": "Cualquiera", - "ad208e3e32c85029": "Ocultar todo", + "aead644e2cf1233f": "Mostrar todo", "77ce79d865716719": "No hay proyectos que coincidan.", "af7eb4f9c7f0f575": "Filtros", "08247dd39b0c85ff": "Asignado", @@ -6465,7 +6492,6 @@ "64d0189be492147c": "No se pueden abrir los detalles de la comprobación", "600347ca50400a54": "Cargando comprobaciones…", "1b381201aba745c2": "No se informó de ninguna comprobación", - "aead644e2cf1233f": "Mostrar todo", "a6d75a4380173c60": "Abrir comprobaciones: {summary}", "be3d1766bad18693": "Comprobaciones: {summary}", "425e4a3d6c5c2867": "{count, plural, one {{count} con errores} other {{count} con errores}}", @@ -9744,6 +9770,7 @@ "51497bd401292062": "Mantener pulsado", "9d6cc6ac23312071": "Doble pulsación", "f001fa7b329c8fbf": "Ocultar las correctas", + "ad208e3e32c85029": "Ocultar todo", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Solo el estado", "cf0f7fc3df26fa75": "Estado y mensajes", @@ -9953,6 +9980,7 @@ "573ea5fdf293a9d6": "Todos los checkouts", "470ad8c54049d1e1": "Buscar checkouts", "7e2dfdd9f97fc027": "Ámbito de proyectos", + "1cf216566c1ee064": "Proyecto no disponible", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index ada03eb7f10a6..97cd5bc681a6f 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -94,6 +94,19 @@ "21be308917bd450e": "Association impossible : {failure}", "acd01e781e2355cc": "Demande terminée", "97e4c50a99272f63": "Impossible de répondre à la demande. Réessayez.", + "605a491783d18b3f": "Impossible de lire ce fil via {via}", + "50f19209548b70d9": "{via} a peut-être besoin d’une mise à jour pour lire les fils associés.", + "3d624e57d675358c": "Les environnements associés sont désactivés sur {via}", + "01b2231effdb835f": "Activez-les dans Paramètres → Labs de {via} pour lire les fils des machines qui lui sont associées.", + "e767e8901a0a3f35": "{via} n’est plus associé à {label}", + "df3cd6ccd77084b4": "Associez-le à nouveau dans Paramètres → Connexions de {via} pour lire ses fils d’ici.", + "3920637506407ca0": "L’association de {via} à {label} a expiré", + "80fec3c2b4fba678": "Associez-le à nouveau dans Paramètres → Connexions de {via} avec un nouveau code d’appairage.", + "fec50d228dc9aa9b": "{label} a refusé la lecture", + "cd63d78559603b12": "Ce fil n’est plus sur {label}", + "bd29efc163476e72": "Il a peut-être été supprimé là-bas.", + "f7870ef3a4828ab1": "{label} a besoin d’une mise à jour", + "eabbf064657519ee": "{label} ne répond pas à {via}", "f71597ae3afaef44": "{first} et {second}", "4047174839a16714": "{first} et {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2343,6 +2356,7 @@ "ac0de2a59d9c8860": "Appareil", "1354df9fb7278843": "Regardez un simulateur iOS ou un émulateur Android.", "fdcd9643e2e63b15": "Posez une question annexe pendant que ce fil continue de travailler.", + "1944f04b75ddf26d": "Fil sur {label}", "314cfeebf191ba0d": "approbation requise", "4e5b7363441a3831": "réponse requise", "97af4e74a5f95e5e": "en cours", @@ -3603,6 +3617,22 @@ ". L’agent peut utiliser cette association telle quelle ; modifiez son accès dans Paramètres → Environnements." ], "000b0df227182d39": "Autre adresse…", + "6bb5b1b35b2796ae": "Sur {label} via {via} · En cours", + "a73b7ab25d6e9bdf": "Sur {label} via {via}", + "009e2ca841fdc1ef": "cet environnement", + "8cb2e5692c4f05ab": "Ouvrez ce fil sur {label} pour voir ce visuel.", + "745a0b899008618c": "Impossible de charger les tours précédents. Réessayez.", + "0014ce0aaf1bd68a": "Lecture seule", + "d0bda35aeec66684": [ + "Lecture depuis ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "Affichage de ce qui a été lu auparavant.", "eb6e0584cf4a2a1d": "Langage : {language}", "d76c606a3c519b78": "Désactiver le retour à la ligne", "2b683498cee8c8a7": "Retour à la ligne", @@ -3630,6 +3660,7 @@ "6d329f7d3a50c7e7": "Copier le tableau", "6c71d251d9917587": "Copier en Markdown", "d510b122f84051a0": "Copier en CSV", + "2912e4ac3697686b": "Lire le fil sur {label}", "ced684880c2e1961": "Autoriser {server} à exécuter {tool} ?", "b66fa23b5647b62d": "Envoyer ce message depuis {server} ?", "bae7f74153fa8a05": "Enregistrer {names} depuis {server} ?", @@ -4161,7 +4192,6 @@ "309b160785f6c473": "Ouvrir le fork dans cette discussion", "6676cd4b8299663f": "Ouvrir le fil parent dans cette discussion", "63e8c7a0ef0513b5": "Fils liés", - "68060b380fe53942": "S’exécute sur {label}. Connectez-vous-y pour y ouvrir le fil.", "9996d9dac573001a": "Ouvrir sur {label}", "15a601a94893277f": "Impossible d’ouvrir le fil parent", "5eb43f554a5b7a58": "Le fil parent a été supprimé", @@ -5688,7 +5718,6 @@ "4333d220c55ba5e4": "Échec de la requête sur l’espace de travail.", "422c1671dfcfe474": "''{path}'' n’existe pas.", "20194b81e50497ad": "Impossible de charger le dossier.", - "745a0b899008618c": "Impossible de charger les tours précédents. Réessayez.", "0061fff77e36bd4f": "Impossible de joindre le serveur.", "04dfdd46e3dd4a2e": "Une erreur s’est produite. Réessayez.", "084bb2d8127a508d": "Envoyé", @@ -5778,19 +5807,17 @@ "56ca98b79cc9ce49": "Activité ({count})", "ddc5e5413923c471": "Vous ne pouvez pas commenter ici.", "516def6f5a881e00": "Ferme ce ticket", - "0014ce0aaf1bd68a": "Lecture seule", "fd93f4720ff70aaf": "Aucun", "b6a29fff7c7c0808": "Personne", "54420465784bb1bd": "Charger les commentaires plus anciens", "9d82ebf35bfb4043": "Rien ne s’est encore passé ici.", - "1cf216566c1ee064": "Projet indisponible", "b5ddadeb0810688c": "État", "93c1fc19d9bf1db0": "Participation", "d5a8b335d88b65bc": "{hidden} masqués", "2160067266a61dd8": "Tous", "cd4ec4acf33c65b9": "{count, plural, one {{count} libellé} other {{count} libellés}}", "bfd20acb8b7dee6b": "N’importe qui", - "ad208e3e32c85029": "Tout masquer", + "aead644e2cf1233f": "Tout afficher", "77ce79d865716719": "Aucun projet correspondant.", "af7eb4f9c7f0f575": "Filtres", "08247dd39b0c85ff": "Assigné", @@ -6466,7 +6493,6 @@ "64d0189be492147c": "Impossible d’ouvrir les détails du check", "600347ca50400a54": "Chargement des checks…", "1b381201aba745c2": "Aucun check signalé", - "aead644e2cf1233f": "Tout afficher", "a6d75a4380173c60": "Ouvrir les checks : {summary}", "be3d1766bad18693": "Checks : {summary}", "425e4a3d6c5c2867": "{count, plural, one {{count} en échec} other {{count} en échec}}", @@ -9746,6 +9772,7 @@ "51497bd401292062": "Appui long", "9d6cc6ac23312071": "Double appui", "f001fa7b329c8fbf": "Masquer les réussis", + "ad208e3e32c85029": "Tout masquer", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Statut uniquement", "cf0f7fc3df26fa75": "Statut et messages", @@ -9955,6 +9982,7 @@ "573ea5fdf293a9d6": "Tous les checkouts", "470ad8c54049d1e1": "Rechercher des checkouts", "7e2dfdd9f97fc027": "Portée des projets", + "1cf216566c1ee064": "Projet indisponible", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 9d743e7e0a7f0..43ee223b82fe4 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -94,6 +94,19 @@ "21be308917bd450e": "リンクできませんでした: {failure}", "acd01e781e2355cc": "リクエストが終了しました", "97e4c50a99272f63": "リクエストに応答できませんでした。もう一度お試しください。", + "605a491783d18b3f": "{via} 経由でこのスレッドを読み取れませんでした", + "50f19209548b70d9": "リンクされたスレッドを読み取るには、{via} の更新が必要な可能性があります。", + "3d624e57d675358c": "{via} でリンクされた環境がオフになっています", + "01b2231effdb835f": "{via} の設定 → Labs でオンにすると、リンク先のマシンのスレッドを読み取れます。", + "e767e8901a0a3f35": "{via} は {label} にリンクされていません", + "df3cd6ccd77084b4": "ここからスレッドを読み取るには、{via} の設定 → 接続で再度リンクしてください。", + "3920637506407ca0": "{via} から {label} へのリンクは期限切れです", + "80fec3c2b4fba678": "{via} の設定 → 接続で、新しいペアリングコードを使って再度リンクしてください。", + "fec50d228dc9aa9b": "{label} が読み取りを拒否しました", + "cd63d78559603b12": "このスレッドはもう {label} にありません", + "bd29efc163476e72": "そちらで削除された可能性があります。", + "f7870ef3a4828ab1": "{label} の更新が必要です", + "eabbf064657519ee": "{label} が {via} に応答していません", "f71597ae3afaef44": "{first} と {second}", "4047174839a16714": "{first}、{last}", "65ca7867c176afbf": "{first}、{rest}", @@ -2341,6 +2354,7 @@ "ac0de2a59d9c8860": "デバイス", "1354df9fb7278843": "iOS シミュレーターまたは Android エミュレーターを表示します。", "fdcd9643e2e63b15": "このスレッドの作業を続けたまま、別の質問をします。", + "1944f04b75ddf26d": "{label} のスレッド", "314cfeebf191ba0d": "承認が必要", "4e5b7363441a3831": "入力が必要", "97af4e74a5f95e5e": "実行中", @@ -3598,6 +3612,22 @@ " にリンクされています。エージェントはそのリンクをそのまま使用できます。アクセス権は [設定] → [環境] で変更してください。" ], "000b0df227182d39": "別のアドレス…", + "6bb5b1b35b2796ae": "{label}({via} 経由) · 作業中", + "a73b7ab25d6e9bdf": "{label}({via} 経由)", + "009e2ca841fdc1ef": "この環境", + "8cb2e5692c4f05ab": "このビジュアルを見るには、{label} でこのスレッドを開いてください。", + "745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。", + "0014ce0aaf1bd68a": "読み取り専用", + "d0bda35aeec66684": [ + "読み取り中: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "以前に読み取った内容を表示しています。", "eb6e0584cf4a2a1d": "言語: {language}", "d76c606a3c519b78": "行の折り返しを無効にする", "2b683498cee8c8a7": "行を折り返す", @@ -3625,6 +3655,7 @@ "6d329f7d3a50c7e7": "表をコピー", "6c71d251d9917587": "Markdown としてコピー", "d510b122f84051a0": "CSV としてコピー", + "2912e4ac3697686b": "{label} のスレッドを読む", "ced684880c2e1961": "{server} に {tool} の実行を許可しますか?", "b66fa23b5647b62d": "{server} からこのメッセージを送信しますか?", "bae7f74153fa8a05": "{server} からの {names} を保存しますか?", @@ -4151,7 +4182,6 @@ "309b160785f6c473": "このチャットでフォークを開く", "6676cd4b8299663f": "このチャットで親スレッドを開く", "63e8c7a0ef0513b5": "関連するスレッド", - "68060b380fe53942": "{label} で実行されています。そこでスレッドを開くには接続してください。", "9996d9dac573001a": "{label} で開く", "15a601a94893277f": "親スレッドを開けませんでした", "5eb43f554a5b7a58": "親スレッドは削除されました", @@ -5670,7 +5700,6 @@ "4333d220c55ba5e4": "ワークスペースのクエリに失敗しました。", "422c1671dfcfe474": "''{path}'' は存在しません。", "20194b81e50497ad": "フォルダーを読み込めません。", - "745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。", "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", @@ -5760,19 +5789,17 @@ "56ca98b79cc9ce49": "アクティビティ ({count})", "ddc5e5413923c471": "ここではコメントできません。", "516def6f5a881e00": "この Issue をクローズします", - "0014ce0aaf1bd68a": "読み取り専用", "fd93f4720ff70aaf": "なし", "b6a29fff7c7c0808": "なし", "54420465784bb1bd": "以前のコメントを読み込む", "9d82ebf35bfb4043": "まだアクティビティはありません。", - "1cf216566c1ee064": "利用できないプロジェクト", "b5ddadeb0810688c": "状態", "93c1fc19d9bf1db0": "関与", "d5a8b335d88b65bc": "{hidden} 件非表示", "2160067266a61dd8": "すべて", "cd4ec4acf33c65b9": "{count, plural, other {{count} 個のラベル}}", "bfd20acb8b7dee6b": "すべてのユーザー", - "ad208e3e32c85029": "すべて非表示", + "aead644e2cf1233f": "すべて表示", "77ce79d865716719": "一致するプロジェクトはありません。", "af7eb4f9c7f0f575": "フィルター", "08247dd39b0c85ff": "担当者", @@ -6435,7 +6462,6 @@ "64d0189be492147c": "チェックの詳細を開けません", "600347ca50400a54": "チェックを読み込んでいます…", "1b381201aba745c2": "報告されたチェックはありません", - "aead644e2cf1233f": "すべて表示", "a6d75a4380173c60": "チェックを開く: {summary}", "be3d1766bad18693": "チェック: {summary}", "425e4a3d6c5c2867": "{count, plural, other {{count} 件失敗}}", @@ -9698,6 +9724,7 @@ "51497bd401292062": "長押し", "9d6cc6ac23312071": "2 回押し", "f001fa7b329c8fbf": "成功したものを非表示", + "ad208e3e32c85029": "すべて非表示", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "ステータスのみ", "cf0f7fc3df26fa75": "ステータスとメッセージ", @@ -9907,6 +9934,7 @@ "573ea5fdf293a9d6": "すべてのチェックアウト", "470ad8c54049d1e1": "チェックアウトを検索", "7e2dfdd9f97fc027": "プロジェクトの範囲", + "1cf216566c1ee064": "利用できないプロジェクト", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 943c383b7cef3..0536a957dcf87 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -94,6 +94,19 @@ "21be308917bd450e": "연결할 수 없음: {failure}", "acd01e781e2355cc": "요청 종료됨", "97e4c50a99272f63": "요청에 응답할 수 없습니다. 다시 시도하세요.", + "605a491783d18b3f": "{via}을(를) 통해 이 스레드를 읽지 못했습니다", + "50f19209548b70d9": "연결된 스레드를 읽으려면 {via}을(를) 업데이트해야 할 수 있습니다.", + "3d624e57d675358c": "{via}에서 연결된 환경이 꺼져 있습니다", + "01b2231effdb835f": "{via}의 설정 → Labs에서 켜면 연결된 기기의 스레드를 읽을 수 있습니다.", + "e767e8901a0a3f35": "{via}이(가) 더 이상 {label}에 연결되어 있지 않습니다", + "df3cd6ccd77084b4": "여기에서 스레드를 읽으려면 {via}의 설정 → 연결에서 다시 연결하세요.", + "3920637506407ca0": "{via}에서 {label}(으)로의 연결이 만료되었습니다", + "80fec3c2b4fba678": "{via}의 설정 → 연결에서 새 페어링 코드로 다시 연결하세요.", + "fec50d228dc9aa9b": "{label}이(가) 읽기를 거부했습니다", + "cd63d78559603b12": "이 스레드는 더 이상 {label}에 없습니다", + "bd29efc163476e72": "그곳에서 삭제되었을 수 있습니다.", + "f7870ef3a4828ab1": "{label}을(를) 업데이트해야 합니다", + "eabbf064657519ee": "{label}이(가) {via}에 응답하지 않습니다", "f71597ae3afaef44": "{first} 및 {second}", "4047174839a16714": "{first} 및 {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2342,6 +2355,7 @@ "ac0de2a59d9c8860": "기기", "1354df9fb7278843": "iOS 시뮬레이터나 Android 에뮬레이터를 봅니다.", "fdcd9643e2e63b15": "이 스레드가 계속 작업하는 동안 곁가지 질문을 하세요.", + "1944f04b75ddf26d": "{label}의 스레드", "314cfeebf191ba0d": "승인 필요", "4e5b7363441a3831": "입력 필요", "97af4e74a5f95e5e": "실행 중", @@ -3598,6 +3612,22 @@ "에 연결되어 있습니다. 에이전트는 이 연결을 그대로 사용할 수 있으며, 액세스는 설정 → 환경에서 변경하세요." ], "000b0df227182d39": "다른 주소…", + "6bb5b1b35b2796ae": "{label} ({via} 경유) · 작업 중", + "a73b7ab25d6e9bdf": "{label} ({via} 경유)", + "009e2ca841fdc1ef": "이 환경", + "8cb2e5692c4f05ab": "이 시각 자료를 보려면 {label}에서 이 스레드를 여세요.", + "745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.", + "0014ce0aaf1bd68a": "읽기 전용", + "d0bda35aeec66684": [ + "읽는 중: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "이전에 읽은 내용을 표시하고 있습니다.", "eb6e0584cf4a2a1d": "언어: {language}", "d76c606a3c519b78": "줄 바꿈 끄기", "2b683498cee8c8a7": "줄 바꿈", @@ -3625,6 +3655,7 @@ "6d329f7d3a50c7e7": "표 복사", "6c71d251d9917587": "Markdown으로 복사", "d510b122f84051a0": "CSV로 복사", + "2912e4ac3697686b": "{label}의 스레드 읽기", "ced684880c2e1961": "{server}이(가) {tool}을(를) 실행하도록 허용할까요?", "b66fa23b5647b62d": "{server}에서 이 메시지를 보낼까요?", "bae7f74153fa8a05": "{server}에서 {names}을(를) 저장할까요?", @@ -4148,7 +4179,6 @@ "309b160785f6c473": "이 채팅에서 포크 열기", "6676cd4b8299663f": "이 채팅에서 상위 스레드 열기", "63e8c7a0ef0513b5": "관련 스레드", - "68060b380fe53942": "{label}에서 실행됩니다. 그곳에서 스레드를 열려면 연결하세요.", "9996d9dac573001a": "{label}에서 열기", "15a601a94893277f": "상위 스레드를 열 수 없습니다", "5eb43f554a5b7a58": "상위 스레드가 삭제되었습니다", @@ -5668,7 +5698,6 @@ "4333d220c55ba5e4": "작업 영역 쿼리에 실패했습니다.", "422c1671dfcfe474": "''{path}''이(가) 없습니다.", "20194b81e50497ad": "폴더를 불러올 수 없습니다.", - "745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.", "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", @@ -5758,19 +5787,17 @@ "56ca98b79cc9ce49": "활동({count})", "ddc5e5413923c471": "여기에는 댓글을 달 수 없습니다.", "516def6f5a881e00": "이 이슈를 닫음", - "0014ce0aaf1bd68a": "읽기 전용", "fd93f4720ff70aaf": "없음", "b6a29fff7c7c0808": "없음", "54420465784bb1bd": "이전 댓글 불러오기", "9d82ebf35bfb4043": "아직 활동이 없습니다.", - "1cf216566c1ee064": "사용할 수 없는 프로젝트", "b5ddadeb0810688c": "상태", "93c1fc19d9bf1db0": "참여", "d5a8b335d88b65bc": "{hidden}개 숨김", "2160067266a61dd8": "전체", "cd4ec4acf33c65b9": "{count, plural, other {레이블 {count}개}}", "bfd20acb8b7dee6b": "모든 사람", - "ad208e3e32c85029": "모두 숨기기", + "aead644e2cf1233f": "모두 표시", "77ce79d865716719": "일치하는 프로젝트가 없습니다.", "af7eb4f9c7f0f575": "필터", "08247dd39b0c85ff": "담당자", @@ -6437,7 +6464,6 @@ "64d0189be492147c": "검사 세부 정보를 열 수 없습니다", "600347ca50400a54": "검사를 불러오는 중…", "1b381201aba745c2": "보고된 검사 없음", - "aead644e2cf1233f": "모두 표시", "a6d75a4380173c60": "검사 열기: {summary}", "be3d1766bad18693": "검사: {summary}", "425e4a3d6c5c2867": "{count, plural, other {{count}개 실패}}", @@ -9701,6 +9727,7 @@ "51497bd401292062": "길게 누르기", "9d6cc6ac23312071": "두 번 누르기", "f001fa7b329c8fbf": "성공한 항목 숨기기", + "ad208e3e32c85029": "모두 숨기기", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "상태만", "cf0f7fc3df26fa75": "상태 및 메시지", @@ -9910,6 +9937,7 @@ "573ea5fdf293a9d6": "모든 체크아웃", "470ad8c54049d1e1": "체크아웃 검색", "7e2dfdd9f97fc027": "프로젝트 범위", + "1cf216566c1ee064": "사용할 수 없는 프로젝트", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 9f2f697d054c0..5003e05f792b7 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -94,6 +94,19 @@ "21be308917bd450e": "Não foi possível vincular: {failure}", "acd01e781e2355cc": "Solicitação encerrada", "97e4c50a99272f63": "Não foi possível responder à solicitação. Tente novamente.", + "605a491783d18b3f": "Não foi possível ler esta thread por {via}", + "50f19209548b70d9": "Talvez {via} precise de uma atualização para ler threads vinculadas.", + "3d624e57d675358c": "Ambientes vinculados está desativado em {via}", + "01b2231effdb835f": "Ative em Configurações → Labs de {via} para ler threads das máquinas vinculadas a ele.", + "e767e8901a0a3f35": "{via} não está mais vinculado a {label}", + "df3cd6ccd77084b4": "Vincule novamente em Configurações → Conexões de {via} para ler as threads dele daqui.", + "3920637506407ca0": "O vínculo de {via} com {label} expirou", + "80fec3c2b4fba678": "Vincule novamente em Configurações → Conexões de {via} com um novo código de pareamento.", + "fec50d228dc9aa9b": "{label} recusou a leitura", + "cd63d78559603b12": "Esta thread não está mais em {label}", + "bd29efc163476e72": "Talvez tenha sido excluída lá.", + "f7870ef3a4828ab1": "{label} precisa de uma atualização", + "eabbf064657519ee": "{label} não está respondendo a {via}", "f71597ae3afaef44": "{first} e {second}", "4047174839a16714": "{first} e {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2343,6 +2356,7 @@ "ac0de2a59d9c8860": "Dispositivo", "1354df9fb7278843": "Acompanhe um iOS Simulator ou Android Emulator.", "fdcd9643e2e63b15": "Faça uma pergunta paralela enquanto esta thread continua trabalhando.", + "1944f04b75ddf26d": "Thread em {label}", "314cfeebf191ba0d": "precisa de aprovação", "4e5b7363441a3831": "precisa de resposta", "97af4e74a5f95e5e": "em execução", @@ -3603,6 +3617,22 @@ ". O agente pode usar esse vínculo como está; altere o acesso em Configurações → Ambientes." ], "000b0df227182d39": "Outro endereço…", + "6bb5b1b35b2796ae": "Em {label} via {via} · Trabalhando", + "a73b7ab25d6e9bdf": "Em {label} via {via}", + "009e2ca841fdc1ef": "este ambiente", + "8cb2e5692c4f05ab": "Abra este thread em {label} para ver este visual.", + "745a0b899008618c": "Não foi possível carregar os turnos anteriores. Tente novamente.", + "0014ce0aaf1bd68a": "Somente leitura", + "d0bda35aeec66684": [ + "Lendo de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "Mostrando o que foi lido antes.", "eb6e0584cf4a2a1d": "Linguagem: {language}", "d76c606a3c519b78": "Desativar quebra de linha", "2b683498cee8c8a7": "Quebrar linhas", @@ -3630,6 +3660,7 @@ "6d329f7d3a50c7e7": "Copiar tabela", "6c71d251d9917587": "Copiar como Markdown", "d510b122f84051a0": "Copiar como CSV", + "2912e4ac3697686b": "Ler a thread em {label}", "ced684880c2e1961": "Permitir que {server} execute {tool}?", "b66fa23b5647b62d": "Enviar esta mensagem de {server}?", "bae7f74153fa8a05": "Salvar {names} de {server}?", @@ -4160,7 +4191,6 @@ "309b160785f6c473": "Abrir o fork neste chat", "6676cd4b8299663f": "Abrir a thread principal neste chat", "63e8c7a0ef0513b5": "Threads relacionadas", - "68060b380fe53942": "Roda em {label}. Conecte-se a ele para abrir a thread lá.", "9996d9dac573001a": "Abrir em {label}", "15a601a94893277f": "Não foi possível abrir a thread principal", "5eb43f554a5b7a58": "A thread principal foi excluída", @@ -5687,7 +5717,6 @@ "4333d220c55ba5e4": "Falha na consulta ao workspace.", "422c1671dfcfe474": "''{path}'' não existe.", "20194b81e50497ad": "Não foi possível carregar a pasta.", - "745a0b899008618c": "Não foi possível carregar os turnos anteriores. Tente novamente.", "0061fff77e36bd4f": "Não foi possível acessar o servidor.", "04dfdd46e3dd4a2e": "Algo deu errado. Tente novamente.", "084bb2d8127a508d": "Enviada", @@ -5777,19 +5806,17 @@ "56ca98b79cc9ce49": "Atividade ({count})", "ddc5e5413923c471": "Você não pode comentar aqui.", "516def6f5a881e00": "Fecha esta issue", - "0014ce0aaf1bd68a": "Somente leitura", "fd93f4720ff70aaf": "Nenhuma", "b6a29fff7c7c0808": "Ninguém", "54420465784bb1bd": "Carregar comentários mais antigos", "9d82ebf35bfb4043": "Nada aconteceu aqui ainda.", - "1cf216566c1ee064": "Projeto indisponível", "b5ddadeb0810688c": "Estado", "93c1fc19d9bf1db0": "Envolvimento", "d5a8b335d88b65bc": "{hidden} ocultos", "2160067266a61dd8": "Qualquer", "cd4ec4acf33c65b9": "{count, plural, one {{count} rótulo} other {{count} rótulos}}", "bfd20acb8b7dee6b": "Qualquer pessoa", - "ad208e3e32c85029": "Ocultar todas", + "aead644e2cf1233f": "Mostrar tudo", "77ce79d865716719": "Nenhum projeto correspondente.", "af7eb4f9c7f0f575": "Filtros", "08247dd39b0c85ff": "Responsável", @@ -6465,7 +6492,6 @@ "64d0189be492147c": "Não foi possível abrir os detalhes da verificação", "600347ca50400a54": "Carregando as verificações…", "1b381201aba745c2": "Nenhuma verificação informada", - "aead644e2cf1233f": "Mostrar tudo", "a6d75a4380173c60": "Abrir verificações: {summary}", "be3d1766bad18693": "Verificações: {summary}", "425e4a3d6c5c2867": "{count, plural, one {{count} com falha} other {{count} com falha}}", @@ -9745,6 +9771,7 @@ "51497bd401292062": "Manter pressionado", "9d6cc6ac23312071": "Pressionar duas vezes", "f001fa7b329c8fbf": "Ocultar bem-sucedidas", + "ad208e3e32c85029": "Ocultar todas", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Só status", "cf0f7fc3df26fa75": "Status e mensagens", @@ -9954,6 +9981,7 @@ "573ea5fdf293a9d6": "Todos os checkouts", "470ad8c54049d1e1": "Pesquisar checkouts", "7e2dfdd9f97fc027": "Escopo de projeto", + "1cf216566c1ee064": "Projeto indisponível", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 758380a495682..9d9c58696fd16 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -94,6 +94,19 @@ "21be308917bd450e": "Не удалось привязать: {failure}", "acd01e781e2355cc": "Запрос завершён", "97e4c50a99272f63": "Не удалось ответить на запрос. Повторите попытку.", + "605a491783d18b3f": "Не удалось прочитать этот тред через {via}", + "50f19209548b70d9": "Возможно, {via} нужно обновить, чтобы читать привязанные треды.", + "3d624e57d675358c": "Привязанные окружения отключены на {via}", + "01b2231effdb835f": "Включите их в разделе «Настройки → Labs» на {via}, чтобы читать треды на привязанных к нему машинах.", + "e767e8901a0a3f35": "{via} больше не связан с {label}", + "df3cd6ccd77084b4": "Свяжите заново в разделе «Настройки → Подключения» на {via}, чтобы читать его треды отсюда.", + "3920637506407ca0": "Срок связи {via} с {label} истёк", + "80fec3c2b4fba678": "Свяжите заново в разделе «Настройки → Подключения» на {via} с новым кодом сопряжения.", + "fec50d228dc9aa9b": "{label} отклонил чтение", + "cd63d78559603b12": "Этого треда больше нет на {label}", + "bd29efc163476e72": "Возможно, его там удалили.", + "f7870ef3a4828ab1": "{label} нужно обновить", + "eabbf064657519ee": "{label} не отвечает {via}", "f71597ae3afaef44": "{first} и {second}", "4047174839a16714": "{first} и {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2343,6 +2356,7 @@ "ac0de2a59d9c8860": "Устройство", "1354df9fb7278843": "Смотрите на iOS Simulator или Android Emulator.", "fdcd9643e2e63b15": "Задайте побочный вопрос, пока тред продолжает работу.", + "1944f04b75ddf26d": "Тред на {label}", "314cfeebf191ba0d": "нужно подтверждение", "4e5b7363441a3831": "нужен ввод", "97af4e74a5f95e5e": "выполняется", @@ -3603,6 +3617,22 @@ ". Агент может использовать эту привязку как есть; изменить её доступ можно в «Настройки → Окружения»." ], "000b0df227182d39": "Другой адрес…", + "6bb5b1b35b2796ae": "На {label} через {via} · Работает", + "a73b7ab25d6e9bdf": "На {label} через {via}", + "009e2ca841fdc1ef": "это окружение", + "8cb2e5692c4f05ab": "Откройте этот тред на {label}, чтобы увидеть это визуальное представление.", + "745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.", + "0014ce0aaf1bd68a": "Только чтение", + "d0bda35aeec66684": [ + "Чтение с ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "Показано то, что было прочитано раньше.", "eb6e0584cf4a2a1d": "Язык: {language}", "d76c606a3c519b78": "Отключить перенос строк", "2b683498cee8c8a7": "Переносить строки", @@ -3630,6 +3660,7 @@ "6d329f7d3a50c7e7": "Копировать таблицу", "6c71d251d9917587": "Копировать как Markdown", "d510b122f84051a0": "Копировать как CSV", + "2912e4ac3697686b": "Читать тред на {label}", "ced684880c2e1961": "Разрешить {server} запустить {tool}?", "b66fa23b5647b62d": "Отправить это сообщение от {server}?", "bae7f74153fa8a05": "Сохранить {names} от {server}?", @@ -4160,7 +4191,6 @@ "309b160785f6c473": "Открыть ответвление в этом чате", "6676cd4b8299663f": "Открыть родительский тред в этом чате", "63e8c7a0ef0513b5": "Связанные треды", - "68060b380fe53942": "Работает на {label}. Подключитесь к нему, чтобы открыть тред там.", "9996d9dac573001a": "Открыть на {label}", "15a601a94893277f": "Не удалось открыть родительский тред", "5eb43f554a5b7a58": "Родительский тред удалён", @@ -5687,7 +5717,6 @@ "4333d220c55ba5e4": "Ошибка запроса к рабочей области.", "422c1671dfcfe474": "''{path}'' не существует.", "20194b81e50497ad": "Не удалось загрузить папку.", - "745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.", "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", @@ -5777,19 +5806,17 @@ "56ca98b79cc9ce49": "Активность ({count})", "ddc5e5413923c471": "Здесь нельзя комментировать.", "516def6f5a881e00": "Закроет этот issue", - "0014ce0aaf1bd68a": "Только чтение", "fd93f4720ff70aaf": "Нет", "b6a29fff7c7c0808": "Нет", "54420465784bb1bd": "Загрузить старые комментарии", "9d82ebf35bfb4043": "Здесь пока ничего не происходило.", - "1cf216566c1ee064": "Проект недоступен", "b5ddadeb0810688c": "Состояние", "93c1fc19d9bf1db0": "Участие", "d5a8b335d88b65bc": "Скрыто: {hidden}", "2160067266a61dd8": "Любая", "cd4ec4acf33c65b9": "{count, plural, one {{count} метка} few {{count} метки} many {{count} меток} other {{count} метки}}", "bfd20acb8b7dee6b": "Любой", - "ad208e3e32c85029": "Скрывать все", + "aead644e2cf1233f": "Показать все", "77ce79d865716719": "Нет подходящих проектов.", "af7eb4f9c7f0f575": "Фильтры", "08247dd39b0c85ff": "Исполнитель", @@ -6465,7 +6492,6 @@ "64d0189be492147c": "Не удалось открыть подробности проверки", "600347ca50400a54": "Загрузка проверок…", "1b381201aba745c2": "Нет проверок", - "aead644e2cf1233f": "Показать все", "a6d75a4380173c60": "Открыть проверки: {summary}", "be3d1766bad18693": "Проверки: {summary}", "425e4a3d6c5c2867": "{count, plural, one {Ошибок: {count}} few {Ошибок: {count}} many {Ошибок: {count}} other {Ошибок: {count}}}", @@ -9748,6 +9774,7 @@ "51497bd401292062": "Удержание", "9d6cc6ac23312071": "Двойное нажатие", "f001fa7b329c8fbf": "Скрывать успешные", + "ad208e3e32c85029": "Скрывать все", "c80e4bb3201efd71": "Дзен", "0cb9ffcd1fb46b0c": "Только статус", "cf0f7fc3df26fa75": "Статус и сообщения", @@ -9957,6 +9984,7 @@ "573ea5fdf293a9d6": "Все копии", "470ad8c54049d1e1": "Поиск копий", "7e2dfdd9f97fc027": "Область проектов", + "1cf216566c1ee064": "Проект недоступен", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 5aa630e1a6853..0a645b45857ae 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -94,6 +94,19 @@ "21be308917bd450e": "Kunde inte länka: {failure}", "acd01e781e2355cc": "Begäran avslutades", "97e4c50a99272f63": "Kunde inte svara på begäran. Försök igen.", + "605a491783d18b3f": "Det gick inte att läsa den här tråden via {via}", + "50f19209548b70d9": "{via} kan behöva uppdateras innan den kan läsa länkade trådar.", + "3d624e57d675358c": "Länkade miljöer är avstängt på {via}", + "01b2231effdb835f": "Slå på det i Inställningar → Labs på {via} för att läsa trådar på maskinerna den länkar till.", + "e767e8901a0a3f35": "{via} är inte längre länkad till {label}", + "df3cd6ccd77084b4": "Länka den igen i Inställningar → Anslutningar på {via} för att läsa dess trådar härifrån.", + "3920637506407ca0": "Länken från {via} till {label} har gått ut", + "80fec3c2b4fba678": "Länka den igen i Inställningar → Anslutningar på {via} med en ny parkopplingskod.", + "fec50d228dc9aa9b": "{label} nekade läsningen", + "cd63d78559603b12": "Den här tråden finns inte längre på {label}", + "bd29efc163476e72": "Den kan ha raderats där.", + "f7870ef3a4828ab1": "{label} behöver uppdateras", + "eabbf064657519ee": "{label} svarar inte {via}", "f71597ae3afaef44": "{first} och {second}", "4047174839a16714": "{first} och {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -2343,6 +2356,7 @@ "ac0de2a59d9c8860": "Enhet", "1354df9fb7278843": "Titta på en iOS-simulator eller Android-emulator.", "fdcd9643e2e63b15": "Ställ en sidofråga medan tråden fortsätter arbeta.", + "1944f04b75ddf26d": "Tråd på {label}", "314cfeebf191ba0d": "behöver godkännande", "4e5b7363441a3831": "behöver input", "97af4e74a5f95e5e": "körs", @@ -3603,6 +3617,22 @@ ". Agenten kan använda den länken som den är; ändra dess åtkomst under Inställningar → Miljöer." ], "000b0df227182d39": "En annan adress…", + "6bb5b1b35b2796ae": "På {label} via {via} · Arbetar", + "a73b7ab25d6e9bdf": "På {label} via {via}", + "009e2ca841fdc1ef": "den här miljön", + "8cb2e5692c4f05ab": "Öppna den här tråden på {label} för att se den här visualiseringen.", + "745a0b899008618c": "Kunde inte läsa in tidigare omgångar. Försök igen.", + "0014ce0aaf1bd68a": "Skrivskyddad", + "d0bda35aeec66684": [ + "Läser från ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "c3e8cd9bf44e2f43": "Visar det som lästes tidigare.", "eb6e0584cf4a2a1d": "Språk: {language}", "d76c606a3c519b78": "Inaktivera radbrytning", "2b683498cee8c8a7": "Bryt rader", @@ -3630,6 +3660,7 @@ "6d329f7d3a50c7e7": "Kopiera tabell", "6c71d251d9917587": "Kopiera som Markdown", "d510b122f84051a0": "Kopiera som CSV", + "2912e4ac3697686b": "Läs tråden på {label}", "ced684880c2e1961": "Tillåta {server} att köra {tool}?", "b66fa23b5647b62d": "Skicka det här meddelandet från {server}?", "bae7f74153fa8a05": "Spara {names} från {server}?", @@ -4161,7 +4192,6 @@ "309b160785f6c473": "Öppna forken i den här chatten", "6676cd4b8299663f": "Öppna den överordnade tråden i den här chatten", "63e8c7a0ef0513b5": "Relaterade trådar", - "68060b380fe53942": "Körs på {label}. Anslut till den för att öppna tråden där.", "9996d9dac573001a": "Öppna på {label}", "15a601a94893277f": "Kunde inte öppna den överordnade tråden", "5eb43f554a5b7a58": "Den överordnade tråden togs bort", @@ -5688,7 +5718,6 @@ "4333d220c55ba5e4": "Frågan mot arbetsytan misslyckades.", "422c1671dfcfe474": "''{path}'' finns inte.", "20194b81e50497ad": "Det gick inte att läsa in mappen.", - "745a0b899008618c": "Kunde inte läsa in tidigare omgångar. Försök igen.", "0061fff77e36bd4f": "Kunde inte nå servern.", "04dfdd46e3dd4a2e": "Något gick fel. Försök igen.", "084bb2d8127a508d": "Skickat", @@ -5778,19 +5807,17 @@ "56ca98b79cc9ce49": "Aktivitet ({count})", "ddc5e5413923c471": "Du kan inte kommentera här.", "516def6f5a881e00": "Stänger det här ärendet", - "0014ce0aaf1bd68a": "Skrivskyddad", "fd93f4720ff70aaf": "Inga", "b6a29fff7c7c0808": "Ingen", "54420465784bb1bd": "Läs in äldre kommentarer", "9d82ebf35bfb4043": "Inget har hänt här än.", - "1cf216566c1ee064": "Projektet är inte tillgängligt", "b5ddadeb0810688c": "Status", "93c1fc19d9bf1db0": "Inblandning", "d5a8b335d88b65bc": "{hidden} dolda", "2160067266a61dd8": "Alla", "cd4ec4acf33c65b9": "{count, plural, one {{count} etikett} other {{count} etiketter}}", "bfd20acb8b7dee6b": "Vem som helst", - "ad208e3e32c85029": "Dölj alla", + "aead644e2cf1233f": "Visa alla", "77ce79d865716719": "Inga matchande projekt.", "af7eb4f9c7f0f575": "Filter", "08247dd39b0c85ff": "Tilldelad", @@ -6471,7 +6498,6 @@ "64d0189be492147c": "Det gick inte att öppna kontrolldetaljer", "600347ca50400a54": "Läser in kontroller…", "1b381201aba745c2": "Inga kontroller rapporterade", - "aead644e2cf1233f": "Visa alla", "a6d75a4380173c60": "Öppna kontroller: {summary}", "be3d1766bad18693": "Kontroller: {summary}", "425e4a3d6c5c2867": "{count, plural, one {{count} misslyckades} other {{count} misslyckades}}", @@ -9754,6 +9780,7 @@ "51497bd401292062": "Håll ned", "9d6cc6ac23312071": "Dubbeltryck", "f001fa7b329c8fbf": "Dölj lyckade", + "ad208e3e32c85029": "Dölj alla", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Endast status", "cf0f7fc3df26fa75": "Status och meddelanden", @@ -9963,6 +9990,7 @@ "573ea5fdf293a9d6": "Alla utcheckningar", "470ad8c54049d1e1": "Sök utcheckningar", "7e2dfdd9f97fc027": "Projektomfång", + "1cf216566c1ee064": "Projektet är inte tillgängligt", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 366a21392f806..b933baac631c6 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -94,6 +94,19 @@ "21be308917bd450e": "无法关联:{failure}", "acd01e781e2355cc": "请求已结束", "97e4c50a99272f63": "无法回复此请求。请重试。", + "605a491783d18b3f": "无法通过 {via} 读取此会话", + "50f19209548b70d9": "{via} 可能需要更新后才能读取关联的会话。", + "3d624e57d675358c": "{via} 上的关联环境已关闭", + "01b2231effdb835f": "在 {via} 的设置 → Labs 中开启,即可读取其关联机器上的会话。", + "e767e8901a0a3f35": "{via} 已不再关联 {label}", + "df3cd6ccd77084b4": "在 {via} 的设置 → 连接中重新关联,即可从这里读取其会话。", + "3920637506407ca0": "{via} 到 {label} 的关联已过期", + "80fec3c2b4fba678": "在 {via} 的设置 → 连接中使用新的配对码重新关联。", + "fec50d228dc9aa9b": "{label} 拒绝了读取", + "cd63d78559603b12": "此会话已不在 {label} 上", + "bd29efc163476e72": "它可能已在那里被删除。", + "f7870ef3a4828ab1": "{label} 需要更新", + "eabbf064657519ee": "{label} 没有响应 {via}", "f71597ae3afaef44": "{first} 和 {second}", "4047174839a16714": "{first} 和 {last}", "65ca7867c176afbf": "{first}、{rest}", @@ -2347,6 +2360,7 @@ "ac0de2a59d9c8860": "设备", "1354df9fb7278843": "查看 iOS 模拟器或 Android 模拟器。", "fdcd9643e2e63b15": "在会话继续运行的同时追问一个旁支问题。", + "1944f04b75ddf26d": "{label} 上的会话", "314cfeebf191ba0d": "待批准", "4e5b7363441a3831": "待输入", "97af4e74a5f95e5e": "运行中", @@ -3608,6 +3622,22 @@ "。智能体可以直接使用该关联;请在“设置 → 环境”中更改其访问权限。" ], "000b0df227182d39": "其他地址…", + "6bb5b1b35b2796ae": "位于 {label},经由 {via} · 运行中", + "a73b7ab25d6e9bdf": "位于 {label},经由 {via}", + "009e2ca841fdc1ef": "此环境", + "8cb2e5692c4f05ab": "在 {label} 上打开此会话即可查看此可视内容。", + "745a0b899008618c": "无法加载更早的对话。请重试。", + "0014ce0aaf1bd68a": "只读", + "d0bda35aeec66684": [ + "正在从 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 读取…" + ], + "c3e8cd9bf44e2f43": "正在显示之前读取的内容。", "eb6e0584cf4a2a1d": "语言:{language}", "d76c606a3c519b78": "取消自动换行", "2b683498cee8c8a7": "自动换行", @@ -3635,6 +3665,7 @@ "6d329f7d3a50c7e7": "复制表格", "6c71d251d9917587": "复制为 Markdown", "d510b122f84051a0": "复制为 CSV", + "2912e4ac3697686b": "读取 {label} 上的会话", "ced684880c2e1961": "允许 {server} 运行 {tool} 吗?", "b66fa23b5647b62d": "要发送这条来自 {server} 的消息吗?", "bae7f74153fa8a05": "要保存来自 {server} 的 {names} 吗?", @@ -4167,7 +4198,6 @@ "309b160785f6c473": "在此对话中打开分叉", "6676cd4b8299663f": "在此对话中打开父会话", "63e8c7a0ef0513b5": "相关会话", - "68060b380fe53942": "运行于 {label}。连接到它以在那里打开会话。", "9996d9dac573001a": "在 {label} 上打开", "15a601a94893277f": "无法打开父会话", "5eb43f554a5b7a58": "父会话已被删除", @@ -5694,7 +5724,6 @@ "4333d220c55ba5e4": "工作区查询失败。", "422c1671dfcfe474": "''{path}'' 不存在。", "20194b81e50497ad": "无法加载文件夹。", - "745a0b899008618c": "无法加载更早的对话。请重试。", "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", @@ -5784,19 +5813,17 @@ "56ca98b79cc9ce49": "活动({count})", "ddc5e5413923c471": "你无法在此评论。", "516def6f5a881e00": "将关闭此 issue", - "0014ce0aaf1bd68a": "只读", "fd93f4720ff70aaf": "无", "b6a29fff7c7c0808": "无", "54420465784bb1bd": "加载较早的评论", "9d82ebf35bfb4043": "这里还没有任何动态。", - "1cf216566c1ee064": "不可用的项目", "b5ddadeb0810688c": "状态", "93c1fc19d9bf1db0": "参与方式", "d5a8b335d88b65bc": "已隐藏 {hidden} 个", "2160067266a61dd8": "任意", "cd4ec4acf33c65b9": "{count, plural, other {{count} 个标签}}", "bfd20acb8b7dee6b": "任何人", - "ad208e3e32c85029": "全部隐藏", + "aead644e2cf1233f": "全部显示", "77ce79d865716719": "没有匹配的项目。", "af7eb4f9c7f0f575": "筛选条件", "08247dd39b0c85ff": "受理人", @@ -6477,7 +6504,6 @@ "64d0189be492147c": "无法打开检查详情", "600347ca50400a54": "正在加载检查…", "1b381201aba745c2": "未报告任何检查", - "aead644e2cf1233f": "全部显示", "a6d75a4380173c60": "打开检查:{summary}", "be3d1766bad18693": "检查:{summary}", "425e4a3d6c5c2867": "{count, plural, other {{count} 个失败}}", @@ -9761,6 +9787,7 @@ "51497bd401292062": "长按", "9d6cc6ac23312071": "连按两次", "f001fa7b329c8fbf": "隐藏成功的调用", + "ad208e3e32c85029": "全部隐藏", "c80e4bb3201efd71": "专注模式", "0cb9ffcd1fb46b0c": "仅状态", "cf0f7fc3df26fa75": "状态和消息", @@ -9970,6 +9997,7 @@ "573ea5fdf293a9d6": "所有工作副本", "470ad8c54049d1e1": "搜索工作副本", "7e2dfdd9f97fc027": "项目范围", + "1cf216566c1ee064": "不可用的项目", "c1b8c351aa90f319": [ { "t": "span", diff --git a/apps/web/src/linkedThreadSurface.ts b/apps/web/src/linkedThreadSurface.ts new file mode 100644 index 0000000000000..344efffe8d472 --- /dev/null +++ b/apps/web/src/linkedThreadSurface.ts @@ -0,0 +1,55 @@ +import type { LinkedThreadTarget } from "@t3tools/client-runtime/linked-thread"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; + +/** A linked environment's thread as a right panel tab, read through `viaEnvironmentId`. */ +export type LinkedThreadSurface = { + id: `linked-thread:${string}`; + kind: "linked-thread"; +} & LinkedThreadTarget; + +/** One tab per thread and the environment it is read through, so opening it again focuses it. */ +export function linkedThreadSurface(target: LinkedThreadTarget): LinkedThreadSurface { + return { + id: `linked-thread:${encodeURIComponent(target.viaEnvironmentId)}:${encodeURIComponent(target.environmentId)}:${encodeURIComponent(target.threadId)}`, + kind: "linked-thread", + viaEnvironmentId: target.viaEnvironmentId, + environmentId: target.environmentId, + threadId: target.threadId, + label: target.label, + title: target.title, + }; +} + +/** A saved linked-thread surface with its id rebuilt, or null when its fields are not usable. */ +export function decodeLinkedThreadSurface(surface: object): LinkedThreadSurface | null { + const { viaEnvironmentId, environmentId, threadId, label, title } = surface as Record< + string, + unknown + >; + if ( + typeof viaEnvironmentId !== "string" || + typeof environmentId !== "string" || + typeof threadId !== "string" || + typeof label !== "string" || + viaEnvironmentId === "" || + environmentId === "" || + threadId === "" + ) { + return null; + } + return linkedThreadSurface({ + viaEnvironmentId: EnvironmentId.make(viaEnvironmentId), + environmentId: EnvironmentId.make(environmentId), + threadId: ThreadId.make(threadId), + label, + title: typeof title === "string" && title !== "" ? title : null, + }); +} + +/** A tab's title: the thread's own once known, else where the thread is. */ +export function linkedThreadTitle( + surface: Pick, + fallback: string, +): string { + return surface.title?.trim() || fallback; +} diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index 2a4d8a3199f21..f226b5f1efd1e 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -164,6 +164,9 @@ export async function reopenClosedView( case "side-chat": panels.openSideChat(ref, surface.threadId); break; + case "linked-thread": + panels.openLinkedThread(ref, surface); + break; default: panels.open(ref, surface.kind); } diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index 3a6bd304863b0..39ac8336ce38c 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -1,8 +1,9 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { type EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; import { beforeEach, describe, expect, it } from "vite-plus/test"; import { useClosedViewStore } from "./closedViewStore"; +import { linkedThreadTitle } from "./linkedThreadSurface"; import { reopenClosedView } from "./reopenClosedView"; import { hostRightPanel, @@ -517,6 +518,83 @@ describe("rightPanelStore", () => { expect(selectThreadRightPanelState(migrated.byThreadKey, refA).maximized).toBe(true); }); + it("opens a linked thread once per thread and environment it is read through", () => { + const store = useRightPanelStore.getState(); + const target = { + viaEnvironmentId: EnvironmentId.make("env-1"), + environmentId: EnvironmentId.make("env:b"), + threadId: ThreadId.make("there"), + label: "fs-17", + title: null, + }; + store.openLinkedThread(refA, target); + store.open(refA, "diff"); + store.openLinkedThread(refA, { ...target, label: "renamed", title: "Fix the build" }); + store.openLinkedThread(refA, { ...target, title: null }); + store.openLinkedThread(refA, { ...target, viaEnvironmentId: EnvironmentId.make("env-2") }); + const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); + expect(panel.surfaces.map((surface) => surface.id)).toEqual([ + "linked-thread:env-1:env%3Ab:there", + "diff", + "linked-thread:env-2:env%3Ab:there", + ]); + // A click that knows no title keeps the one an earlier click or read gave. + expect(panel.surfaces[0]).toMatchObject({ label: "fs-17", title: "Fix the build" }); + store.setLinkedThreadTitle(refA, "linked-thread:env-1:env%3Ab:there", "Fix flaky test"); + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces[0], + ).toMatchObject({ title: "Fix flaky test" }); + // The tab is named for the thread once its title is known, else for where it is. + expect(linkedThreadTitle({ title: "Fix flaky test" }, "Thread on fs-17")).toBe( + "Fix flaky test", + ); + expect(linkedThreadTitle({ title: " " }, "Thread on fs-17")).toBe("Thread on fs-17"); + expect(linkedThreadTitle({ title: null }, "Thread on fs-17")).toBe("Thread on fs-17"); + }); + + it("keeps saved linked threads it can show and drops surfaces it cannot", () => { + const linked = { + id: "linked-thread:stale-id", + kind: "linked-thread", + viaEnvironmentId: "env-1", + environmentId: "env-b", + threadId: "there", + label: "fs-17", + }; + const migrated = migratePersistedRightPanelState({ + byThreadKey: { + "env-1:thread-A": { + isOpen: true, + activeSurfaceId: "linked-thread:stale-id", + surfaces: [ + linked, + { ...linked, id: "linked-thread:no-thread", threadId: undefined }, + { id: "hologram:1", kind: "hologram" }, + null, + { id: "diff", kind: "diff" }, + ], + }, + }, + }); + expect(selectThreadRightPanelState(migrated.byThreadKey, refA)).toEqual({ + isOpen: true, + // The saved id no longer names a surface, so the first one left is shown. + activeSurfaceId: "linked-thread:env-1:env-b:there", + surfaces: [ + { + id: "linked-thread:env-1:env-b:there", + kind: "linked-thread", + viaEnvironmentId: "env-1", + environmentId: "env-b", + threadId: "there", + label: "fs-17", + title: null, + }, + { id: "diff", kind: "diff" }, + ], + }); + }); + it("drops the legacy singleton terminal surface during migration", () => { expect( migratePersistedRightPanelState({ diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index da7ca64e01ce6..6b932ed4a46cf 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -11,6 +11,12 @@ import { createJSONStorage, persist } from "zustand/middleware"; import { useClosedViewStore } from "./closedViewStore"; import { m } from "./i18n/messages"; import { resolveStorage } from "./lib/storage"; +import type { LinkedThreadTarget } from "@t3tools/client-runtime/linked-thread"; +import { + decodeLinkedThreadSurface, + linkedThreadSurface, + type LinkedThreadSurface, +} from "./linkedThreadSurface"; import type { ThreadPanelPresentation } from "./rightPanelLayout"; import type { ChatFileAttachment } from "./types"; @@ -25,6 +31,7 @@ const RIGHT_PANEL_KINDS = [ "pull-requests", "issue", "side-chat", + "linked-thread", ] as const; export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number]; @@ -96,7 +103,9 @@ export type RightPanelSurface = key: string; url?: string; } - | { id: `side-chat:${string}`; kind: "side-chat"; threadId: ThreadId }; + | { id: `side-chat:${string}`; kind: "side-chat"; threadId: ThreadId } + /** A linked environment's thread, read through `viaEnvironmentId`; it has no thread here. */ + | LinkedThreadSurface; const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2"; const RIGHT_PANEL_STORAGE_VERSION = 15; @@ -154,9 +163,15 @@ interface RightPanelStoreState { ) => boolean; open: ( ref: ScopedThreadRef, - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "terminal" | "pull-request" | "issue" | "side-chat" | "linked-thread" + >, ) => void; openSideChat: (ref: ScopedThreadRef, threadId: ThreadId) => void; + openLinkedThread: (ref: ScopedThreadRef, target: LinkedThreadTarget) => void; + /** Records the title the linked environment gave, so the tab and a reopened one show it. */ + setLinkedThreadTitle: (ref: ScopedThreadRef, surfaceId: string, title: string) => void; openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void; renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void; openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void; @@ -221,7 +236,10 @@ interface RightPanelStoreState { toggleVisibility: (ref: ScopedThreadRef) => void; toggle: ( ref: ScopedThreadRef, - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "terminal" | "pull-request" | "issue" | "side-chat" | "linked-thread" + >, ) => void; setThreadPanelOpen: ( ref: ScopedThreadRef, @@ -246,7 +264,7 @@ const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { const singletonSurface = ( kind: Exclude< RightPanelKind, - "file" | "preview" | "terminal" | "pull-request" | "issue" | "side-chat" + "file" | "preview" | "terminal" | "pull-request" | "issue" | "side-chat" | "linked-thread" >, ): RightPanelSurface => { switch (kind) { @@ -567,8 +585,14 @@ export function migratePersistedRightPanelState(persistedState: unknown): { threadState && typeof threadState === "object" ? threadState : null; const surfaces = Array.isArray(validThreadState?.surfaces) ? validThreadState.surfaces.flatMap((surface) => { + if (!surface || typeof surface !== "object") return []; const kind = (surface as { kind?: string }).kind; - if (kind === "plan" || kind === "agents") return []; + // Also drops kinds this build does not know, such as one a newer build saved. + if (!(RIGHT_PANEL_KINDS as ReadonlyArray).includes(kind)) return []; + if (surface.kind === "linked-thread") { + const decoded = decodeLinkedThreadSurface(surface); + return decoded === null ? [] : [decoded]; + } if ( (surface.kind === "file" || surface.kind === "files") && "folderTrail" in surface && @@ -822,6 +846,38 @@ export const useRightPanelStore = create()( upsertSurface(current, { id: `side-chat:${threadId}`, kind: "side-chat", threadId }), ), ), + openLinkedThread: (ref, target) => + set((state) => + userAction(state, scopedThreadKey(ref), (current) => { + const surface = linkedThreadSurface(target); + const next = upsertSurface(current, surface); + return { + ...next, + // A later click may know the title or label an earlier one did not. + surfaces: next.surfaces.map((entry) => + entry.id === surface.id && entry.kind === "linked-thread" + ? { ...surface, title: surface.title ?? entry.title } + : entry, + ), + }; + }), + ), + setLinkedThreadTitle: (ref, surfaceId, title) => + set((state) => { + const threadKey = scopedThreadKey(rightPanelHostRef(ref)); + const existing = state.byThreadKey[threadKey]?.surfaces.find( + (surface) => surface.id === surfaceId, + ); + if (existing?.kind !== "linked-thread" || existing.title === title) return state; + return automaticUpdate(state, threadKey, (current) => ({ + ...current, + surfaces: current.surfaces.map((surface) => + surface.id === surfaceId && surface.kind === "linked-thread" + ? { ...surface, title } + : surface, + ), + })); + }), renameDevice: (ref, surfaceId, title) => set((state) => userAction(state, scopedThreadKey(ref), (current) => ({ diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts new file mode 100644 index 0000000000000..63145c73119d6 --- /dev/null +++ b/apps/web/src/state/linkedThreadView.ts @@ -0,0 +1,139 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + type LinkedThreadOpen, + resolveLinkedThreadOpen, +} from "@t3tools/client-runtime/linked-thread"; +import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import type { TurnItemSource } from "../components/chat/timelineRowContext"; +import { useRightPanelStore } from "../rightPanelStore"; +import type { LinkedThreadSurface } from "../linkedThreadSurface"; +import { buildThreadRouteParams } from "../threadRoutes"; +import { useEnvironment } from "./environments"; +import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks"; +import { useEnvironmentQuery } from "./query"; + +/** + * How a click opens a thread that the thread `panelRef` says is on a linked environment: in place + * when this client is connected there itself, else as a read-only tab in that thread's right + * panel, read through its environment. Once the link is gone a saved environment opens in place, + * where the client can reconnect to it; with neither, the tab says what to link again. + */ +export function useLinkedThreadOpener( + panelRef: ScopedThreadRef, + thread: + | { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly label: string; + } + | undefined, + title: string | null, +): { readonly mode: Exclude; readonly open: () => void } | null { + const navigate = useNavigate(); + const viaEnvironmentId = panelRef.environmentId; + const own = useEnvironment(thread?.environmentId ?? null); + const connected = own?.connection.phase === "connected"; + const links = useLinkedEnvironments(thread === undefined || connected ? null : viaEnvironmentId); + if (thread === undefined) return null; + const resolved = resolveLinkedThreadOpen({ + environmentId: thread.environmentId, + viaEnvironmentId, + own: own === null ? undefined : { connected }, + linked: links.has(thread.environmentId), + }); + const mode = resolved === "direct" ? "direct" : "linked"; + return { + mode, + open: () => { + if (mode === "linked") { + useRightPanelStore.getState().openLinkedThread(panelRef, { + viaEnvironmentId, + environmentId: thread.environmentId, + threadId: thread.threadId, + label: own?.label ?? thread.label, + title, + }); + return; + } + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.threadId)), + }); + }, + }; +} + +type TabKey = readonly [ + panelEnvironmentId: EnvironmentId, + panelThreadId: ThreadId, + surfaceId: string, + viaEnvironmentId: EnvironmentId, + environmentId: EnvironmentId, + threadId: ThreadId, +]; + +const targetOf = ( + surface: Pick, +) => ({ + environmentId: surface.viaEnvironmentId, + input: { environmentId: surface.environmentId, threadId: surface.threadId }, +}); + +/** One tab's subscription, which also keeps the tab's title to the thread's own. */ +const tabViewAtom = Atom.family((key: string) => { + const [panelEnvironmentId, panelThreadId, surfaceId, viaEnvironmentId, environmentId, threadId] = + JSON.parse(key) as TabKey; + const panelRef = scopeThreadRef(panelEnvironmentId, panelThreadId); + const view = peerLinkEnvironment.threadView( + targetOf({ viaEnvironmentId, environmentId, threadId }), + ); + return Atom.make((get) => { + const live = get(view); + const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; + if (title) useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + return live; + }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); +}); + +/** + * The thread of `surface`, streamed through the environment that links to it for the tab in + * `panelRef`'s panel. The stream runs only while `visible`; what it last showed stays. + */ +export function useLinkedThreadView( + panelRef: ScopedThreadRef, + surface: Pick, + visible: boolean, +) { + const key: TabKey = [ + panelRef.environmentId, + panelRef.threadId, + surface.id, + surface.viaEnvironmentId, + surface.environmentId, + surface.threadId, + ]; + const live = useEnvironmentQuery(visible ? tabViewAtom(JSON.stringify(key)) : null); + const view = useAtomValue(peerLinkEnvironment.lastThreadView(targetOf(surface))); + return { + view, + /** Why the stream is not running: it ended, or it waits to ask again. */ + error: live.failure ?? view?.error ?? null, + /** Asks again now. */ + retry: live.refresh, + }; +} + +/** Where a linked thread's expanded rows read an item in full: through the linking environment. */ +export const linkedThreadItemSource = ( + target: Pick, +): TurnItemSource => ({ + detail: (input) => + peerLinkEnvironment.threadItem({ + environmentId: target.viaEnvironmentId, + input: { environmentId: target.environmentId, ...input }, + }), +}); diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts index b19276c6f88b5..624da1618672a 100644 --- a/apps/web/src/state/peerLinks.ts +++ b/apps/web/src/state/peerLinks.ts @@ -30,8 +30,7 @@ const offersNoLinksAtom = Atom.make(false).pipe(Atom.withLabel("peer-links:offer /** * The machines `environmentId` links to, by name, while it offers links, and none otherwise. - * Its agents can read threads there. Listing asks each linked machine whether it answers, so - * every caller shares one briefly cached list. + * Its agents can read threads there, and so can a client allowed to read threads on it. */ export function useLinkedEnvironments( environmentId: EnvironmentId | null, @@ -42,7 +41,7 @@ export function useLinkedEnvironments( const identities = useEnvironmentIdentities(); const links = useEnvironmentQuery( offered && environmentId !== null - ? peerLinkEnvironment.list({ environmentId, input: {} }) + ? peerLinkEnvironment.names({ environmentId, input: {} }) : null, ); return linkedEnvironmentNames({ diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index fac296343d37f..9d0ebabb48158 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -77,7 +77,9 @@ The result is an ordinary session with subject `mcp-client`. A read-only grant holds `orchestration:read` alone. On `/mcp` it passes only tools declared as reads in [McpToolAccess](../../apps/server/src/mcp/McpToolAccess.ts), where every tool must declare who may call it to compile. Any other grant adds -`orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions. Every other HTTP and WebSocket +`orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions, and for a +[peer link](remote.md#peer-links)'s session alone the thread routes in +[linkThreadHttp](../../apps/server/src/peer/linkThreadHttp.ts), which only read. Every other HTTP and WebSocket path rejects that subject, because the RPC surface would let the agent act above its ceiling. Inside MCP the credential sets the limits and tool parameters only pick targets; see diff --git a/docs/internals/remote.md b/docs/internals/remote.md index 5bb875f137eef..c4d52681cb606 100644 --- a/docs/internals/remote.md +++ b/docs/internals/remote.md @@ -115,6 +115,18 @@ Unlinking on the linking side only forgets the token. receiving `/mcp` sends nothing while a wait is open and T3 Connect's edge drops idle requests after about 100 s. +**A client reads a linked thread as the thread's own stream.** A client connected +only to the linking environment subscribes to `peerLinks.subscribeThread`; +[`PeerThreadRelay`](../../apps/server/src/peer/PeerThreadRelay.ts) opens the +receiving environment's +[link thread routes](../../apps/server/src/peer/linkThreadHttp.ts) with the +link's token and passes on the same stream items, history pages and item detail +the owner's client gets. Clients reduce and draw it like any thread, read-only, +so there is no second transcript format to keep in step. The relay holds one +upstream per subscription and nothing once the client stops listening. The +routes accept only a peer link's session, refuse browser origins as `/mcp` does, +and serve any access level, since each already reads threads through `/mcp`. + **Work a link paired below full access starts stays within that link.** The receiving environment knows a session is a peer link because the linking side registers its OAuth client with the `t3code-peer-link` software id, and the diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 80fc00427c5de..1f6e221b3ebe5 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -477,6 +477,25 @@ ends, as for any delegated task. It keeps following the task across restarts. If the other machine revokes the link, or the link is removed here, the task fails with that reason. +### Read a linked machine's threads + +You can read a thread on a linked machine without connecting this app to it. Open +a task that was delegated there from the thread's agents, or a thread link that +points there, and the thread opens read-only, streamed through the machine you +are connected to over its link. It follows the thread live. On web and desktop +it opens as a tab in the right panel, beside the thread you are in, and shows +the same timeline as any other thread. + +- The view is marked **Read-only** with both machines' names. To reply, approve + or stop the thread, connect this app to that machine. +- Files, images and published visuals stay on that machine and do not load + here. A command's output shows as of when you open its row. +- If this app is already connected to that machine, the thread opens there as + usual instead. +- You need permission to read threads on the machine you are connected to, and + Linked environments must be on there. Both machines need a version of T3 Code + that has this view. + ## Manage or revoke access On the host, **Settings → Sharing & access** lets authorized administrators create diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 182c28a319120..0663ee293e2e8 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -111,6 +111,10 @@ "types": "./src/linkRequest.ts", "default": "./src/linkRequest.ts" }, + "./linked-thread": { + "types": "./src/linkedThread.ts", + "default": "./src/linkedThread.ts" + }, "./scheduled-task-webhook": { "types": "./src/scheduledTaskWebhook.ts", "default": "./src/scheduledTaskWebhook.ts" @@ -263,6 +267,10 @@ "types": "./src/state/orchestration.ts", "default": "./src/state/orchestration.ts" }, + "./state/thread-stream": { + "types": "./src/state/threadStream.ts", + "default": "./src/state/threadStream.ts" + }, "./state/thread-history-merge": { "types": "./src/state/threadHistoryMerge.ts", "default": "./src/state/threadHistoryMerge.ts" diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts index 6eef6f48679ec..70d33176a6873 100644 --- a/packages/client-runtime/src/linkRequest.test.ts +++ b/packages/client-runtime/src/linkRequest.test.ts @@ -339,16 +339,15 @@ describe("linkableMachines", () => { }); describe("linkedEnvironmentNames", () => { - it("names the unexpired links as this client does, else as the link does", () => { + it("names the links as this client does, else as the link does", () => { const vps = EnvironmentId.make("environment-vps"); const mini = EnvironmentId.make("environment-mini"); const unsaved = EnvironmentId.make("environment-unsaved"); expect( linkedEnvironmentNames({ links: [ - { environmentId: vps, label: "vps-01", status: "unreachable" }, - { environmentId: mini, label: "mini", status: "expired" }, - { environmentId: unsaved, label: "Office box", status: "reachable" }, + { environmentId: vps, label: "vps-01" }, + { environmentId: unsaved, label: "Office box" }, ], environments: [ { environmentId: vps, label: "Hetzner VPS" }, diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts index 6b8322e0ebee8..93665fce42cbc 100644 --- a/packages/client-runtime/src/linkRequest.ts +++ b/packages/client-runtime/src/linkRequest.ts @@ -5,6 +5,7 @@ import { type EnvironmentMachineKind, type OrchestrationV2TurnItem, type PeerLinkRequestAnswerInput, + type PeerLinkName, type PeerLinkSummary, resolveEnvironmentMachineKind, type ServerConfig, @@ -27,11 +28,11 @@ export const offersLinkedEnvironments = ( config?.environment.capabilities.peerLinks === true && config.settings.linkedEnvironmentsEnabled; /** - * The machines an environment's agents can work on, by name: its links that have not - * expired, named as this client names them, else as the link does. + * The machines an environment's agents can work on, by name: its unexpired links (the server + * leaves out expired ones), named as this client names them, else as the link does. */ export function linkedEnvironmentNames(input: { - readonly links: ReadonlyArray>; + readonly links: ReadonlyArray; readonly environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string; @@ -41,10 +42,8 @@ export function linkedEnvironmentNames(input: { input.environments.map((environment) => [environment.environmentId, environment.label]), ); return new Map( - input.links.flatMap((link) => - link.status === "expired" - ? [] - : [[link.environmentId, names.get(link.environmentId) ?? link.label] as const], + input.links.map( + (link) => [link.environmentId, names.get(link.environmentId) ?? link.label] as const, ), ); } diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts new file mode 100644 index 0000000000000..694363d5c135a --- /dev/null +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -0,0 +1,160 @@ +import { + EventId, + type OrchestrationV2ThreadHistoryPage, + type OrchestrationV2ThreadStreamItem, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { TestClock } from "effect/testing"; + +import { + followLinkedThread, + keepLinkedThreadView, + LINKED_THREAD_RETRY_MS, + type LinkedThreadView, +} from "./linkedThread.ts"; +import { v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; + +const snapshot = ( + snapshotSequence: number, + historyCursor: string | null = null, +): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence, + projection: v2Projection, + historyCursor, + hasMoreHistory: historyCursor !== null, +}); + +const retitled = (sequence: number, title: string): OrchestrationV2ThreadStreamItem => ({ + kind: "event", + sequence, + event: { + id: EventId.make(`event:${sequence}`), + type: "thread.metadata-updated", + threadId: v2Projection.thread.id, + occurredAt: v2Now, + payload: { ...v2Projection.thread, title }, + }, +}); + +const failure = (reason: string) => ({ _tag: "PeerLinkThreadReadError", reason }); +const titleOf = (view: LinkedThreadView) => view.thread.projection?.thread.title ?? null; + +it.effect("keeps what it read while a linked environment is out of reach, and asks it again", () => + Effect.gen(function* () { + const attempts = [ + Stream.make(snapshot(1), retitled(2, "Renamed")).pipe( + Stream.concat(Stream.fail(failure("unreachable"))), + ), + Stream.make(snapshot(5)).pipe(Stream.concat(Stream.fail(failure("expired")))), + ]; + let opened = 0; + const views = yield* Queue.unbounded(); + const following = yield* followLinkedThread({ + items: Stream.suspend(() => attempts[opened++]!), + historyPage: () => Effect.die("unused"), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.flip, + Effect.forkChild, + ); + + expect(titleOf(yield* Queue.take(views))).toBe(v2Projection.thread.title); + expect(titleOf(yield* Queue.take(views))).toBe("Renamed"); + // Out of reach: the thread stays as read, with the reason beside it. + const waiting = yield* Queue.take(views); + expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]); + expect(opened).toBe(1); + + yield* TestClock.adjust(LINKED_THREAD_RETRY_MS); + // It answers again: its snapshot replaces the thread and clears the reason. + const back = yield* Queue.take(views); + expect([titleOf(back), back.error, back.thread.sequence]).toEqual([ + v2Projection.thread.title, + null, + 5, + ]); + // A link that expired cannot come back by waiting, so the stream ends with it. + expect(yield* Fiber.join(following)).toEqual(failure("expired")); + expect(opened).toBe(2); + }), +); + +it.effect("keeps the thread a view showed while its reopened stream has read nothing", () => + Effect.gen(function* () { + const attempts = [ + Stream.make(snapshot(1, "cursor-1"), retitled(2, "Renamed")), + // The view closed and opened again while the linked environment was out of reach. + Stream.fail(failure("unreachable")), + Stream.make(snapshot(5)).pipe(Stream.concat(Stream.never)), + ]; + let opened = 0; + const follow = () => + followLinkedThread({ + items: Stream.suspend(() => attempts[opened++]!), + historyPage: () => Effect.die("unused"), + }); + let kept: LinkedThreadView | null = null; + yield* follow().pipe( + Stream.runForEach((view) => Effect.sync(() => (kept = keepLinkedThreadView(kept, view)))), + ); + + const views = yield* Queue.unbounded(); + yield* follow().pipe( + Stream.runForEach((view) => Queue.offer(views, keepLinkedThreadView(kept, view))), + Effect.forkScoped, + ); + const waiting = yield* Queue.take(views); + expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]); + // Earlier turns belong to a stream that is gone, so none are offered until one is back. + expect(waiting.thread.historyCursor).toBeNull(); + + yield* TestClock.adjust(LINKED_THREAD_RETRY_MS); + const back = yield* Queue.take(views); + expect([titleOf(back), back.error, back.thread.sequence]).toEqual([ + v2Projection.thread.title, + null, + 5, + ]); + }).pipe(Effect.scoped), +); + +it.effect("loads the turns before a snapshot's window once per request", () => + Effect.gen(function* () { + const asked: string[] = []; + const page: OrchestrationV2ThreadHistoryPage = { + snapshotSequence: 1, + items: [], + nextCursor: null, + hasMoreHistory: false, + }; + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.make(snapshot(1, "cursor-1")).pipe(Stream.concat(Stream.never)), + historyPage: (cursor) => + Effect.sync(() => { + asked.push(cursor); + return page; + }), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + + const shown = yield* Queue.take(views); + expect(shown.thread.historyCursor).toBe("cursor-1"); + shown.loadEarlier(); + // A second tap while the page loads asks for nothing more. + shown.loadEarlier(); + expect((yield* Queue.take(views)).history).toEqual({ loading: true, failed: false }); + const loaded = yield* Queue.take(views); + expect([loaded.history.loading, loaded.thread.historyCursor]).toEqual([false, null]); + // Nothing is left to load. + loaded.loadEarlier(); + expect(asked).toEqual(["cursor-1"]); + }).pipe(Effect.scoped), +); diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts new file mode 100644 index 0000000000000..a5316a99008b7 --- /dev/null +++ b/packages/client-runtime/src/linkedThread.ts @@ -0,0 +1,275 @@ +import type { + EnvironmentId, + OrchestrationV2ThreadHistoryPage, + OrchestrationV2ThreadProjection, + OrchestrationV2ThreadStreamItem, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; + +import { + deriveRunlessWorkStartedAt, + deriveThreadStructureRuntime, +} from "./state/threadExecution.ts"; +import { + applyThreadHistoryPage, + applyThreadStreamItem, + initialThreadStreamState, + type ThreadStreamState, +} from "./state/threadStream.ts"; + +/** A thread on a linked environment, read through the environment that holds the link. */ +export interface LinkedThreadTarget { + /** The environment this client is connected to, which reads the thread over its link. */ + readonly viaEnvironmentId: EnvironmentId; + /** The linked environment the thread lives in. */ + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + /** What to call the linked environment and the thread until the first page names them. */ + readonly label: string; + readonly title: string | null; +} + +export type LinkedThreadOpen = "direct" | "linked" | "unavailable"; + +/** + * How a client opens a thread on `environmentId` that a thread or link in `viaEnvironmentId` + * points at. A connection of the client's own always wins, since it can do more than read. Without + * one, the environment holding the link reads it. A saved environment that neither answers nor is + * linked still opens directly, where the client says it is offline. + */ +export function resolveLinkedThreadOpen(input: { + readonly environmentId: EnvironmentId; + readonly viaEnvironmentId: EnvironmentId; + /** The client's own saved connection to `environmentId`, when it has one. */ + readonly own: { readonly connected: boolean } | undefined; + /** Whether `viaEnvironmentId` holds a link to `environmentId`. */ + readonly linked: boolean; +}): LinkedThreadOpen { + if (input.environmentId === input.viaEnvironmentId) return "direct"; + if (input.own?.connected === true) return "direct"; + if (input.linked) return "linked"; + return input.own === undefined ? "unavailable" : "direct"; +} + +const hasStringField = (value: unknown, key: K): value is Record => + typeof value === "object" && + value !== null && + typeof (value as Record)[key] === "string"; + +/** Whether a failed read can succeed later with nothing changed: the linked environment was only out of reach. */ +const isLinkedThreadUnreachable = (error: unknown): boolean => + hasStringField(error, "_tag") && + error._tag === "PeerLinkThreadReadError" && + hasStringField(error, "reason") && + error.reason === "unreachable"; + +export interface LinkedThreadFailure { + readonly title: string; + readonly detail: string; + /** Whether reading again can succeed without the user changing something first. */ + readonly retryable: boolean; +} + +/** + * A failed read in the user's words. `via` and `label` name the two environments as the client + * knows them; the server's own label wins once it has answered with one. + */ +export function linkedThreadFailure( + error: unknown, + names: { readonly via: string; readonly label: string }, + resolve: MFunctionType = mFallback, +): LinkedThreadFailure { + const via = names.via; + const serverMessage = hasStringField(error, "message") ? error.message : ""; + if (!hasStringField(error, "_tag") || error._tag !== "PeerLinkThreadReadError") { + // An environment from before this read answers with an unknown method. + return { + title: resolve(msg("Could not read this thread through {via}", { via })), + detail: + serverMessage || + resolve(msg("{via} may need an update before it can read linked threads.", { via })), + retryable: true, + }; + } + const retryable = isLinkedThreadUnreachable(error); + const label = hasStringField(error, "label") ? error.label : names.label; + const reason = hasStringField(error, "reason") ? error.reason : ""; + switch (reason) { + case "disabled": + return { + title: resolve(msg("Linked environments is off on {via}", { via })), + detail: resolve( + msg( + "Turn it on in {via}'s Settings → Labs to read threads on the machines it links to.", + { + via, + }, + ), + ), + retryable, + }; + case "unknown_link": + return { + title: resolve(msg("{via} is no longer linked to {label}", { via, label })), + detail: resolve( + msg("Link it again in {via}'s Settings → Connections to read its threads from here.", { + via, + }), + ), + retryable, + }; + case "expired": + return { + title: resolve(msg("The link from {via} to {label} expired", { via, label })), + detail: resolve( + msg("Link it again in {via}'s Settings → Connections with a new pairing code.", { via }), + ), + retryable, + }; + case "rejected": + return { + title: resolve(msg("{label} refused the read", { label })), + detail: serverMessage, + retryable, + }; + case "thread_not_found": + return { + title: resolve(msg("This thread is no longer on {label}", { label })), + detail: resolve(msg("It may have been deleted there.")), + retryable, + }; + case "incompatible": + return { + title: resolve(msg("{label} needs an update", { label })), + detail: serverMessage, + retryable, + }; + default: + return { + title: resolve(msg("{label} is not answering {via}", { label, via })), + detail: serverMessage, + retryable, + }; + } +} + +const WORKING_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]); + +/** Whether the thread has work under way, for the note that stands where its composer would. */ +export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjection): boolean { + return ( + WORKING_STATUSES.has(deriveThreadStructureRuntime(projection)?.status ?? "") || + deriveRunlessWorkStartedAt(projection) !== null + ); +} + +/** How long a view waits before asking again for a thread whose environment did not answer. */ +export const LINKED_THREAD_RETRY_MS = 15_000; + +/** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */ +export interface LinkedThreadView { + readonly thread: ThreadStreamState; + /** Why the stream stopped, while the view waits to ask again; the next item clears it. */ + readonly error: unknown; + readonly history: { readonly loading: boolean; readonly failed: boolean }; + /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */ + readonly loadEarlier: () => void; +} + +/** + * What a view keeps once its stream shows `next`. A stream that was opened again has read nothing + * until its snapshot arrives, so the thread read before stays, with the new stream's state beside + * it. Its earlier turns load again only once that stream has a thread of its own to add them to. + */ +export const keepLinkedThreadView = ( + kept: LinkedThreadView | null, + next: LinkedThreadView, +): LinkedThreadView => + next.thread.projection !== null || kept === null || kept.thread.projection === null + ? next + : { ...next, thread: { ...kept.thread, historyCursor: null } }; + +/** + * Follows a linked environment's thread for as long as something consumes the result. The thread + * is built from the same stream items and with the same reducer as a guest page's, and older + * turns load through the same cursor. A linked environment that stops answering is asked again + * after a wait, with what was read kept; any other failure ends the stream. + */ +export const followLinkedThread = (source: { + readonly items: Stream.Stream; + readonly historyPage: (cursor: string) => Effect.Effect; +}): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + const requests = yield* Queue.unbounded(); + let requested = false; + // Both halves below run one step at a time, so each reads the view the other left. + let view: LinkedThreadView = { + thread: initialThreadStreamState, + error: null, + history: { loading: false, failed: false }, + loadEarlier: () => { + if (requested || view.thread.historyCursor === null) return; + requested = true; + Queue.offerUnsafe(requests, undefined); + }, + }; + const show = (patch: Partial) => { + view = { ...view, ...patch }; + return view; + }; + const attempt = (): Stream.Stream => + source.items.pipe( + Stream.map((item) => + show({ thread: applyThreadStreamItem(view.thread, item), error: null }), + ), + Stream.catch((error) => + isLinkedThreadUnreachable(error) + ? Stream.make(show({ error })).pipe( + Stream.concat( + Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))), + ), + ) + : Stream.fail(error), + ), + ); + const earlier = Stream.fromQueue(requests).pipe( + Stream.flatMap(() => + Stream.suspend(() => { + const cursor = view.thread.historyCursor; + if (cursor === null) { + requested = false; + return Stream.empty; + } + return Stream.make(show({ history: { loading: true, failed: false } })).pipe( + Stream.concat( + Stream.fromEffect( + source.historyPage(cursor).pipe( + Effect.match({ + onSuccess: (page) => + show({ + thread: applyThreadHistoryPage(view.thread, cursor, page), + history: { loading: false, failed: false }, + }), + onFailure: () => show({ history: { loading: false, failed: true } }), + }), + Effect.ensuring( + Effect.sync(() => { + requested = false; + }), + ), + ), + ), + ), + ); + }), + ), + ); + return Stream.merge(attempt(), earlier, { haltStrategy: "left" }); + }), + ); diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 7c8f06cb1f083..11588aa329ee0 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -63,6 +63,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.providerInstallSubscribe | typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell | typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread + | typeof WS_METHODS.peerLinksSubscribeThread | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput | typeof ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion | typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 9b355e29085ed..fe6579d9d0c75 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -1,11 +1,38 @@ -import { type PeerLinkSummary, WS_METHODS } from "@t3tools/contracts"; +import { + type EnvironmentId, + type PeerLinkSummary, + type PeerLinkThreadInput, + WS_METHODS, +} from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; -import { Atom } from "effect/reactivity"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import type { EnvironmentRegistry } from "../connection/registry.ts"; -import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; +import { + followLinkedThread, + keepLinkedThreadView, + type LinkedThreadView, +} from "../linkedThread.ts"; +import { request, subscribe } from "../rpc/client.ts"; +import { + createEnvironmentRpcCommand, + createEnvironmentRpcQueryAtomFamily, + createEnvironmentSubscriptionAtomFamily, +} from "./runtime.ts"; + +/** The environment a client reads through, and the linked environment's thread it reads. */ +export interface LinkedThreadViewTarget { + readonly environmentId: EnvironmentId; + readonly input: PeerLinkThreadInput; +} + +const threadViewKey = ({ environmentId, input }: LinkedThreadViewTarget) => + JSON.stringify({ + environmentId, + input: { environmentId: input.environmentId, threadId: input.threadId }, + }); export function createPeerLinkEnvironmentAtoms( runtime: Atom.AtomRuntime, @@ -16,13 +43,59 @@ export function createPeerLinkEnvironmentAtoms( // Listing probes every linked environment, so a list stays fresh briefly. staleTimeMs: 10_000, }); + // Names only, for opening linked threads with thread read access; it probes nothing. + const names = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:peer-links:names", + tag: WS_METHODS.peerLinksNames, + staleTimeMs: 10_000, + }); + const refreshLinks = (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => + Effect.sync(() => { + registry.refresh(list({ environmentId, input: {} })); + registry.refresh(names({ environmentId, input: {} })); + }); + const threadStream = createEnvironmentSubscriptionAtomFamily(runtime, { + label: "environment-data:peer-links:thread-stream", + idleTtlMs: 0, + subscribe: (input: PeerLinkThreadInput) => + followLinkedThread({ + items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), + historyPage: (cursor) => + request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), + }), + }); + /** + * What a view of the thread last showed. It outlives the subscription for a while, so coming + * back to the view shows the thread at once while the stream starts again. + */ + const lastThreadView = Atom.family((key: string) => + Atom.make(null).pipe( + Atom.setIdleTTL(5 * 60_000), + Atom.withLabel(`environment-data:peer-links:last-thread-view:${key}`), + ), + ); + /** + * A linked environment's thread, streamed while a view reads it. The subscription ends with its + * last reader, which closes the stream at the linked environment too. + */ + const threadView = Atom.family((key: string) => { + const stream = threadStream(JSON.parse(key) as LinkedThreadViewTarget); + return Atom.make((get) => { + const live = get(stream); + if (AsyncResult.isSuccess(live)) { + const kept = lastThreadView(key); + get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); + } + return live; + }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); + }); return { list, + names, link: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:link", tag: WS_METHODS.peerLinksLink, - onSuccess: ({ environmentId }, registry) => - Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId), }), // Leaves the list alone: a batch refreshes it once, when it ends (`runLinkBatch`). linkInBatch: createEnvironmentRpcCommand(runtime, { @@ -32,8 +105,15 @@ export function createPeerLinkEnvironmentAtoms( unlink: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:unlink", tag: WS_METHODS.peerLinksUnlink, - onSuccess: ({ environmentId }, registry) => - Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId), + }), + threadView: (target: LinkedThreadViewTarget) => threadView(threadViewKey(target)), + lastThreadView: (target: LinkedThreadViewTarget) => lastThreadView(threadViewKey(target)), + /** One item of a linked environment's thread in full, for a row the reader opened. */ + threadItem: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:peer-links:thread-item", + tag: WS_METHODS.peerLinksThreadItem, + idleTtlMs: 0, }), // An agent's link card. One answer per card at a time. answerRequest: createEnvironmentRpcCommand(runtime, { @@ -44,8 +124,7 @@ export function createPeerLinkEnvironmentAtoms( key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId, input.turnItemId]), }, - onSuccess: ({ environmentId }, registry) => - Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId), }), }; } diff --git a/packages/client-runtime/src/state/threadStream.ts b/packages/client-runtime/src/state/threadStream.ts new file mode 100644 index 0000000000000..b723a99885aad --- /dev/null +++ b/packages/client-runtime/src/state/threadStream.ts @@ -0,0 +1,94 @@ +import type { + OrchestrationV2ThreadHistoryPage, + OrchestrationV2ThreadProjection, + OrchestrationV2ThreadStreamItem, +} from "@t3tools/contracts"; +import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; + +import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; +import { + mergeOlderHistoryIntoProjection, + mergeOlderSubagentsIntoProjection, +} from "./threadHistoryMerge.ts"; + +/** + * A thread built from its stream alone, for a view with no environment connection of its own to + * the thread: a guest page, or a linked environment's thread read through the link. + */ +export interface ThreadStreamState { + /** The thread as the owner's client holds it, built with the same reducer. */ + readonly projection: OrchestrationV2ThreadProjection | null; + readonly sequence: number; + /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */ + readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null; + /** Where "Load earlier turns" continues, or null once the whole thread is loaded. */ + readonly historyCursor: string | null; +} + +export const initialThreadStreamState: ThreadStreamState = { + projection: null, + sequence: 0, + partial: null, + historyCursor: null, +}; + +/** + * Applies the owner's thread stream the way the owner's client does (see EnvironmentThreadState): + * a snapshot replaces the thread, and later events pass through the same projection reducer, once + * each. + */ +export function applyThreadStreamItem( + state: ThreadStreamState, + item: OrchestrationV2ThreadStreamItem, +): ThreadStreamState { + if (item.kind === "snapshot") { + return { + projection: boundedSnapshotProjection(item), + sequence: item.snapshotSequence, + partial: + item.hasMoreHistory === true || (item.historyCursor ?? null) !== null + ? { latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null } + : null, + historyCursor: item.hasMoreHistory === true ? (item.historyCursor ?? null) : null, + }; + } + if (item.kind === "synchronized" || item.sequence <= state.sequence) return state; + if (item.kind === "unknown-event") return { ...state, sequence: item.sequence }; + const projection = + applyOrchestrationV2ProjectionEvent( + state.projection, + item.event, + state.partial === null ? undefined : { partialTimeline: true, ...state.partial }, + ) ?? state.projection; + const turnItem = item.event.type === "turn-item.updated" ? item.event.payload : null; + const watermark = state.partial?.latestLocalTurnOrdinal ?? null; + return { + ...state, + projection, + sequence: item.sequence, + partial: + state.partial !== null && + turnItem !== null && + (watermark === null || turnItem.ordinal > watermark) + ? { latestLocalTurnOrdinal: turnItem.ordinal } + : state.partial, + }; +} + +/** Merges a page of older turns, fetched from `cursor`, in front, as in the owner's view. */ +export function applyThreadHistoryPage( + state: ThreadStreamState, + cursor: string, + page: OrchestrationV2ThreadHistoryPage, +): ThreadStreamState { + // A snapshot since the request replaced the thread and its cursor. + if (state.projection === null || state.historyCursor !== cursor) return state; + return { + ...state, + projection: mergeOlderSubagentsIntoProjection( + mergeOlderHistoryIntoProjection(state.projection, page.items), + page.subagents, + ), + historyCursor: page.hasMoreHistory ? page.nextCursor : null, + }; +} diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index a7316a9f0482d..b1a4c9ea18fcd 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -188,6 +188,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ (`linkOrigin`). Another environment links to this one only when it is set, since without it that work could change the user's own threads. */ linkFence: Schema.optionalKey(Schema.Boolean), + /** Serves a thread's stream, history pages and item detail to a link's session + (`PEER_LINK_THREAD_STREAM_ROUTE`), so a client of the linking environment can read it. */ + linkThreadStream: Schema.optionalKey(Schema.Boolean), /** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */ mcpApprovalCodes: Schema.optionalKey(Schema.Boolean), peerLinkPairingCodes: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index 0d72b978e2609..bf25a34e07cf7 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -32,6 +32,16 @@ export const PeerLinkSummary = Schema.Struct({ }); export type PeerLinkSummary = typeof PeerLinkSummary.Type; +/** + * A link's name only, for a client that may read threads here but not manage access: enough to + * name and open a linked environment's threads, without its addresses, access or health. + */ +export const PeerLinkName = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, +}); +export type PeerLinkName = typeof PeerLinkName.Type; + export const PeerLinkCreateInput = Schema.Struct({ /** Where the peer answers: an https, Tailscale, LAN or loopback base URL. */ url: TrimmedNonEmptyString, @@ -89,6 +99,63 @@ export const peerLinkFailureKind = ( ? "code_refused" : "other"; +/** + * Where an environment serves one of its threads to an environment linked to it, signed in with + * the link's own session as on `/mcp`. The stream carries the same items the owner's thread + * subscription does; history pages and item detail are the owner's too. + */ +const PEER_LINK_THREAD_ROUTE_PREFIX = "/api/links/thread"; +export const PEER_LINK_THREAD_STREAM_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/stream`; +export const PEER_LINK_THREAD_HISTORY_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/history`; +export const PEER_LINK_THREAD_ITEM_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/item`; + +/** A thread on a linked environment, as a client of this environment names it. */ +export const PeerLinkThreadInput = Schema.Struct({ + /** The linked environment the thread lives in. */ + environmentId: EnvironmentId, + threadId: ThreadId, +}); +export type PeerLinkThreadInput = typeof PeerLinkThreadInput.Type; + +export const PeerLinkThreadHistoryInput = Schema.Struct({ + ...PeerLinkThreadInput.fields, + /** The `historyCursor` of the snapshot or of the page before. */ + cursor: TrimmedNonEmptyString, +}); +export type PeerLinkThreadHistoryInput = typeof PeerLinkThreadHistoryInput.Type; + +export const PeerLinkThreadItemInput = Schema.Struct({ + ...PeerLinkThreadInput.fields, + itemId: TurnItemId, + /** Unused by the server; a client keys its cache on it, as for its own threads' items. */ + revision: Schema.optional(Schema.String), +}); +export type PeerLinkThreadItemInput = typeof PeerLinkThreadItemInput.Type; + +/** Why a linked environment's thread could not be read, with the reason in words. */ +export class PeerLinkThreadReadError extends Schema.TaggedError()( + "PeerLinkThreadReadError", + { + reason: Schema.Literals([ + /** Linked environments is off here. */ + "disabled", + "unknown_link", + "expired", + /** The linked environment no longer accepts the link, or refuses the read. */ + "rejected", + "unreachable", + "thread_not_found", + /** The linked environment runs a version that does not serve its threads to a link. */ + "incompatible", + ]), + /** What this environment calls the linked one, when it still has the link. */ + label: Schema.NullOr(Schema.String), + message: Schema.String, + /** The failure underneath, when the read got as far as the link or the linked environment. */ + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + /** * The user's answer to an agent asking to link an environment. The pairing * code is used once to link and is never recorded; the thread learns only the diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 41733dae56417..371228eed134d 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -20,11 +20,16 @@ import { PeerLink, PeerLinkCreateInput, PeerLinkError, + PeerLinkName, PeerLinkRemoveInput, PeerLinkRemoveResult, PeerLinkRequestAnswerInput, PeerLinkRequestError, PeerLinkSummary, + PeerLinkThreadHistoryInput, + PeerLinkThreadInput, + PeerLinkThreadItemInput, + PeerLinkThreadReadError, } from "./peerLink.ts"; import { ChatGptReconnectProfileInput, @@ -260,6 +265,7 @@ import { OrchestrationV2CommandOutputError, OrchestrationV2GetThreadProjectionError, OrchestrationV2RpcSchemas, + OrchestrationV2ThreadHistoryPage, OrchestrationV2ThreadLaunchError, } from "./orchestrationV2.ts"; import { @@ -546,9 +552,13 @@ export const WS_METHODS = { serverGetDatabaseStorage: "server.getDatabaseStorage", serverReclaimDatabaseSpace: "server.reclaimDatabaseSpace", peerLinksList: "peerLinks.list", + peerLinksNames: "peerLinks.names", peerLinksLink: "peerLinks.link", peerLinksUnlink: "peerLinks.unlink", peerLinksAnswerRequest: "peerLinks.answerRequest", + peerLinksSubscribeThread: "peerLinks.subscribeThread", + peerLinksThreadHistoryPage: "peerLinks.threadHistoryPage", + peerLinksThreadItem: "peerLinks.threadItem", serverGetSettings: "server.getSettings", serverUpdateSettings: "server.updateSettings", serverDiscoverSourceControl: "server.discoverSourceControl", @@ -890,6 +900,13 @@ const WsPeerLinksListRpc = Rpc.make(WS_METHODS.peerLinksList, { error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), }); +/** The unexpired links' names, readable with thread read access. */ +const WsPeerLinksNamesRpc = Rpc.make(WS_METHODS.peerLinksNames, { + payload: Schema.Struct({}), + success: Schema.Struct({ links: Schema.Array(PeerLinkName) }), + error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), +}); + const WsPeerLinksLinkRpc = Rpc.make(WS_METHODS.peerLinksLink, { payload: PeerLinkCreateInput, success: PeerLink, @@ -902,6 +919,26 @@ const WsPeerLinksUnlinkRpc = Rpc.make(WS_METHODS.peerLinksUnlink, { error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), }); +/** A linked environment's thread, as its own thread subscription streams it. */ +const WsPeerLinksSubscribeThreadRpc = Rpc.make(WS_METHODS.peerLinksSubscribeThread, { + payload: PeerLinkThreadInput, + success: OrchestrationV2RpcSchemas.subscribeThread.output, + error: Schema.Union([PeerLinkThreadReadError, EnvironmentAuthorizationError]), + stream: true, +}); + +const WsPeerLinksThreadHistoryPageRpc = Rpc.make(WS_METHODS.peerLinksThreadHistoryPage, { + payload: PeerLinkThreadHistoryInput, + success: OrchestrationV2ThreadHistoryPage, + error: Schema.Union([PeerLinkThreadReadError, EnvironmentAuthorizationError]), +}); + +const WsPeerLinksThreadItemRpc = Rpc.make(WS_METHODS.peerLinksThreadItem, { + payload: PeerLinkThreadItemInput, + success: OrchestrationV2RpcSchemas.getTurnItem.output, + error: Schema.Union([PeerLinkThreadReadError, EnvironmentAuthorizationError]), +}); + const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, { payload: PeerLinkRequestAnswerInput, error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]), @@ -2302,9 +2339,13 @@ export const WsRpcGroup = RpcGroup.make( WsServerReclaimDatabaseSpaceRpc, WsServerUpdateSettingsRpc, WsPeerLinksListRpc, + WsPeerLinksNamesRpc, WsPeerLinksLinkRpc, WsPeerLinksUnlinkRpc, WsPeerLinksAnswerRequestRpc, + WsPeerLinksSubscribeThreadRpc, + WsPeerLinksThreadHistoryPageRpc, + WsPeerLinksThreadItemRpc, WsServerDiscoverSourceControlRpc, WsServerCheckSecretSourceRpc, WsServerSearchAcpRegistryRpc, diff --git a/packages/shared/src/threadLinksCopy.ts b/packages/shared/src/threadLinksCopy.ts index 3b7480992b7e4..e4e452a43ca2b 100644 --- a/packages/shared/src/threadLinksCopy.ts +++ b/packages/shared/src/threadLinksCopy.ts @@ -28,12 +28,12 @@ export function unknownThreadLinkLabel( export function relabelThreadLinks( markdown: string, messageEnvironmentId: EnvironmentId, - title: (ref: ScopedThreadRef) => string | undefined, + title: (ref: ScopedThreadRef, label: string | undefined) => string | undefined, resolve: MFunctionType = mFallback, ): string { return replaceThreadLinks(markdown, (written, label) => { for (const ref of threadLinkCandidates(written, messageEnvironmentId)) { - const current = title(ref); + const current = title(ref, label); if (current === undefined) continue; return formatThreadLink( { environmentId: written.environmentId, threadId: ref.threadId }, From d7f6b3efcac375160bbe20e28276be853eaf7315 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 12:15:36 -0800 Subject: [PATCH 4/7] feat: connect to a linked environment from its read-only thread (#39439) Co-authored-by: Claude Fable 5.2 --- apps/mobile/src/connection/onboarding.ts | 8 + .../connection/ConnectionsNewRouteScreen.tsx | 31 +- .../connection/linkedEnvironmentPrefill.ts | 12 + .../features/threads/LinkedThreadSheet.tsx | 66 ++++- apps/mobile/src/i18n/translations/de.json | 7 +- apps/mobile/src/i18n/translations/en.json | 7 +- apps/mobile/src/i18n/translations/es.json | 7 +- apps/mobile/src/i18n/translations/fr.json | 7 +- apps/mobile/src/i18n/translations/ja.json | 7 +- apps/mobile/src/i18n/translations/ko.json | 7 +- apps/mobile/src/i18n/translations/pt-BR.json | 7 +- apps/mobile/src/i18n/translations/ru.json | 7 +- apps/mobile/src/i18n/translations/sv.json | 7 +- apps/mobile/src/i18n/translations/zh.json | 7 +- apps/mobile/src/state/linkedThread.ts | 69 ++++- apps/server/src/auth/RpcAuthorization.test.ts | 53 ++++ .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../server/src/peer/PeerClientPairing.test.ts | 275 ++++++++++++++++++ apps/server/src/peer/PeerClientPairing.ts | 231 +++++++++++++++ apps/server/src/peer/PeerLinks.testkit.ts | 31 +- apps/server/src/peer/PeerLinks.ts | 5 +- apps/server/src/peer/http.ts | 76 +++++ apps/server/src/server.ts | 5 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 6 + .../src/components/chat/LinkedThreadPane.tsx | 82 +++++- .../settings/AddEnvironmentDialog.tsx | 20 +- .../settings/ConnectionsSettings.tsx | 10 +- apps/web/src/connection/onboarding.ts | 10 +- apps/web/src/i18n/translations/de.json | 13 +- apps/web/src/i18n/translations/en.json | 13 +- apps/web/src/i18n/translations/es.json | 13 +- apps/web/src/i18n/translations/fr.json | 13 +- apps/web/src/i18n/translations/ja.json | 13 +- apps/web/src/i18n/translations/ko.json | 13 +- apps/web/src/i18n/translations/pt-BR.json | 13 +- apps/web/src/i18n/translations/ru.json | 13 +- apps/web/src/i18n/translations/sv.json | 13 +- apps/web/src/i18n/translations/zh.json | 13 +- apps/web/src/state/linkedThreadView.ts | 109 ++++++- docs/internals/environment-auth.md | 14 +- docs/user/remote-access.md | 11 +- .../src/connection/onboarding.ts | 32 ++ .../client-runtime/src/linkedThread.test.ts | 81 +++++- packages/client-runtime/src/linkedThread.ts | 41 +++ .../client-runtime/src/state/peerLinks.ts | 9 + .../contracts/src/clientRpcPermissions.ts | 1 + packages/contracts/src/environment.ts | 3 + packages/contracts/src/environmentHttp.ts | 21 +- packages/contracts/src/peerLink.ts | 56 +++- packages/contracts/src/rpc.ts | 10 + 52 files changed, 1518 insertions(+), 64 deletions(-) create mode 100644 apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts create mode 100644 apps/server/src/peer/PeerClientPairing.test.ts create mode 100644 apps/server/src/peer/PeerClientPairing.ts create mode 100644 apps/server/src/peer/http.ts diff --git a/apps/mobile/src/connection/onboarding.ts b/apps/mobile/src/connection/onboarding.ts index 54963759ed189..bf10122432349 100644 --- a/apps/mobile/src/connection/onboarding.ts +++ b/apps/mobile/src/connection/onboarding.ts @@ -44,3 +44,11 @@ export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime Effect.flatMap((onboarding) => onboarding.updateBearer(input)), ), }); + +export const reachesEnvironment = createRuntimeCommand(connectionAtomRuntime, { + label: "mobile:connection:reaches-environment", + execute: (input: { readonly host: string; readonly environmentId: EnvironmentId }) => + ConnectionOnboarding.ConnectionOnboarding.pipe( + Effect.flatMap((onboarding) => onboarding.reaches(input)), + ), +}); diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index 533c71b54ef35..73e035fe75ece 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -30,6 +30,7 @@ import { SymbolView } from "../../components/ui/AppSymbol"; import { hasCloudPublicConfig } from "../cloud/publicConfig"; import { CloudEnvironmentRows } from "./CloudEnvironmentRows"; import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect"; +import { linkedEnvironmentPrefillAtom } from "./linkedEnvironmentPrefill"; import { splitEnvironmentSections } from "./environmentSections"; import { leaveSettingsPage } from "../settings/settings-navigation"; import { workspaceHasColumns } from "../layout/workspace/workspace-selection-store"; @@ -40,6 +41,8 @@ type ConnectionsNewRouteParams = { readonly pairingUrl?: string; readonly autoConnect?: string; readonly routeFor?: EnvironmentId; + /** A linked machine this app chose to pair with; its details come from app state, never the link. */ + readonly linked?: string; }; export function ConnectionsNewRouteScreen({ @@ -48,12 +51,15 @@ export function ConnectionsNewRouteScreen({ const params = route.params ?? {}; // Dev-only prefill prevents production links from supplying an attacker-chosen host and token. const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : ""; + const known = useAtomValue(linkedEnvironmentPrefillAtom); + const linked = known !== null && known.environmentId === params.linked ? known : null; // A new prefill link replaces whatever the form held. return ( ); } @@ -61,9 +67,11 @@ export function ConnectionsNewRouteScreen({ function PairingForm({ routePairingUrl, routeFor, + linked, }: { readonly routePairingUrl: string; readonly routeFor: EnvironmentId | undefined; + readonly linked: { readonly label: string; readonly host: string | null } | null; }) { const gt = useGT(); const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress } = @@ -71,7 +79,7 @@ function PairingForm({ const navigation = useNavigation(); const insets = useSafeAreaInsets(); const [initialPairing] = useState(() => parsePairingUrl(routePairingUrl || connectionPairingUrl)); - const [hostInput, setHostInput] = useState(initialPairing.host); + const [hostInput, setHostInput] = useState(linked?.host ?? initialPairing.host); const [codeInput, setCodeInput] = useState(initialPairing.code); const [isSubmitting, setIsSubmitting] = useState(false); const [submitError, setSubmitError] = useState(null); @@ -188,7 +196,11 @@ function PairingForm({ return ( {pairingConnectionError ?? - gt( - "For machines on your local network or tailnet. The machine keeps its own provider credentials.", - )} + (linked + ? gt( + "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.", + { environment: linked.label }, + ) + : gt( + "For machines on your local network or tailnet. The machine keeps its own provider credentials.", + ))}
    diff --git a/apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts b/apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts new file mode 100644 index 0000000000000..991137c50c2cf --- /dev/null +++ b/apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts @@ -0,0 +1,12 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +/** + * A linked machine the add-environment screen opens for, with what the environment that links to + * it said about it. Set only by this app; a route names the machine and never supplies an address. + */ +export const linkedEnvironmentPrefillAtom = Atom.make<{ + readonly environmentId: EnvironmentId; + readonly label: string; + readonly host: string | null; +} | null>(null).pipe(Atom.withLabel("linked-environment-prefill")); diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 9cbc930548464..7c9ee3c17e9a7 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -1,4 +1,9 @@ -import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { + StackActions, + useIsFocused, + useNavigation, + type StaticScreenProps, +} from "@react-navigation/native"; import { isLinkedThreadWorking, linkedThreadFailure, @@ -31,11 +36,12 @@ import { type ThreadFeedActivity, type ThreadFeedEntry, } from "../../lib/threadActivity"; -import { useLinkedThreadView } from "../../state/linkedThread"; +import { useConnectLinkedEnvironment, useLinkedThreadView } from "../../state/linkedThread"; import { peerLinkEnvironment } from "../../state/peerLinks"; import { useEnvironmentQuery } from "../../state/query"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; import { ReadOnlyComposerBar } from "./ReadOnlyComposerBar"; +import { useOpenLinkedThread } from "./useOpenLinkedThread"; type LinkedThreadRouteParams = { readonly viaEnvironmentId: string; @@ -290,6 +296,21 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { // Follows new items only while the reader is already at the end. const atEnd = useRef(true); const working = projection !== null && isLinkedThreadWorking(projection); + const connection = useConnectLinkedEnvironment(target); + const connectState = connection.state; + const openThread = useOpenLinkedThread(); + const connect = async () => { + const outcome = await connection.connect(); + if (outcome.type === "unreachable") return; + // This sheet closes either way: the thread opens where the app is now connected, or the + // add-environment screen takes its place. + if (outcome.type === "connected") { + navigation.goBack(); + openThread({ environmentId: target.environmentId, threadId: target.threadId }); + return; + } + navigation.dispatch(StackActions.replace("ConnectionsNew", { linked: target.environmentId })); + }; return ( - + void connect()} + /> + } + notice={ + connectState.phase === "connecting" ? ( + + {gt("Connecting to {environment}...", { environment: label })} + + ) : connectState.phase === "unreachable" ? ( + + + {gt("{label} is not reachable from this device", { + label: connectState.label, + })} + + + + Join a network it is on, such as its Tailscale network, and try again. You can + keep reading here. + + + + ) : null + } + /> diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 1ca61edb42844..4d04ac029bf64 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "T3 Code auf {host} war zu beschäftigt, um zu antworten.", "5c5941732d5dfac6": "Die Kopplungsdaten sind ungültig.", "b8ca23ad7dda376e": "Diese Adresse führt zu {host}, einem anderen Rechner. Füge sie stattdessen als eigene Umgebung hinzu.", + "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.", "693cb5c4fb40f109": "Nur gespeicherte Bearer-Umgebungen können bearbeitet werden.", "5f5844b910cb1544": "Die gespeicherten Bearer-Zugangsdaten sind nicht verfügbar.", "51b0133f1ed3cf5c": "Die Bezeichnung der Umgebung darf nicht leer sein.", - "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.", "3aa15bfbe1920376": "Aktualisiere T3 Code auf {host} manuell; es kann sich nicht selbst aktualisieren.", "71907f57b7ec64d5": "{host} ist nicht mit einer kompatiblen T3-Code-Version zurückgekommen.", "e77ac580a4ddcd3b": "Verfügbar", @@ -1969,11 +1969,13 @@ "28ae2c5e144a8c02": "Einstellungen öffnen", "41e3df8a7b6d5d9d": "Ungültiger QR-Code", "c28525066e29c024": "Der gescannte QR-Code wurde nicht erkannt.", + "8a333daf9b7fd03f": "Mit {environment} verbinden", "53c162d8868a1d0e": "Umgebung hinzufügen", "403dd9b445331000": "Wird verbunden", "44bbcfd33b751bd6": "Adresse", "42fd195574793f9e": "Code", "51b31345c7bed6f0": "Kopplungscode", + "e1cb1c8599e84e26": "Erstelle auf {environment} einen Kopplungscode, in dessen Einstellungen → Freigabe & Zugriff oder mit `t3 auth pairing create`, und gib ihn hier ein.", "7d6f419f8ab7f779": "Für Rechner in deinem lokalen Netzwerk oder Tailnet. Der Rechner behält seine eigenen Anbieter-Anmeldedaten.", "36f32bd159bdc0d1": "QR-Code scannen", "11fd02455d938901": "Scanne den Code von {command} oder aus den Verbindungseinstellungen am Desktop", @@ -4158,8 +4160,11 @@ "009e2ca841fdc1ef": "diese Umgebung", "596842e9e887232b": "Wird von {label} gelesen …", "ff889c17671b40af": "Frühere laden", + "d49e5c66faa5d153": "Verbinden, um zu interagieren", + "93e690821c726e13": "{label} ist von diesem Gerät aus nicht erreichbar", "0014ce0aaf1bd68a": "Schreibgeschützt", "048b8a737af895ac": "Noch nichts in diesem Thread.", + "d148218513d9950a": "Tritt einem Netzwerk bei, in dem es sich befindet, etwa seinem Tailscale-Netzwerk, und versuche es erneut. Du kannst hier weiterlesen.", "1410155e503a917f": "{denial} Wechsle den Modus dieses Threads, um fortzufahren.", "81ceeceeb521bba6": "Zu {mode} wechseln", "6ebd73c7bfb58bb7": "App", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 0c37b2d400c94..ac22e97d21be3 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "T3 Code on {host} was too busy to answer.", "5c5941732d5dfac6": "The pairing details are invalid.", "b8ca23ad7dda376e": "That address reaches {host}, a different machine. Add it as its own environment instead.", + "0c0150a90b582a7a": "The environment URL is invalid.", "693cb5c4fb40f109": "Only saved bearer environments can be edited.", "5f5844b910cb1544": "The saved bearer credential is unavailable.", "51b0133f1ed3cf5c": "Environment label cannot be empty.", - "0c0150a90b582a7a": "The environment URL is invalid.", "3aa15bfbe1920376": "Update T3 Code on {host} manually; it cannot update itself.", "71907f57b7ec64d5": "{host} did not come back on a compatible T3 Code version.", "e77ac580a4ddcd3b": "Available", @@ -1969,11 +1969,13 @@ "28ae2c5e144a8c02": "Open Settings", "41e3df8a7b6d5d9d": "Invalid QR code", "c28525066e29c024": "Scanned QR code was not recognized.", + "8a333daf9b7fd03f": "Connect to {environment}", "53c162d8868a1d0e": "Add environment", "403dd9b445331000": "Connecting", "44bbcfd33b751bd6": "Address", "42fd195574793f9e": "Code", "51b31345c7bed6f0": "Pairing code", + "e1cb1c8599e84e26": "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.", "7d6f419f8ab7f779": "For machines on your local network or tailnet. The machine keeps its own provider credentials.", "36f32bd159bdc0d1": "Scan QR code", "11fd02455d938901": "Scan the code from {command} or desktop Connections settings", @@ -4159,8 +4161,11 @@ "009e2ca841fdc1ef": "this environment", "596842e9e887232b": "Reading from {label}…", "ff889c17671b40af": "Load earlier", + "d49e5c66faa5d153": "Connect to interact", + "93e690821c726e13": "{label} is not reachable from this device", "0014ce0aaf1bd68a": "Read-only", "048b8a737af895ac": "Nothing in this thread yet.", + "d148218513d9950a": "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.", "1410155e503a917f": "{denial} Switch this thread's mode to continue.", "81ceeceeb521bba6": "Switch to {mode}", "6ebd73c7bfb58bb7": "App", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 09e9b73026ad9..046959950b3b0 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "T3 Code en {host} estaba demasiado ocupado para responder.", "5c5941732d5dfac6": "Los datos de emparejamiento no son válidos.", "b8ca23ad7dda376e": "Esa dirección lleva a {host}, otra máquina. Añádela como un entorno propio.", + "0c0150a90b582a7a": "La URL del entorno no es válida.", "693cb5c4fb40f109": "Solo se pueden editar los entornos bearer guardados.", "5f5844b910cb1544": "La credencial bearer guardada no está disponible.", "51b0133f1ed3cf5c": "La etiqueta del entorno no puede estar vacía.", - "0c0150a90b582a7a": "La URL del entorno no es válida.", "3aa15bfbe1920376": "Actualiza T3 Code en {host} manualmente; no puede actualizarse solo.", "71907f57b7ec64d5": "{host} no volvió con una versión compatible de T3 Code.", "e77ac580a4ddcd3b": "Disponible", @@ -1969,11 +1969,13 @@ "28ae2c5e144a8c02": "Abrir Ajustes", "41e3df8a7b6d5d9d": "Código QR no válido", "c28525066e29c024": "No se reconoció el código QR escaneado.", + "8a333daf9b7fd03f": "Conectar con {environment}", "53c162d8868a1d0e": "Añadir entorno", "403dd9b445331000": "Conectando", "44bbcfd33b751bd6": "Dirección", "42fd195574793f9e": "Código", "51b31345c7bed6f0": "Código de emparejamiento", + "e1cb1c8599e84e26": "Crea un código de emparejamiento en {environment}, en sus Ajustes → Compartir y acceso o con `t3 auth pairing create`, e introdúcelo aquí.", "7d6f419f8ab7f779": "Para máquinas de tu red local o tailnet. La máquina conserva sus propias credenciales de proveedores.", "36f32bd159bdc0d1": "Escanear código QR", "11fd02455d938901": "Escanea el código de {command} o de los ajustes de Conexiones del escritorio", @@ -4153,8 +4155,11 @@ "009e2ca841fdc1ef": "este entorno", "596842e9e887232b": "Leyendo desde {label}…", "ff889c17671b40af": "Cargar anteriores", + "d49e5c66faa5d153": "Conectar para interactuar", + "93e690821c726e13": "No se puede acceder a {label} desde este dispositivo", "0014ce0aaf1bd68a": "Solo lectura", "048b8a737af895ac": "Aún no hay nada en este hilo.", + "d148218513d9950a": "Únete a una red en la que esté, como su red de Tailscale, y vuelve a intentarlo. Puedes seguir leyendo aquí.", "1410155e503a917f": "{denial} Cambia el modo de este hilo para continuar.", "81ceeceeb521bba6": "Cambiar a {mode}", "6ebd73c7bfb58bb7": "App", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 69183070867dd..c156610bd5c09 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "T3 Code sur {host} était trop occupé pour répondre.", "5c5941732d5dfac6": "Les informations d’appairage ne sont pas valides.", "b8ca23ad7dda376e": "Cette adresse mène à {host}, une autre machine. Ajoutez-la plutôt comme environnement distinct.", + "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.", "693cb5c4fb40f109": "Seuls les environnements bearer enregistrés peuvent être modifiés.", "5f5844b910cb1544": "Les identifiants bearer enregistrés ne sont pas disponibles.", "51b0133f1ed3cf5c": "Le libellé de l’environnement ne peut pas être vide.", - "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.", "3aa15bfbe1920376": "Mettez à jour T3 Code sur {host} manuellement ; il ne peut pas se mettre à jour seul.", "71907f57b7ec64d5": "{host} n’est pas revenu sur une version compatible de T3 Code.", "e77ac580a4ddcd3b": "Disponible", @@ -1969,11 +1969,13 @@ "28ae2c5e144a8c02": "Ouvrir les Réglages", "41e3df8a7b6d5d9d": "Code QR non valide", "c28525066e29c024": "Le code QR scanné n’a pas été reconnu.", + "8a333daf9b7fd03f": "Se connecter à {environment}", "53c162d8868a1d0e": "Ajouter un environnement", "403dd9b445331000": "Connexion", "44bbcfd33b751bd6": "Adresse", "42fd195574793f9e": "Code", "51b31345c7bed6f0": "Code d’appairage", + "e1cb1c8599e84e26": "Créez un code d’appairage sur {environment}, dans ses Paramètres → Partage et accès ou avec `t3 auth pairing create`, puis saisissez-le ici.", "7d6f419f8ab7f779": "Pour les machines de votre réseau local ou de votre tailnet. La machine garde ses propres identifiants de fournisseur.", "36f32bd159bdc0d1": "Scanner un code QR", "11fd02455d938901": "Scannez le code de {command} ou des paramètres Connexions du bureau", @@ -4153,8 +4155,11 @@ "009e2ca841fdc1ef": "cet environnement", "596842e9e887232b": "Lecture depuis {label}…", "ff889c17671b40af": "Charger les précédents", + "d49e5c66faa5d153": "Se connecter pour interagir", + "93e690821c726e13": "{label} n’est pas accessible depuis cet appareil", "0014ce0aaf1bd68a": "Lecture seule", "048b8a737af895ac": "Rien dans ce fil pour l’instant.", + "d148218513d9950a": "Rejoignez un réseau sur lequel il se trouve, comme son réseau Tailscale, puis réessayez. Vous pouvez continuer à lire ici.", "1410155e503a917f": "{denial} Changez le mode de ce fil pour continuer.", "81ceeceeb521bba6": "Passer en {mode}", "6ebd73c7bfb58bb7": "App", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index fd55b3e454fa2..019032f1eee88 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "{host} の T3 Code はビジー状態で応答できませんでした。", "5c5941732d5dfac6": "ペアリングの詳細が無効です。", "b8ca23ad7dda376e": "そのアドレスは別のマシンである {host} につながります。代わりに独立した環境として追加してください。", + "0c0150a90b582a7a": "環境の URL が無効です。", "693cb5c4fb40f109": "編集できるのは保存済みのベアラー環境のみです。", "5f5844b910cb1544": "保存済みのベアラー資格情報は利用できません。", "51b0133f1ed3cf5c": "環境のラベルは空にできません。", - "0c0150a90b582a7a": "環境の URL が無効です。", "3aa15bfbe1920376": "{host} の T3 Code は自動で更新できないため、手動で更新してください。", "71907f57b7ec64d5": "{host} は互換性のある T3 Code のバージョンで復帰しませんでした。", "e77ac580a4ddcd3b": "利用可能", @@ -1969,11 +1969,13 @@ "28ae2c5e144a8c02": "設定を開く", "41e3df8a7b6d5d9d": "無効な QR コード", "c28525066e29c024": "スキャンした QR コードを認識できませんでした。", + "8a333daf9b7fd03f": "{environment} に接続", "53c162d8868a1d0e": "環境を追加", "403dd9b445331000": "接続中", "44bbcfd33b751bd6": "アドレス", "42fd195574793f9e": "コード", "51b31345c7bed6f0": "ペアリングコード", + "e1cb1c8599e84e26": "{environment} の設定 → 共有とアクセス、または `t3 auth pairing create` でペアリングコードを作成し、ここに入力してください。", "7d6f419f8ab7f779": "ローカルネットワークや tailnet 上のマシン向けです。マシンはプロバイダーの認証情報を自身で保持します。", "36f32bd159bdc0d1": "QR コードをスキャン", "11fd02455d938901": "{command} またはデスクトップの接続設定に表示されるコードをスキャンしてください", @@ -4149,8 +4151,11 @@ "009e2ca841fdc1ef": "この環境", "596842e9e887232b": "{label} から読み取り中…", "ff889c17671b40af": "以前のものを読み込む", + "d49e5c66faa5d153": "接続して操作する", + "93e690821c726e13": "このデバイスから {label} に接続できません", "0014ce0aaf1bd68a": "読み取り専用", "048b8a737af895ac": "このスレッドにはまだ何もありません。", + "d148218513d9950a": "Tailscale ネットワークなど、そのマシンが接続しているネットワークに参加してから、もう一度お試しください。ここでは引き続き閲覧できます。", "1410155e503a917f": "{denial} 続行するには、このスレッドのモードを切り替えてください。", "81ceeceeb521bba6": "{mode} に切り替え", "6ebd73c7bfb58bb7": "アプリ", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 0489c6184e35e..de7e21280597f 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "{host}의 T3 Code가 너무 바빠서 응답하지 못했습니다.", "5c5941732d5dfac6": "페어링 정보가 올바르지 않습니다.", "b8ca23ad7dda376e": "이 주소는 다른 머신인 {host}에 연결됩니다. 대신 별도의 환경으로 추가하세요.", + "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.", "693cb5c4fb40f109": "저장된 bearer 환경만 편집할 수 있습니다.", "5f5844b910cb1544": "저장된 bearer 자격 증명을 사용할 수 없습니다.", "51b0133f1ed3cf5c": "환경 레이블은 비워 둘 수 없습니다.", - "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.", "3aa15bfbe1920376": "{host}의 T3 Code는 스스로 업데이트할 수 없으니 직접 업데이트하세요.", "71907f57b7ec64d5": "{host}이(가) 호환되는 T3 Code 버전으로 돌아오지 않았습니다.", "e77ac580a4ddcd3b": "사용 가능", @@ -1970,11 +1970,13 @@ "28ae2c5e144a8c02": "설정 열기", "41e3df8a7b6d5d9d": "잘못된 QR 코드", "c28525066e29c024": "스캔한 QR 코드를 인식할 수 없습니다.", + "8a333daf9b7fd03f": "{environment}에 연결", "53c162d8868a1d0e": "환경 추가", "403dd9b445331000": "연결 중", "44bbcfd33b751bd6": "주소", "42fd195574793f9e": "코드", "51b31345c7bed6f0": "페어링 코드", + "e1cb1c8599e84e26": "{environment}의 설정 → 공유 및 액세스에서 또는 `t3 auth pairing create`로 페어링 코드를 만든 다음 여기에 입력하세요.", "7d6f419f8ab7f779": "로컬 네트워크나 tailnet에 있는 머신용입니다. 머신은 자체 제공자 자격 증명을 유지합니다.", "36f32bd159bdc0d1": "QR 코드 스캔", "11fd02455d938901": "{command} 또는 데스크톱 연결 설정의 코드를 스캔하세요", @@ -4153,8 +4155,11 @@ "009e2ca841fdc1ef": "이 환경", "596842e9e887232b": "{label}에서 읽는 중…", "ff889c17671b40af": "이전 항목 불러오기", + "d49e5c66faa5d153": "연결하여 상호작용", + "93e690821c726e13": "이 기기에서 {label}에 연결할 수 없습니다", "0014ce0aaf1bd68a": "읽기 전용", "048b8a737af895ac": "이 스레드에는 아직 아무것도 없습니다.", + "d148218513d9950a": "Tailscale 네트워크처럼 해당 머신이 연결된 네트워크에 참여한 후 다시 시도하세요. 여기에서 계속 읽을 수 있습니다.", "1410155e503a917f": "{denial} 계속하려면 이 스레드의 모드를 전환하세요.", "81ceeceeb521bba6": "{mode}(으)로 전환", "6ebd73c7bfb58bb7": "앱", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 03d50749e39cd..46a70448abf80 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "O T3 Code em {host} estava ocupado demais para responder.", "5c5941732d5dfac6": "Os detalhes de pareamento são inválidos.", "b8ca23ad7dda376e": "Esse endereço leva a {host}, outra máquina. Adicione-a como um ambiente próprio.", + "0c0150a90b582a7a": "A URL do ambiente é inválida.", "693cb5c4fb40f109": "Só é possível editar ambientes bearer salvos.", "5f5844b910cb1544": "A credencial bearer salva não está disponível.", "51b0133f1ed3cf5c": "O rótulo do ambiente não pode ficar vazio.", - "0c0150a90b582a7a": "A URL do ambiente é inválida.", "3aa15bfbe1920376": "Atualize o T3 Code em {host} manualmente; ele não consegue se atualizar sozinho.", "71907f57b7ec64d5": "{host} não voltou em uma versão compatível do T3 Code.", "e77ac580a4ddcd3b": "Disponível", @@ -1969,11 +1969,13 @@ "28ae2c5e144a8c02": "Abrir Ajustes", "41e3df8a7b6d5d9d": "QR code inválido", "c28525066e29c024": "O QR code escaneado não foi reconhecido.", + "8a333daf9b7fd03f": "Conectar a {environment}", "53c162d8868a1d0e": "Adicionar ambiente", "403dd9b445331000": "Conectando", "44bbcfd33b751bd6": "Endereço", "42fd195574793f9e": "Código", "51b31345c7bed6f0": "Código de pareamento", + "e1cb1c8599e84e26": "Crie um código de pareamento em {environment}, em Configurações → Compartilhamento e acesso ou com `t3 auth pairing create`, e insira-o aqui.", "7d6f419f8ab7f779": "Para máquinas na sua rede local ou tailnet. A máquina mantém as próprias credenciais dos provedores.", "36f32bd159bdc0d1": "Escanear QR code", "11fd02455d938901": "Escaneie o código de {command} ou das configurações de Conexões do desktop", @@ -4153,8 +4155,11 @@ "009e2ca841fdc1ef": "este ambiente", "596842e9e887232b": "Lendo de {label}…", "ff889c17671b40af": "Carregar anteriores", + "d49e5c66faa5d153": "Conectar para interagir", + "93e690821c726e13": "{label} não está acessível a partir deste dispositivo", "0014ce0aaf1bd68a": "Somente leitura", "048b8a737af895ac": "Ainda não há nada nesta thread.", + "d148218513d9950a": "Entre em uma rede em que ele esteja, como a rede Tailscale dele, e tente novamente. Você pode continuar lendo aqui.", "1410155e503a917f": "{denial} Mude o modo desta thread para continuar.", "81ceeceeb521bba6": "Mudar para {mode}", "6ebd73c7bfb58bb7": "App", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index b5700f2a091af..0632e3bf3d673 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "T3 Code на {host} был слишком занят, чтобы ответить.", "5c5941732d5dfac6": "Данные сопряжения недействительны.", "b8ca23ad7dda376e": "Этот адрес ведёт к {host}, другому компьютеру. Добавьте его как отдельное окружение.", + "0c0150a90b582a7a": "URL окружения недействителен.", "693cb5c4fb40f109": "Изменять можно только сохранённые окружения с bearer-токеном.", "5f5844b910cb1544": "Сохранённые bearer-учётные данные недоступны.", "51b0133f1ed3cf5c": "Название окружения не может быть пустым.", - "0c0150a90b582a7a": "URL окружения недействителен.", "3aa15bfbe1920376": "Обновите T3 Code на {host} вручную: он не может обновиться сам.", "71907f57b7ec64d5": "{host} не вернулся с совместимой версией T3 Code.", "e77ac580a4ddcd3b": "Доступно", @@ -1993,11 +1993,13 @@ "28ae2c5e144a8c02": "Открыть настройки", "41e3df8a7b6d5d9d": "Недействительный QR-код", "c28525066e29c024": "Отсканированный QR-код не распознан.", + "8a333daf9b7fd03f": "Подключиться к {environment}", "53c162d8868a1d0e": "Добавить окружение", "403dd9b445331000": "Подключение", "44bbcfd33b751bd6": "Адрес", "42fd195574793f9e": "Код", "51b31345c7bed6f0": "Код сопряжения", + "e1cb1c8599e84e26": "Создайте код сопряжения на {environment} в разделе «Настройки → Общий доступ» или командой `t3 auth pairing create` и введите его здесь.", "7d6f419f8ab7f779": "Для машин в вашей локальной сети или tailnet. Машина хранит собственные учётные данные провайдеров.", "36f32bd159bdc0d1": "Сканировать QR-код", "11fd02455d938901": "Отсканируйте код из {command} или из настроек подключений в десктопном приложении", @@ -4207,8 +4209,11 @@ "009e2ca841fdc1ef": "это окружение", "596842e9e887232b": "Чтение с {label}…", "ff889c17671b40af": "Загрузить более ранние", + "d49e5c66faa5d153": "Подключиться для взаимодействия", + "93e690821c726e13": "{label} недоступно с этого устройства", "0014ce0aaf1bd68a": "Только чтение", "048b8a737af895ac": "В этом треде пока ничего нет.", + "d148218513d9950a": "Подключитесь к сети, в которой оно находится, например к его сети Tailscale, и повторите попытку. Здесь можно продолжать чтение.", "1410155e503a917f": "{denial} Чтобы продолжить, переключите режим этого треда.", "81ceeceeb521bba6": "Переключиться на {mode}", "6ebd73c7bfb58bb7": "Приложение", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 387410edf127e..7d613fb7b3c9b 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "T3 Code på {host} var för upptagen för att svara.", "5c5941732d5dfac6": "Uppgifterna för parkopplingen är ogiltiga.", "b8ca23ad7dda376e": "Den adressen leder till {host}, en annan dator. Lägg till den som en egen miljö i stället.", + "0c0150a90b582a7a": "Miljöns URL är ogiltig.", "693cb5c4fb40f109": "Bara sparade bearer-miljöer kan redigeras.", "5f5844b910cb1544": "Den sparade bearer-uppgiften är inte tillgänglig.", "51b0133f1ed3cf5c": "Miljöns etikett får inte vara tom.", - "0c0150a90b582a7a": "Miljöns URL är ogiltig.", "3aa15bfbe1920376": "Uppdatera T3 Code på {host} manuellt; det kan inte uppdatera sig självt.", "71907f57b7ec64d5": "{host} kom inte tillbaka med en kompatibel version av T3 Code.", "e77ac580a4ddcd3b": "Tillgänglig", @@ -1969,11 +1969,13 @@ "28ae2c5e144a8c02": "Öppna Inställningar", "41e3df8a7b6d5d9d": "Ogiltig QR-kod", "c28525066e29c024": "Den skannade QR-koden kändes inte igen.", + "8a333daf9b7fd03f": "Anslut till {environment}", "53c162d8868a1d0e": "Lägg till miljö", "403dd9b445331000": "Ansluter", "44bbcfd33b751bd6": "Adress", "42fd195574793f9e": "Kod", "51b31345c7bed6f0": "Parkopplingskod", + "e1cb1c8599e84e26": "Skapa en parkopplingskod på {environment}, i dess Inställningar → Delning och åtkomst eller med `t3 auth pairing create`, och ange den här.", "7d6f419f8ab7f779": "För datorer i ditt lokala nätverk eller tailnet. Datorn behåller sina egna leverantörsuppgifter.", "36f32bd159bdc0d1": "Skanna QR-kod", "11fd02455d938901": "Skanna koden från {command} eller inställningen Anslutningar på skrivbordet", @@ -4159,8 +4161,11 @@ "009e2ca841fdc1ef": "den här miljön", "596842e9e887232b": "Läser från {label}…", "ff889c17671b40af": "Läs in tidigare", + "d49e5c66faa5d153": "Anslut för att interagera", + "93e690821c726e13": "{label} kan inte nås från den här enheten", "0014ce0aaf1bd68a": "Skrivskyddad", "048b8a737af895ac": "Inget i den här tråden ännu.", + "d148218513d9950a": "Anslut till ett nätverk som den finns på, till exempel dess Tailscale-nätverk, och försök igen. Du kan fortsätta läsa här.", "1410155e503a917f": "{denial} Byt trådens läge för att fortsätta.", "81ceeceeb521bba6": "Byt till {mode}", "6ebd73c7bfb58bb7": "App", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index c526a2f9eb1e3..b560f0af3fbf0 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -457,10 +457,10 @@ "93e37fedae7eaa5b": "{host} 上的 T3 Code 太忙,未能响应。", "5c5941732d5dfac6": "配对信息无效。", "b8ca23ad7dda376e": "该地址指向另一台机器 {host}。请将其添加为独立环境。", + "0c0150a90b582a7a": "环境 URL 无效。", "693cb5c4fb40f109": "只能编辑已保存的 bearer 环境。", "5f5844b910cb1544": "已保存的 bearer 凭据不可用。", "51b0133f1ed3cf5c": "环境名称不能为空。", - "0c0150a90b582a7a": "环境 URL 无效。", "3aa15bfbe1920376": "请手动更新 {host} 上的 T3 Code;它无法自行更新。", "71907f57b7ec64d5": "{host} 重启后未运行兼容的 T3 Code 版本。", "e77ac580a4ddcd3b": "可用", @@ -1971,11 +1971,13 @@ "28ae2c5e144a8c02": "打开设置", "41e3df8a7b6d5d9d": "二维码无效", "c28525066e29c024": "无法识别扫描的二维码。", + "8a333daf9b7fd03f": "连接到 {environment}", "53c162d8868a1d0e": "添加环境", "403dd9b445331000": "正在连接", "44bbcfd33b751bd6": "地址", "42fd195574793f9e": "配对码", "51b31345c7bed6f0": "配对码", + "e1cb1c8599e84e26": "在 {environment} 的设置 → 共享与访问中或使用 `t3 auth pairing create` 创建配对码,然后在此输入。", "7d6f419f8ab7f779": "适用于本地网络或 tailnet 中的机器。该机器保留自己的提供方凭据。", "36f32bd159bdc0d1": "扫描二维码", "11fd02455d938901": "扫描 {command} 或桌面端“连接”设置中的二维码", @@ -4156,8 +4158,11 @@ "009e2ca841fdc1ef": "此环境", "596842e9e887232b": "正在从 {label} 读取…", "ff889c17671b40af": "加载更早的内容", + "d49e5c66faa5d153": "连接以进行交互", + "93e690821c726e13": "无法从此设备访问 {label}", "0014ce0aaf1bd68a": "只读", "048b8a737af895ac": "此会话中还没有内容。", + "d148218513d9950a": "请加入它所在的网络(例如其 Tailscale 网络),然后重试。你仍可在此继续阅读。", "1410155e503a917f": "{denial} 切换此会话的模式以继续。", "81ceeceeb521bba6": "切换到 {mode}", "6ebd73c7bfb58bb7": "应用", diff --git a/apps/mobile/src/state/linkedThread.ts b/apps/mobile/src/state/linkedThread.ts index fd685650c903c..ff4c75b9ac1ac 100644 --- a/apps/mobile/src/state/linkedThread.ts +++ b/apps/mobile/src/state/linkedThread.ts @@ -1,10 +1,18 @@ -import { useAtomValue } from "@effect/atom-react"; -import type { LinkedThreadTarget } from "@t3tools/client-runtime/linked-thread"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { + connectLinkedEnvironment, + type LinkedThreadTarget, +} from "@t3tools/client-runtime/linked-thread"; import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts"; +import { useState } from "react"; +import { connectPairingUrl, reachesEnvironment } from "../connection/onboarding"; +import { linkedEnvironmentPrefillAtom } from "../features/connection/linkedEnvironmentPrefill"; +import { buildPairingUrl } from "../features/connection/pairing"; import { useEnvironments } from "./environments"; import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks"; import { useEnvironmentQuery } from "./query"; +import { useAtomCommand } from "./use-atom-command"; /** * What places a delegated task's thread: this app's own connections, and the links `environmentId` @@ -32,6 +40,63 @@ export function useLinkedThreadReach( return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) }; } +export type LinkedEnvironmentConnectState = + | { readonly phase: "idle" | "connecting" } + | { readonly phase: "unreachable"; readonly label: string }; + +/** + * Connects this app to the environment `target` lives in. One step when the linking environment + * can get a pairing for this app; otherwise the caller opens the add-environment screen, which + * reads what was learned about the machine. + */ +export function useConnectLinkedEnvironment(target: LinkedThreadTarget) { + const setPrefill = useAtomSet(linkedEnvironmentPrefillAtom); + const mayPair = useAtomValue( + peerLinkEnvironment.pairClient.permissionAtom(target.viaEnvironmentId), + ); + const quiet = { reportFailure: false, reportDefect: false } as const; + const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet); + const reaches = useAtomCommand(reachesEnvironment, quiet); + const pair = useAtomCommand(connectPairingUrl, quiet); + const [state, setState] = useState({ phase: "idle" }); + const connect = async () => { + setState({ phase: "connecting" }); + const outcome = await connectLinkedEnvironment({ + label: target.label, + requestPairing: async () => { + // Without it the linking environment refuses; the user can still pair by hand. + if (!mayPair) return null; + const result = await requestPairing({ + environmentId: target.viaEnvironmentId, + input: { environmentId: target.environmentId }, + }); + return result._tag === "Success" ? result.value : null; + }, + reaches: async (host) => { + const result = await reaches({ host, environmentId: target.environmentId }); + return result._tag === "Success" && result.value; + }, + pair: async ({ host, pairingCode }) => { + const result = await pair({ + pairingUrl: buildPairingUrl(host, pairingCode), + expectedEnvironmentId: target.environmentId, + }); + return result._tag === "Success"; + }, + }); + setState( + outcome.type === "unreachable" + ? { phase: "unreachable", label: outcome.label } + : { phase: "idle" }, + ); + if (outcome.type === "manual") { + setPrefill({ environmentId: target.environmentId, label: outcome.label, host: outcome.host }); + } + return outcome; + }; + return { state, connect }; +} + /** * The thread of `target`, streamed through the environment that links to it. The stream runs only * while `active`; what it last showed stays, so coming back to the screen shows it at once. diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index aee5dd3fae815..200a049e0118b 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -288,6 +288,59 @@ it.effect("reads a linked environment's thread only for a client that may read t }).pipe(Effect.scoped), ); +it.effect("pairs a client with a linked environment only for one that may hand out access", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.peerLinksPairClient + > => tag !== WS_METHODS.peerLinksPairClient, + ), + ); + let asked = 0; + const environmentId = EnvironmentId.make("environment-box"); + const handlers = group.toLayerHandler(WS_METHODS.peerLinksPairClient, () => + Effect.sync(() => { + asked++; + return { + type: "unsupported" as const, + reason: "link_access" as const, + environmentId, + label: "Box", + urls: [], + }; + }), + ); + // Running agents and reading the access list do not include handing access out. + const operator = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.merge( + handlers, + RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]), + ), + ), + ); + expect( + yield* operator[WS_METHODS.peerLinksPairClient]({ environmentId }).pipe(Effect.flip), + ).toMatchObject({ + _tag: "EnvironmentAuthorizationError", + requiredPermission: AuthAccessWriteScope, + }); + expect(asked).toBe(0); + + const manager = yield* RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthAccessWriteScope]))), + ); + expect((yield* manager[WS_METHODS.peerLinksPairClient]({ environmentId })).type).toBe( + "unsupported", + ); + expect(asked).toBe(1); + }).pipe(Effect.scoped), +); + it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)( "enforces read permission on stream %s", (method) => diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 5c1e54b8ab75a..2208e70b983e3 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -298,6 +298,7 @@ export const make = Effect.gen(function* () { mcpModeLimitHeader: true, linkFence: true, linkThreadStream: true, + linkClientPairing: true, mcpApprovalCodes: true, peerLinkPairingCodes: true, mcpHostedApproval: true, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 651ca4070a8e9..96351b39b6315 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -73,6 +73,7 @@ const RPC_AGGREGATES = { [WS_METHODS.peerLinksSubscribeThread]: "peerLinks", [WS_METHODS.peerLinksThreadHistoryPage]: "peerLinks", [WS_METHODS.peerLinksThreadItem]: "peerLinks", + [WS_METHODS.peerLinksPairClient]: "peerLinks", [WS_METHODS.serverGetSettings]: "server", [WS_METHODS.serverUpdateSettings]: "server", [WS_METHODS.serverSearchAcpRegistry]: "server", diff --git a/apps/server/src/peer/PeerClientPairing.test.ts b/apps/server/src/peer/PeerClientPairing.test.ts new file mode 100644 index 0000000000000..a9bd0f63454d7 --- /dev/null +++ b/apps/server/src/peer/PeerClientPairing.test.ts @@ -0,0 +1,275 @@ +import { NodeHttpServer } from "@effect/platform-node"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { + AuthAccessWriteScope, + type AuthEnvironmentScope, + type AuthMcpClientAccess, + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, + AuthRelayConfigureScope, + AuthStandardClientScopes, + AuthTerminalOperateScope, + type ExecutionEnvironmentDescriptor, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpBody from "effect/http/HttpBody"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as TestClock from "effect/testing/TestClock"; +import { Toolkit } from "effect/ai"; + +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; +import * as McpToolAccess from "../mcp/McpToolAccess.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as PeerClientPairing from "./PeerClientPairing.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import { + descriptorOf, + layerEnvironmentAuth, + layerLinkingEnvironment, + linkTo, + type ServedPeer, + servePeer, +} from "./PeerLinks.testkit.ts"; + +const laptop = descriptorOf("environment-laptop", "Laptop"); +const box = descriptorOf("environment-box", "Box", { linkClientPairing: true }); +const NoTools = Toolkit.make(); + +const serveBox = (descriptor: ExecutionEnvironmentDescriptor = box) => + servePeer( + descriptor, + McpHttpServer.toolkitRegistration(NoTools, McpToolAccess.toLayer(NoTools, {})), + ); + +/** The laptop: its links, its own clients, and what answers a client asking to pair with a link. */ +const makeLaptop = Effect.gen(function* () { + const linking = yield* Layer.build(layerLinkingEnvironment(laptop)); + const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-here-auth-")); + const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth); + const pairing = yield* PeerClientPairing.layer.pipe( + Layer.provide(Layer.succeedContext(linking)), + Layer.provide(Layer.succeed(EnvironmentAuth.EnvironmentAuth, auth)), + Layer.provide(FetchHttpClient.layer), + Layer.build, + ); + return { + links: Context.get(linking, PeerLinks.PeerLinks), + settings: Context.get(linking, ServerSettings.ServerSettingsService), + pairing: Context.get(pairing, PeerClientPairing.PeerClientPairing), + /** A client paired with the laptop, such as a phone. */ + client: (scopes: ReadonlyArray) => + auth.issueSession({ scopes, label: "Phone" }), + }; +}); + +const metadata = { deviceType: "mobile" as const }; + +/** Asks the box's route directly, as anything holding `bearer` could, and answers its status. */ +const askBox = (b: ServedPeer, bearer: string | undefined, headers: Record = {}) => + HttpClient.execute( + HttpClientRequest.post(`${b.url}/api/peer-link/client-pairing`).pipe( + HttpClientRequest.setHeaders({ + ...(bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }), + ...headers, + }), + HttpClientRequest.setBody( + HttpBody.text( + JSON.stringify({ scopes: AuthStandardClientScopes, clientLabel: "Phone" }), + "application/json", + ), + ), + ), + ).pipe( + Effect.map((response) => response.status), + Effect.provide(FetchHttpClient.layer), + ); + +const linkTokenOf = (a: Effect.Success) => + a.links.resolve(box.environmentId).pipe(Effect.map((resolved) => resolved.token)); + +it.effect( + "a full-access link gets a client one pairing, with no more than the client holds here", + () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveBox(); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "full-access"); + // Holds less than a pairing code grants, and one scope no pairing code grants. + const held = [ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + AuthAccessWriteScope, + AuthRelayConfigureScope, + ]; + const phone = yield* a.client(held); + + const result = yield* a.pairing.request({ environmentId: box.environmentId }, phone); + if (result.type !== "credential") return yield* Effect.die(result); + expect(result).toMatchObject({ + environmentId: box.environmentId, + label: "Box", + urls: [b.url], + }); + // The box's Connections says where the pairing came from, and can revoke it. + expect(yield* b.auth.listPairingLinks()).toMatchObject([{ label: "Phone · via Laptop" }]); + + const session = yield* b.auth.exchangeBootstrapCredentialForAccessToken( + result.credential, + undefined, + metadata, + ); + expect(new Set(session.scope.split(" "))).toEqual( + new Set([ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + AuthAccessWriteScope, + ]), + ); + expect(session.scope).not.toContain(AuthTerminalOperateScope); + const again = yield* b.auth + .exchangeBootstrapCredentialForAccessToken(result.credential, undefined, metadata) + .pipe(Effect.flip); + expect(again._tag).toBe("ServerAuthInvalidCredentialError"); + + // One the client never redeems is gone within minutes. + const unused = yield* a.pairing.request({ environmentId: box.environmentId }, phone); + if (unused.type !== "credential") return yield* Effect.die(unused); + yield* TestClock.adjust("3 minutes"); + const late = yield* b.auth + .exchangeBootstrapCredentialForAccessToken(unused.credential, undefined, metadata) + .pipe(Effect.flip); + expect(late._tag).toBe("ServerAuthInvalidCredentialError"); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect.each(["read-only", "approval-required", "auto"] as const)( + "a %s link cannot pair a client, even when the linking environment is bypassed", + (access: AuthMcpClientAccess) => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveBox(); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, access); + const phone = yield* a.client(AuthStandardClientScopes); + + expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({ + type: "unsupported", + reason: "link_access", + environmentId: box.environmentId, + label: "Box", + urls: [b.url], + }); + expect(yield* Ref.get(b.bearers)).toEqual([]); + + expect(yield* askBox(b, yield* linkTokenOf(a))).toBe(403); + expect(yield* b.auth.listPairingLinks()).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("only a full-access link's own session reaches the box's pairing route", () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveBox(); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "full-access"); + const linkToken = yield* linkTokenOf(a); + + // An outside agent approved at full access is not a link. + const agent = yield* b.auth.issueMcpClientSession({ + label: "Outside agent", + access: "full-access", + peerLink: false, + client: { deviceType: "bot" }, + }); + expect(yield* askBox(b, agent.token)).toBe(403); + + // An agent's thread credential, which a link-started agent holds too, is not a session. + const registry = yield* McpSessionRegistry.layer.pipe( + Layer.provide( + Layer.succeed(ServerEnvironment.ServerEnvironment, { + getEnvironmentId: Effect.succeed(box.environmentId), + getDescriptor: Effect.succeed(box), + }), + ), + Layer.provide(NodeCrypto.layer), + Layer.build, + ); + const thread = yield* Context.get(registry, McpSessionRegistry.McpSessionRegistry).issue({ + threadId: ThreadId.make("thread:box-link-started"), + providerInstanceId: ProviderInstanceId.make("codex"), + }); + expect(yield* askBox(b, thread.config.authorizationHeader.slice("Bearer ".length))).toBe(401); + + // The box's own administrator client pairs devices from Connections, not from here. + const owner = yield* b.auth.issueSession({ scopes: AuthStandardClientScopes }); + expect(yield* askBox(b, owner.token)).toBe(401); + expect(yield* askBox(b, undefined)).toBe(401); + // A page in a browser never holds a link's token. + expect(yield* askBox(b, linkToken, { origin: "https://example.com" })).toBe(403); + expect(yield* b.auth.listPairingLinks()).toEqual([]); + + expect(yield* askBox(b, linkToken)).toBe(200); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("pairs no client while Linked environments is off on either side", () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveBox(); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "full-access"); + const phone = yield* a.client(AuthStandardClientScopes); + const linkToken = yield* linkTokenOf(a); + + yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false }); + expect(yield* askBox(b, linkToken)).toBe(403); + expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toMatchObject({ + type: "unsupported", + reason: "refused", + }); + yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true }); + + yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false }); + const off = yield* a.pairing + .request({ environmentId: box.environmentId }, phone) + .pipe(Effect.flip); + expect(off.reason).toBe("disabled"); + expect(yield* b.auth.listPairingLinks()).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("a linked environment from before client pairing is never asked", () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveBox(descriptorOf("environment-box", "Box")); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "full-access"); + const phone = yield* a.client(AuthStandardClientScopes); + + expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({ + type: "unsupported", + reason: "version", + environmentId: box.environmentId, + label: "Box", + urls: [b.url], + }); + expect(yield* Ref.get(b.bearers)).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/peer/PeerClientPairing.ts b/apps/server/src/peer/PeerClientPairing.ts new file mode 100644 index 0000000000000..045b369cfe2f4 --- /dev/null +++ b/apps/server/src/peer/PeerClientPairing.ts @@ -0,0 +1,231 @@ +import { + type AuthEnvironmentScope, + type AuthSessionId, + AuthStandardClientScopes, + EnvironmentHttpApi, + type PeerLinkClientPairingCredential, + type PeerLinkClientPairingInput, + type PeerLinkClientPairingRequest, + type PeerLinkClientPairingResult, + PeerLinkError, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpApi from "effect/http-api/HttpApi"; +import * as HttpApiClient from "effect/http-api/HttpApiClient"; + +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as PeerLinks from "./PeerLinks.ts"; + +/** Long enough for the client to reach the linked environment and redeem it, and no longer. */ +const CLIENT_PAIRING_TTL = Duration.minutes(3); +const CLIENT_LABEL_MAX_LENGTH = 80; + +const ClientPairingApi = HttpApi.make(EnvironmentHttpApi.identifier) + .add(EnvironmentHttpApi.groups.peerLink) + .annotateMerge(EnvironmentHttpApi.annotations); + +/** Why the linked environment will not mint a client pairing for this caller. */ +export class PeerClientPairingRefused extends Schema.TaggedError()( + "PeerClientPairingRefused", + { + reason: Schema.Literals(["disabled", "not_a_full_access_link", "no_scopes", "policy"]), + message: Schema.String, + }, +) {} + +/** + * The linked side: mints a one-time pairing credential for a client of the environment that + * links here, when that environment asks over its link. + */ +export class PeerClientPairingIssuer extends Context.Service< + PeerClientPairingIssuer, + { + readonly issue: ( + caller: EnvironmentAuth.McpClientSession, + request: PeerLinkClientPairingRequest, + ) => Effect.Effect< + PeerLinkClientPairingCredential, + PeerClientPairingRefused | EnvironmentAuth.ServerAuthInternalError + >; + } +>()("t3/peer/PeerClientPairing/PeerClientPairingIssuer") {} + +/** + * The linking side: gets a client of this environment a pairing credential for an environment + * this one links to, so the client can connect there itself. + */ +export class PeerClientPairing extends Context.Service< + PeerClientPairing, + { + readonly request: ( + input: PeerLinkClientPairingInput, + client: { + readonly sessionId: AuthSessionId; + readonly scopes: ReadonlyArray; + }, + ) => Effect.Effect; + } +>()("t3/peer/PeerClientPairing") {} + +const makeIssuer = Effect.gen(function* () { + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const serverSettings = yield* ServerSettings.ServerSettingsService; + const maxRuntimeMode = serverSettings.managedPolicy?.limits?.maxRuntimeMode; + const enabled = serverSettings.getSettings.pipe( + Effect.map((settings) => settings.linkedEnvironmentsEnabled), + Effect.orElseSucceed(() => false), + ); + + const issue: PeerClientPairingIssuer["Service"]["issue"] = Effect.fn( + "PeerClientPairingIssuer.issue", + )(function* (caller, request) { + if (!(yield* enabled)) { + return yield* new PeerClientPairingRefused({ + reason: "disabled", + message: PeerLinks.LINKED_ENVIRONMENTS_OFF, + }); + } + // A full-access link's agents already run as this machine's user and could run + // `t3 auth pairing create` themselves, so minting here adds no power. Any lower link would + // gain more than it holds, and so would one an administrator's ceiling holds below full access. + if ( + !caller.peerLink || + caller.access !== "full-access" || + (maxRuntimeMode !== undefined && maxRuntimeMode !== "full-access") + ) { + return yield* new PeerClientPairingRefused({ + reason: "not_a_full_access_link", + message: "Only a full-access link may pair a client here.", + }); + } + // Never more than the client holds where it asked, nor more than a pairing code grants. + const scopes = AuthStandardClientScopes.filter((scope) => request.scopes.includes(scope)); + if (scopes.length === 0) { + return yield* new PeerClientPairingRefused({ + reason: "no_scopes", + message: "The client holds no access a pairing could carry.", + }); + } + const via = caller.label.startsWith(PeerLinks.LINK_CLIENT_NAME_PREFIX) + ? caller.label.slice(PeerLinks.LINK_CLIENT_NAME_PREFIX.length) + : caller.label; + const clientLabel = Array.from(request.clientLabel).slice(0, CLIENT_LABEL_MAX_LENGTH).join(""); + const issued = yield* auth + .createPairingLink({ + scopes, + ttl: CLIENT_PAIRING_TTL, + label: `${clientLabel} · via ${via}`, + }) + .pipe( + Effect.catchTags({ + ManagedPolicyRefusedError: (error) => + Effect.fail(new PeerClientPairingRefused({ reason: "policy", message: error.message })), + }), + ); + return { credential: issued.credential, expiresAt: issued.expiresAt }; + }); + + return PeerClientPairingIssuer.of({ issue }); +}); + +export const layerIssuer = Layer.effect(PeerClientPairingIssuer, makeIssuer); + +const make = Effect.gen(function* () { + const links = yield* PeerLinks.PeerLinks; + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const httpClient = yield* HttpClient.HttpClient; + + /** What this environment's Connections calls the client that asked. */ + const clientLabelOf = (sessionId: AuthSessionId) => + auth.listClientSessions(sessionId).pipe( + Effect.map((sessions) => { + const client = sessions.find((session) => session.sessionId === sessionId)?.client; + return ( + client?.label ?? + ([client?.browser, client?.os].filter((part) => part !== undefined).join(" on ") || + "T3 Code client") + ); + }), + Effect.orElseSucceed(() => "T3 Code client"), + ); + + const request: PeerClientPairing["Service"]["request"] = Effect.fn("PeerClientPairing.request")( + function* (input, client) { + if (!(yield* links.enabled)) { + return yield* new PeerLinkError({ + reason: "disabled", + message: PeerLinks.LINKED_ENVIRONMENTS_OFF, + }); + } + const stored = yield* links.get(input.environmentId); + if (Option.isNone(stored)) { + return yield* new PeerLinkError({ + reason: "unknown_link", + message: "This environment is no longer linked to that one.", + }); + } + const { environmentId, label, urls, access, expiresAt } = stored.value; + if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) { + return yield* new PeerLinkError({ + reason: "expired", + message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`, + }); + } + const unsupported = ( + reason: Extract["reason"], + name = label, + ): PeerLinkClientPairingResult => ({ + type: "unsupported", + environmentId, + label: name, + urls, + reason, + }); + // The linked environment refuses this too; asking would only spend a round trip. + if (access !== "full-access") return unsupported("link_access"); + const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option); + if (Option.isNone(resolved)) return unsupported("unreachable"); + const peer = resolved.value; + if (peer.capabilities.linkClientPairing !== true) { + return unsupported("version", peer.link.label); + } + const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + ); + return yield* api.peerLink + .clientPairing({ + headers: { authorization: `Bearer ${peer.token}` }, + payload: { scopes: client.scopes, clientLabel: yield* clientLabelOf(client.sessionId) }, + }) + .pipe( + Effect.timeout(PeerLinks.probeTimeout(peer.url)), + Effect.map((issued): PeerLinkClientPairingResult => ({ + type: "credential", + environmentId, + label: peer.link.label, + urls, + credential: issued.credential, + expiresAt: issued.expiresAt, + })), + // No cause is logged or returned: a response this version cannot read may hold the credential. + Effect.catchTags({ + HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)), + TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)), + }), + Effect.orElseSucceed(() => unsupported("refused", peer.link.label)), + ); + }, + ); + + return PeerClientPairing.of({ request }); +}); + +export const layer = Layer.effect(PeerClientPairing, make); diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts index e95a6a7a427f1..ff09db6cbdf7f 100644 --- a/apps/server/src/peer/PeerLinks.testkit.ts +++ b/apps/server/src/peer/PeerLinks.testkit.ts @@ -32,6 +32,8 @@ import * as ServerHttp from "../http.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import * as Sqlite from "../persistence/Sqlite.ts"; +import * as PeerHttp from "./http.ts"; +import * as PeerClientPairing from "./PeerClientPairing.ts"; import * as PeerLinks from "./PeerLinks.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as PeerMcpClient from "./PeerMcpClient.ts"; @@ -39,7 +41,8 @@ import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; class PeerTestApi extends HttpApi.make("environment") .add(EnvironmentHttpApi.groups.metadata) - .add(EnvironmentHttpApi.groups.mcpOAuth) {} + .add(EnvironmentHttpApi.groups.mcpOAuth) + .add(EnvironmentHttpApi.groups.peerLink) {} export const descriptorOf = ( environmentId: string, @@ -58,6 +61,19 @@ export const descriptorOf = ( }, }); +/** An environment's own sessions and pairing links, on a database and secret store of its own. */ +export const layerEnvironmentAuth = (prefix: string) => + EnvironmentAuth.layer.pipe( + Layer.provide(ManagedPolicy.layerTest()), + Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })), + Layer.provide(Sqlite.layerMemory), + Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge(ServerEnvironment.layerIdentity), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + Layer.fresh, + ); + /** * The environment a link points at, as it runs: its descriptor, MCP OAuth, * and `/mcp` with `tools` behind the real client authenticator, on a real @@ -81,17 +97,7 @@ export const servePeer = ( getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)), getDescriptor: Ref.get(descriptor), }); - const authContext = yield* EnvironmentAuth.layer.pipe( - Layer.provide(ManagedPolicy.layerTest()), - Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })), - Layer.provide(Sqlite.layerMemory), - Layer.provideMerge(ServerSecretStore.layer), - Layer.provideMerge(ServerEnvironment.layerIdentity), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })), - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - Layer.fresh, - Layer.build, - ); + const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-peer-")); const layerRecordBearers = HttpRouter.middleware( (httpEffect) => Effect.gen(function* () { @@ -131,6 +137,7 @@ export const servePeer = ( ), ), ), + Layer.provide(PeerHttp.layer.pipe(Layer.provide(PeerClientPairing.layerIssuer))), Layer.provide(ServerHttp.layerServerEnvironmentHttpApi), Layer.provide(AuthHttp.layerAuthenticatedAuth), ), diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 4bf0653974e53..5325e5745c5d7 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -84,6 +84,9 @@ export interface ResolvedPeerLink { readonly capabilities: ExecutionEnvironmentCapabilities; } +/** What a link's session is called in the peer's Connections, before this environment's label. */ +export const LINK_CLIENT_NAME_PREFIX = "T3 Code · "; + export const LINKED_ENVIRONMENTS_OFF = "Linked environments is off on this machine. Turn it on in Settings → Labs."; @@ -552,7 +555,7 @@ const make = Effect.gen(function* () { message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`, }); } - const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`); + const issued = yield* signIn(primary, input, `${LINK_CLIENT_NAME_PREFIX}${self.label}`); const now = yield* DateTime.now; const linked: PeerLink = { environmentId: peer.environmentId, diff --git a/apps/server/src/peer/http.ts b/apps/server/src/peer/http.ts new file mode 100644 index 0000000000000..4baf9bebb9746 --- /dev/null +++ b/apps/server/src/peer/http.ts @@ -0,0 +1,76 @@ +import { + EnvironmentHttpApi, + EnvironmentHttpForbiddenError, + EnvironmentHttpInternalServerError, + EnvironmentHttpUnauthorizedError, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import { HttpServerRequest, HttpServerResponse } from "effect/http"; +import * as HttpEffect from "effect/http/HttpEffect"; +import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; + +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as PeerClientPairing from "./PeerClientPairing.ts"; + +// The response is a credential. +const noStore = HttpEffect.appendPreResponseHandler((_request, response) => + Effect.succeed( + HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }), + ), +); + +/** + * A link session is accepted on `/mcp` and here, nowhere else. This is a route and not an MCP + * tool so that no agent's tool list can hold it: thread credentials never authenticate here. + */ +export const layer = HttpApiBuilder.group( + EnvironmentHttpApi, + "peerLink", + Effect.fnUntraced(function* (handlers) { + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const issuer = yield* PeerClientPairing.PeerClientPairingIssuer; + return handlers.handle( + "clientPairing", + Effect.fn("environment.peerLink.clientPairing")(function* (args) { + const request = yield* HttpServerRequest.HttpServerRequest; + yield* noStore; + // A browser never holds a link's token; refuse one before reading credentials, as `/mcp` does. + if (request.headers.origin !== undefined) { + return yield* new EnvironmentHttpForbiddenError({ + message: "This route does not accept browser requests.", + }); + } + const caller = yield* auth.authenticateMcpClient(request).pipe( + Effect.mapError((error) => + EnvironmentAuth.isServerAuthCredentialError(error) + ? new EnvironmentHttpUnauthorizedError({ + message: "Only a linked environment's session is accepted here.", + }) + : new EnvironmentHttpInternalServerError({ + message: "The session could not be checked.", + }), + ), + ); + return yield* issuer.issue(caller, args.payload).pipe( + Effect.catchTags({ + PeerClientPairingRefused: (error) => + Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })), + }), + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) => + Effect.logError("Could not mint a client pairing for a linked environment.", { + cause, + }).pipe( + Effect.andThen( + Effect.fail( + new EnvironmentHttpInternalServerError({ + message: "The pairing could not be created.", + }), + ), + ), + ), + ), + ); + }), + ); + }), +); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d23f4ff7aa756..c838cfc2b7872 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -92,6 +92,8 @@ import * as TerminalManager from "./terminal/Manager.ts"; import * as McpHttpServer from "./mcp/McpHttpServer.ts"; import * as PeerForwarding from "./peer/PeerForwarding.ts"; import * as RemoteDelegation from "./peer/RemoteDelegation.ts"; +import * as PeerClientPairing from "./peer/PeerClientPairing.ts"; +import * as PeerClientPairingHttp from "./peer/http.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PeerMcpClient from "./peer/PeerMcpClient.ts"; @@ -850,6 +852,7 @@ const layerMakeRoutes = Layer.mergeAll( HttpApiBuilder.layer(EnvironmentHttpApi).pipe( Layer.provide(AuthHttp.layer), Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))), + Layer.provide(PeerClientPairingHttp.layer.pipe(Layer.provide(PeerClientPairing.layerIssuer))), Layer.provide(CloudHttp.layer), Layer.provide(OrchestrationHttp.layer), Layer.provide(PullRequestHttp.layer), @@ -901,7 +904,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(PreviewBrowser.layer), // Links to other environments, shared by clients (WebSocket) and agents (/mcp). Layer.provide( - Layer.merge(PeerForwarding.layer, PeerThreadRelay.layer).pipe( + Layer.mergeAll(PeerForwarding.layer, PeerThreadRelay.layer, PeerClientPairing.layer).pipe( Layer.provideMerge(PeerMcpClient.layer), Layer.provideMerge(PeerLinks.layer), ), diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 6da9e9ab69c66..12d6a1b601b3a 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -102,6 +102,7 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as RpcAuthorization from "./auth/RpcAuthorization.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts"; +import * as PeerClientPairing from "./peer/PeerClientPairing.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as PreviewManager from "./preview/Manager.ts"; @@ -850,6 +851,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(PeerLinks.PeerLinks)({}), Layer.mock(PeerLinkRequests.PeerLinkRequests)({}), Layer.mock(PeerThreadRelay.PeerThreadRelay)({}), + Layer.mock(PeerClientPairing.PeerClientPairing)({}), Layer.mock(PortScanner.PortDiscovery)({ trackAgent: () => () => undefined }), Layer.mock(PreviewManager.PreviewManager)({}), Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1035be8096a9c..3747e013a0193 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -6,6 +6,7 @@ import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; +import * as PeerClientPairing from "./peer/PeerClientPairing.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts"; @@ -1562,6 +1563,7 @@ export const layerWsRpc = ( const peerLinks = yield* PeerLinks.PeerLinks; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay; + const peerClientPairing = yield* PeerClientPairing.PeerClientPairing; const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; @@ -2720,6 +2722,8 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(peerThreadRelay.item(input)), ), + [WS_METHODS.peerLinksPairClient]: (input) => + peerClientPairing.request(input, currentSession), [WS_METHODS.peerLinksAnswerRequest]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(peerLinkRequests.answer(input)), @@ -3632,6 +3636,7 @@ export const layer = Layer.unwrap( const peerLinks = yield* PeerLinks.PeerLinks; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay; + const peerClientPairing = yield* PeerClientPairing.PeerClientPairing; const sql = yield* SqlClient.SqlClient; return HttpRouter.add( "GET", @@ -3733,6 +3738,7 @@ export const layer = Layer.unwrap( Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)), Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)), Layer.provide(Layer.succeed(PeerThreadRelay.PeerThreadRelay, peerThreadRelay)), + Layer.provide(Layer.succeed(PeerClientPairing.PeerClientPairing, peerClientPairing)), Layer.provide( SourceControlDiscovery.layer.pipe( Layer.provide( diff --git a/apps/web/src/components/chat/LinkedThreadPane.tsx b/apps/web/src/components/chat/LinkedThreadPane.tsx index 041c46a6bc52f..514e75b3c1e34 100644 --- a/apps/web/src/components/chat/LinkedThreadPane.tsx +++ b/apps/web/src/components/chat/LinkedThreadPane.tsx @@ -1,13 +1,17 @@ import { isLinkedThreadWorking, linkedThreadFailure } from "@t3tools/client-runtime/linked-thread"; import type { ScopedThreadRef } from "@t3tools/contracts"; import { T, useGT, useMessages, Var } from "gt-react"; -import { EyeIcon } from "lucide-react"; +import { EyeIcon, PlugIcon } from "lucide-react"; import { useState, type ReactNode } from "react"; import { useStableCallback } from "../../hooks/useStableCallback"; import { type LinkedThreadSurface, linkedThreadTitle } from "../../linkedThreadSurface"; import { useEnvironment } from "../../state/environments"; -import { linkedThreadItemSource, useLinkedThreadView } from "../../state/linkedThreadView"; +import { + linkedThreadItemSource, + useConnectLinkedEnvironment, + useLinkedThreadView, +} from "../../state/linkedThreadView"; import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert"; import { Button } from "../ui/button"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack"; @@ -18,6 +22,7 @@ import { ReadOnlyComposerStatus, } from "./ReadOnlyComposerBar"; import { Spinner } from "../ui/spinner"; +import { toastManager } from "../ui/toast"; import type { MessagesTimelineHistoryControls } from "./MessagesTimeline"; import { ReadOnlyThreadTimeline } from "./ReadOnlyThreadTimeline"; @@ -86,6 +91,63 @@ export function LinkedThreadPane(props: { const [turnItemSource] = useState(() => linkedThreadItemSource(surface)); const label = surface.label; const projection = view?.thread.projection ?? null; + const connection = useConnectLinkedEnvironment(panelRef, surface); + const connectState = connection.state; + const connecting = connectState.phase === "connecting"; + const connect = async () => { + const outcome = await connection.connect(); + if (outcome.type === "connected") { + toastManager.add({ + type: "success", + title: gt("Connected to {label}", { label }), + description: gt("This device is paired with it and can use its threads."), + }); + } + }; + const connectNotice: ComposerBannerStackItem | null = + connectState.phase === "connecting" + ? { + id: "connecting", + variant: "info", + icon: , + title: gt("Connecting to {label}…", { label }), + } + : connectState.phase === "unreachable" + ? { + id: "unreachable", + variant: "warning", + icon: , + title: gt("{label} is not reachable from this device", { label: connectState.label }), + description: gt( + "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.", + ), + } + : connectState.phase === "manual" + ? { + id: "manual", + variant: "info", + icon: , + title: gt("{label} needs a pairing code", { label: connectState.prefill.label }), + description: gt("Create one on it, then add it to this device as an environment."), + actions: ( + + ), + } + : null; + const connectAction = ( + + ); const failure = error === null ? null : linkedThreadFailure(error, { via, label }, m); const retryAction = failure?.retryable ? ( @@ -136,7 +198,13 @@ export function LinkedThreadPane(props: { )} - + ) : ( )} - + )} diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx index 1ff226b1bc03d..bdf0dae7cbf96 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx @@ -53,6 +53,7 @@ import { import { useEnvironmentQuery } from "~/state/query"; import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts"; import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments"; +import type { AddEnvironmentPrefill } from "~/state/linkedThreadView"; import { useAtomCommand } from "../../state/use-atom-command"; import { primaryServerKeybindingsAtom } from "~/state/server"; import { @@ -77,6 +78,7 @@ const sshHostSuggestionValue = (target: DesktopDiscoveredSshHost) => export function AddEnvironmentDialog({ open, + prefill = null, routeTarget, error, savedEnvironments, @@ -84,6 +86,8 @@ export function AddEnvironmentDialog({ onErrorChange, }: { readonly open: boolean; + /** A machine the user chose elsewhere to pair with; they supply only the pairing code. */ + readonly prefill?: AddEnvironmentPrefill | null; readonly routeTarget: EnvironmentPresentation | null; readonly error: string | null; readonly savedEnvironments: ReadonlyArray; @@ -119,7 +123,7 @@ export function AddEnvironmentDialog({ return keys; })(); const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote"); - const [savedBackendHost, setSavedBackendHost] = useState(""); + const [savedBackendHost, setSavedBackendHost] = useState(prefill?.host ?? ""); const [savedBackendPairingCode, setSavedBackendPairingCode] = useState(""); const [savedBackendSshHost, setSavedBackendSshHost] = useState(""); const [savedBackendSshUsername, setSavedBackendSshUsername] = useState(""); @@ -243,9 +247,10 @@ export function AddEnvironmentDialog({ return; } + const expected = routeTarget ?? prefill; const result = await connectPairing({ ...remotePairingInput, - ...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}), + ...(expected ? { expectedEnvironmentId: expected.environmentId } : {}), }); if (result._tag === "Failure") { if (!isAtomCommandInterrupted(result)) { @@ -683,14 +688,21 @@ export function AddEnvironmentDialog({ {routeTarget ? gt("Add a route to {environment}", { environment: routeTarget.label }) - : gt("Add Environment")} + : prefill + ? gt("Connect to {environment}", { environment: prefill.label }) + : gt("Add Environment")} {routeTarget ? gt( "Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine.", ) - : gt("Pair another environment to this client.")} + : prefill + ? gt( + "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.", + { environment: prefill.label }, + ) + : gt("Pair another environment to this client.")} diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 8f4d8778bcf80..1201b18e2a9a8 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -4,7 +4,7 @@ import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels import { SessionPermissions } from "./SessionPermissions"; import { useSearch } from "@tanstack/react-router"; import { ChevronRightIcon, EllipsisIcon } from "lucide-react"; -import { useAtomValue } from "@effect/atom-react"; +import { useAtom, useAtomValue } from "@effect/atom-react"; import { type ReactNode, useState } from "react"; import { T, useGT, useMessages, Var } from "gt-react"; import { @@ -50,6 +50,7 @@ import { ConnectDeviceApprovalSettings } from "./ConnectDeviceApprovalSettings"; import { EnvironmentIconMenu } from "./EnvironmentIconPicker"; import { FoldedSettingsSection } from "./FoldedSettingsSection"; import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings"; +import { addEnvironmentPrefillAtom } from "~/state/linkedThreadView"; import { usePeerLinkHosts } from "~/state/peerLinks"; import { LoadBalancingSettings } from "./LoadBalancingSettings"; import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings"; @@ -356,12 +357,15 @@ function ConnectionsSettingsContent({ const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false); const [routeTarget, setRouteTarget] = useState(null); const [savedBackendError, setSavedBackendError] = useState(null); + // Set by a read-only linked thread whose machine this client is about to pair with. + const [addPrefill, setAddPrefill] = useAtom(addEnvironmentPrefillAtom); const handleAddBackendDialogOpenChange = (open: boolean) => { setAddBackendDialogOpen(open); if (open) { setRouteTarget(null); } else { setSavedBackendError(null); + setAddPrefill(null); } }; const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] = @@ -1814,7 +1818,9 @@ function ConnectionsSettingsContent({ ) : null} onboarding.registerSsh(input)), ), }); + +export const reachesEnvironment = createRuntimeCommand(connectionAtomRuntime, { + label: "web:connection:reaches-environment", + execute: (input: { readonly host: string; readonly environmentId: EnvironmentId }) => + ConnectionOnboarding.ConnectionOnboarding.pipe( + Effect.flatMap((onboarding) => onboarding.reaches(input)), + ), +}); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index acdfd90c95938..6bf4e782aad8d 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "T3 Code auf {host} war zu beschäftigt, um zu antworten.", "5c5941732d5dfac6": "Die Kopplungsdaten sind ungültig.", "b8ca23ad7dda376e": "Diese Adresse führt zu {host}, einem anderen Rechner. Füge sie stattdessen als eigene Umgebung hinzu.", + "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.", "693cb5c4fb40f109": "Nur gespeicherte Bearer-Umgebungen können bearbeitet werden.", "5f5844b910cb1544": "Die gespeicherten Bearer-Zugangsdaten sind nicht verfügbar.", "51b0133f1ed3cf5c": "Die Bezeichnung der Umgebung darf nicht leer sein.", - "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.", "3aa15bfbe1920376": "Aktualisiere T3 Code auf {host} manuell; es kann sich nicht selbst aktualisieren.", "71907f57b7ec64d5": "{host} ist nicht mit einer kompatiblen T3-Code-Version zurückgekommen.", "e77ac580a4ddcd3b": "Verfügbar", @@ -3623,7 +3623,15 @@ "009e2ca841fdc1ef": "diese Umgebung", "8cb2e5692c4f05ab": "Öffne diesen Thread auf {label}, um diese Darstellung zu sehen.", "745a0b899008618c": "Frühere Runden konnten nicht geladen werden. Versuche es erneut.", + "4ab24e2807a0d82f": "Mit {label} verbunden", + "b797c7beccf2dc46": "Dieses Gerät ist damit gekoppelt und kann seine Threads verwenden.", + "d8c4a71a728fcf68": "Verbindung mit {label} wird hergestellt…", + "93e690821c726e13": "{label} ist von diesem Gerät aus nicht erreichbar", + "a5424a5a76e10aa3": "Tritt einem Netzwerk bei, in dem es sich befindet, etwa seinem Tailscale-Netzwerk, und versuche es erneut. Du kannst hier weiterlesen.", + "1942567fd95da447": "{label} benötigt einen Kopplungscode", + "0f62d432499e13f9": "Erstelle dort einen und füge es diesem Gerät als Umgebung hinzu.", "0014ce0aaf1bd68a": "Schreibgeschützt", + "10ca916def8211d4": "Code eingeben", "d0bda35aeec66684": [ "Wird von ", { @@ -3634,6 +3642,7 @@ " gelesen …" ], "c3e8cd9bf44e2f43": "Angezeigt wird, was zuvor gelesen wurde.", + "a446e3bda256c2b3": "Verbinden, um zu interagieren", "eb6e0584cf4a2a1d": "Sprache: {language}", "d76c606a3c519b78": "Zeilenumbruch deaktivieren", "2b683498cee8c8a7": "Zeilen umbrechen", @@ -7303,8 +7312,10 @@ "53c162d8868a1d0e": "Umgebung hinzufügen", "53339e47accf021a": "Hosts durchsuchen oder devbox eingeben", "d808738388ab80b0": "Route zu {environment} hinzufügen", + "8a333daf9b7fd03f": "Mit {environment} verbinden", "7662025844bf543f": "Umgebung hinzufügen", "65b1d784a5e84254": "Kopple diesen Rechner erneut über eine andere Adresse, etwa seinen Tailscale-Namen. Er wird den vorhandenen Routen hinzugefügt, statt einen zweiten Rechner anzulegen.", + "e1cb1c8599e84e26": "Erstelle auf {environment} einen Kopplungscode, in dessen Einstellungen → Freigabe & Zugriff oder mit `t3 auth pairing create`, und gib ihn hier ein.", "1bea4864d46d70d0": "Eine weitere Umgebung mit diesem Client koppeln.", "9b24ef052b321e57": "Gib einen Backend-Host und einen Kopplungscode ein.", "3e20f17f71edf0ad": "Lokale SSH-Konfiguration, Agent und Tunnel für das Backend verwenden.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index bf9125e821f5d..3ed9b5b0b09ca 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "T3 Code on {host} was too busy to answer.", "5c5941732d5dfac6": "The pairing details are invalid.", "b8ca23ad7dda376e": "That address reaches {host}, a different machine. Add it as its own environment instead.", + "0c0150a90b582a7a": "The environment URL is invalid.", "693cb5c4fb40f109": "Only saved bearer environments can be edited.", "5f5844b910cb1544": "The saved bearer credential is unavailable.", "51b0133f1ed3cf5c": "Environment label cannot be empty.", - "0c0150a90b582a7a": "The environment URL is invalid.", "3aa15bfbe1920376": "Update T3 Code on {host} manually; it cannot update itself.", "71907f57b7ec64d5": "{host} did not come back on a compatible T3 Code version.", "e77ac580a4ddcd3b": "Available", @@ -3622,7 +3622,15 @@ "009e2ca841fdc1ef": "this environment", "8cb2e5692c4f05ab": "Open this thread on {label} to see this visual.", "745a0b899008618c": "Could not load earlier turns. Try again.", + "4ab24e2807a0d82f": "Connected to {label}", + "b797c7beccf2dc46": "This device is paired with it and can use its threads.", + "d8c4a71a728fcf68": "Connecting to {label}…", + "93e690821c726e13": "{label} is not reachable from this device", + "a5424a5a76e10aa3": "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.", + "1942567fd95da447": "{label} needs a pairing code", + "0f62d432499e13f9": "Create one on it, then add it to this device as an environment.", "0014ce0aaf1bd68a": "Read-only", + "10ca916def8211d4": "Enter code", "d0bda35aeec66684": [ "Reading from ", { @@ -3633,6 +3641,7 @@ "…" ], "c3e8cd9bf44e2f43": "Showing what was read before.", + "a446e3bda256c2b3": "Connect to interact", "eb6e0584cf4a2a1d": "Language: {language}", "d76c606a3c519b78": "Disable line wrap", "2b683498cee8c8a7": "Wrap lines", @@ -7311,8 +7320,10 @@ "53c162d8868a1d0e": "Add environment", "53339e47accf021a": "Search hosts or type devbox", "d808738388ab80b0": "Add a route to {environment}", + "8a333daf9b7fd03f": "Connect to {environment}", "7662025844bf543f": "Add Environment", "65b1d784a5e84254": "Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine.", + "e1cb1c8599e84e26": "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.", "1bea4864d46d70d0": "Pair another environment to this client.", "9b24ef052b321e57": "Enter a backend host and pairing code.", "3e20f17f71edf0ad": "Use local SSH config, agent, and tunnels for the backend.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index e0f52492df584..dd9280abac65f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "T3 Code en {host} estaba demasiado ocupado para responder.", "5c5941732d5dfac6": "Los datos de emparejamiento no son válidos.", "b8ca23ad7dda376e": "Esa dirección lleva a {host}, otra máquina. Añádela como un entorno propio.", + "0c0150a90b582a7a": "La URL del entorno no es válida.", "693cb5c4fb40f109": "Solo se pueden editar los entornos bearer guardados.", "5f5844b910cb1544": "La credencial bearer guardada no está disponible.", "51b0133f1ed3cf5c": "La etiqueta del entorno no puede estar vacía.", - "0c0150a90b582a7a": "La URL del entorno no es válida.", "3aa15bfbe1920376": "Actualiza T3 Code en {host} manualmente; no puede actualizarse solo.", "71907f57b7ec64d5": "{host} no volvió con una versión compatible de T3 Code.", "e77ac580a4ddcd3b": "Disponible", @@ -3622,7 +3622,15 @@ "009e2ca841fdc1ef": "este entorno", "8cb2e5692c4f05ab": "Abre este hilo en {label} para ver este elemento visual.", "745a0b899008618c": "No se pudieron cargar los turnos anteriores. Vuelve a intentarlo.", + "4ab24e2807a0d82f": "Conectado a {label}", + "b797c7beccf2dc46": "Este dispositivo está emparejado con él y puede usar sus hilos.", + "d8c4a71a728fcf68": "Conectando con {label}…", + "93e690821c726e13": "No se puede acceder a {label} desde este dispositivo", + "a5424a5a76e10aa3": "Únete a una red en la que esté, como su red de Tailscale, y vuelve a intentarlo. Puedes seguir leyendo aquí.", + "1942567fd95da447": "{label} necesita un código de emparejamiento", + "0f62d432499e13f9": "Crea uno allí y añádelo a este dispositivo como entorno.", "0014ce0aaf1bd68a": "Solo lectura", + "10ca916def8211d4": "Introducir código", "d0bda35aeec66684": [ "Leyendo desde ", { @@ -3633,6 +3641,7 @@ "…" ], "c3e8cd9bf44e2f43": "Se muestra lo que se leyó antes.", + "a446e3bda256c2b3": "Conectar para interactuar", "eb6e0584cf4a2a1d": "Lenguaje: {language}", "d76c606a3c519b78": "Desactivar ajuste de línea", "2b683498cee8c8a7": "Ajustar líneas", @@ -7304,8 +7313,10 @@ "53c162d8868a1d0e": "Añadir entorno", "53339e47accf021a": "Busca hosts o escribe devbox", "d808738388ab80b0": "Añadir una ruta a {environment}", + "8a333daf9b7fd03f": "Conectar con {environment}", "7662025844bf543f": "Añadir entorno", "65b1d784a5e84254": "Vuelve a emparejar esta máquina con otra dirección, como su nombre de Tailscale. Se une a las rutas existentes en lugar de añadir una segunda máquina.", + "e1cb1c8599e84e26": "Crea un código de emparejamiento en {environment}, en sus Ajustes → Compartir y acceso o con `t3 auth pairing create`, e introdúcelo aquí.", "1bea4864d46d70d0": "Empareja otro entorno con este cliente.", "9b24ef052b321e57": "Introduce un host de backend y un código de emparejamiento.", "3e20f17f71edf0ad": "Usa la configuración SSH local, el agente y los túneles para el backend.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 97cd5bc681a6f..f4c23672f0cef 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "T3 Code sur {host} était trop occupé pour répondre.", "5c5941732d5dfac6": "Les informations d’appairage ne sont pas valides.", "b8ca23ad7dda376e": "Cette adresse mène à {host}, une autre machine. Ajoutez-la plutôt comme environnement distinct.", + "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.", "693cb5c4fb40f109": "Seuls les environnements bearer enregistrés peuvent être modifiés.", "5f5844b910cb1544": "Les identifiants bearer enregistrés ne sont pas disponibles.", "51b0133f1ed3cf5c": "Le libellé de l’environnement ne peut pas être vide.", - "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.", "3aa15bfbe1920376": "Mettez à jour T3 Code sur {host} manuellement ; il ne peut pas se mettre à jour seul.", "71907f57b7ec64d5": "{host} n’est pas revenu sur une version compatible de T3 Code.", "e77ac580a4ddcd3b": "Disponible", @@ -3622,7 +3622,15 @@ "009e2ca841fdc1ef": "cet environnement", "8cb2e5692c4f05ab": "Ouvrez ce fil sur {label} pour voir ce visuel.", "745a0b899008618c": "Impossible de charger les tours précédents. Réessayez.", + "4ab24e2807a0d82f": "Connecté à {label}", + "b797c7beccf2dc46": "Cet appareil y est appairé et peut utiliser ses fils.", + "d8c4a71a728fcf68": "Connexion à {label}…", + "93e690821c726e13": "{label} n’est pas accessible depuis cet appareil", + "a5424a5a76e10aa3": "Rejoignez un réseau sur lequel il se trouve, comme son réseau Tailscale, puis réessayez. Vous pouvez continuer à lire ici.", + "1942567fd95da447": "{label} nécessite un code d’appairage", + "0f62d432499e13f9": "Créez-en un dessus, puis ajoutez-le à cet appareil comme environnement.", "0014ce0aaf1bd68a": "Lecture seule", + "10ca916def8211d4": "Saisir le code", "d0bda35aeec66684": [ "Lecture depuis ", { @@ -3633,6 +3641,7 @@ "…" ], "c3e8cd9bf44e2f43": "Affichage de ce qui a été lu auparavant.", + "a446e3bda256c2b3": "Se connecter pour interagir", "eb6e0584cf4a2a1d": "Langage : {language}", "d76c606a3c519b78": "Désactiver le retour à la ligne", "2b683498cee8c8a7": "Retour à la ligne", @@ -7305,8 +7314,10 @@ "53c162d8868a1d0e": "Ajouter un environnement", "53339e47accf021a": "Rechercher des hôtes ou saisir devbox", "d808738388ab80b0": "Ajouter une route vers {environment}", + "8a333daf9b7fd03f": "Se connecter à {environment}", "7662025844bf543f": "Ajouter un environnement", "65b1d784a5e84254": "Appairez à nouveau cette machine via une autre adresse, comme son nom Tailscale. Elle rejoint les routes existantes au lieu d’ajouter une deuxième machine.", + "e1cb1c8599e84e26": "Créez un code d’appairage sur {environment}, dans ses Paramètres → Partage et accès ou avec `t3 auth pairing create`, puis saisissez-le ici.", "1bea4864d46d70d0": "Appairez un autre environnement à ce client.", "9b24ef052b321e57": "Saisissez un hôte de backend et un code d’appairage.", "3e20f17f71edf0ad": "Utiliser la configuration SSH locale, l’agent et les tunnels pour le backend.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 43ee223b82fe4..7e2d260d010ba 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "{host} の T3 Code はビジー状態で応答できませんでした。", "5c5941732d5dfac6": "ペアリングの詳細が無効です。", "b8ca23ad7dda376e": "そのアドレスは別のマシンである {host} につながります。代わりに独立した環境として追加してください。", + "0c0150a90b582a7a": "環境の URL が無効です。", "693cb5c4fb40f109": "編集できるのは保存済みのベアラー環境のみです。", "5f5844b910cb1544": "保存済みのベアラー資格情報は利用できません。", "51b0133f1ed3cf5c": "環境のラベルは空にできません。", - "0c0150a90b582a7a": "環境の URL が無効です。", "3aa15bfbe1920376": "{host} の T3 Code は自動で更新できないため、手動で更新してください。", "71907f57b7ec64d5": "{host} は互換性のある T3 Code のバージョンで復帰しませんでした。", "e77ac580a4ddcd3b": "利用可能", @@ -3617,7 +3617,15 @@ "009e2ca841fdc1ef": "この環境", "8cb2e5692c4f05ab": "このビジュアルを見るには、{label} でこのスレッドを開いてください。", "745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。", + "4ab24e2807a0d82f": "{label} に接続しました", + "b797c7beccf2dc46": "このデバイスはペアリング済みで、そのスレッドを利用できます。", + "d8c4a71a728fcf68": "{label} に接続しています…", + "93e690821c726e13": "このデバイスから {label} に接続できません", + "a5424a5a76e10aa3": "Tailscale ネットワークなど、そのマシンが接続しているネットワークに参加してから、もう一度お試しください。ここでは引き続き閲覧できます。", + "1942567fd95da447": "{label} にはペアリングコードが必要です", + "0f62d432499e13f9": "そのマシンで作成し、このデバイスに環境として追加してください。", "0014ce0aaf1bd68a": "読み取り専用", + "10ca916def8211d4": "コードを入力", "d0bda35aeec66684": [ "読み取り中: ", { @@ -3628,6 +3636,7 @@ "…" ], "c3e8cd9bf44e2f43": "以前に読み取った内容を表示しています。", + "a446e3bda256c2b3": "接続して操作する", "eb6e0584cf4a2a1d": "言語: {language}", "d76c606a3c519b78": "行の折り返しを無効にする", "2b683498cee8c8a7": "行を折り返す", @@ -7271,8 +7280,10 @@ "53c162d8868a1d0e": "環境を追加", "53339e47accf021a": "ホストを検索、または devbox と入力", "d808738388ab80b0": "{environment} へのルートを追加", + "8a333daf9b7fd03f": "{environment} に接続", "7662025844bf543f": "環境を追加", "65b1d784a5e84254": "このマシンを別のアドレス (Tailscale の名前など) でもう一度ペアリングします。2 台目のマシンとして追加されるのではなく、既存のルートに加わります。", + "e1cb1c8599e84e26": "{environment} の設定 → 共有とアクセス、または `t3 auth pairing create` でペアリングコードを作成し、ここに入力してください。", "1bea4864d46d70d0": "このクライアントに別の環境をペアリングします。", "9b24ef052b321e57": "バックエンドのホストとペアリングコードを入力してください。", "3e20f17f71edf0ad": "バックエンドにはローカルの SSH 構成、エージェント、トンネルを使用します。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 0536a957dcf87..6e9795c9f0fd6 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "{host}의 T3 Code가 너무 바빠서 응답하지 못했습니다.", "5c5941732d5dfac6": "페어링 정보가 올바르지 않습니다.", "b8ca23ad7dda376e": "이 주소는 다른 머신인 {host}에 연결됩니다. 대신 별도의 환경으로 추가하세요.", + "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.", "693cb5c4fb40f109": "저장된 bearer 환경만 편집할 수 있습니다.", "5f5844b910cb1544": "저장된 bearer 자격 증명을 사용할 수 없습니다.", "51b0133f1ed3cf5c": "환경 레이블은 비워 둘 수 없습니다.", - "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.", "3aa15bfbe1920376": "{host}의 T3 Code는 스스로 업데이트할 수 없으니 직접 업데이트하세요.", "71907f57b7ec64d5": "{host}이(가) 호환되는 T3 Code 버전으로 돌아오지 않았습니다.", "e77ac580a4ddcd3b": "사용 가능", @@ -3617,7 +3617,15 @@ "009e2ca841fdc1ef": "이 환경", "8cb2e5692c4f05ab": "이 시각 자료를 보려면 {label}에서 이 스레드를 여세요.", "745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.", + "4ab24e2807a0d82f": "{label}에 연결됨", + "b797c7beccf2dc46": "이 기기가 페어링되어 해당 스레드를 사용할 수 있습니다.", + "d8c4a71a728fcf68": "{label}에 연결하는 중…", + "93e690821c726e13": "이 기기에서 {label}에 연결할 수 없습니다", + "a5424a5a76e10aa3": "Tailscale 네트워크처럼 해당 머신이 연결된 네트워크에 참여한 후 다시 시도하세요. 여기에서 계속 읽을 수 있습니다.", + "1942567fd95da447": "{label}에 페어링 코드가 필요합니다", + "0f62d432499e13f9": "해당 머신에서 코드를 만든 다음 이 기기에 환경으로 추가하세요.", "0014ce0aaf1bd68a": "읽기 전용", + "10ca916def8211d4": "코드 입력", "d0bda35aeec66684": [ "읽는 중: ", { @@ -3628,6 +3636,7 @@ "…" ], "c3e8cd9bf44e2f43": "이전에 읽은 내용을 표시하고 있습니다.", + "a446e3bda256c2b3": "연결하여 상호작용", "eb6e0584cf4a2a1d": "언어: {language}", "d76c606a3c519b78": "줄 바꿈 끄기", "2b683498cee8c8a7": "줄 바꿈", @@ -7274,8 +7283,10 @@ "53c162d8868a1d0e": "환경 추가", "53339e47accf021a": "호스트 검색 또는 devbox 입력", "d808738388ab80b0": "{environment}에 경로 추가", + "8a333daf9b7fd03f": "{environment}에 연결", "7662025844bf543f": "환경 추가", "65b1d784a5e84254": "Tailscale 이름 같은 다른 주소로 이 머신을 다시 페어링하세요. 두 번째 머신을 추가하는 대신 기존 경로에 합쳐집니다.", + "e1cb1c8599e84e26": "{environment}의 설정 → 공유 및 액세스에서 또는 `t3 auth pairing create`로 페어링 코드를 만든 다음 여기에 입력하세요.", "1bea4864d46d70d0": "이 클라이언트에 다른 환경을 페어링합니다.", "9b24ef052b321e57": "백엔드 호스트와 페어링 코드를 입력하세요.", "3e20f17f71edf0ad": "백엔드에 로컬 SSH 구성, 에이전트, 터널을 사용합니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5003e05f792b7..dc0dbfcad030c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "O T3 Code em {host} estava ocupado demais para responder.", "5c5941732d5dfac6": "Os detalhes de pareamento são inválidos.", "b8ca23ad7dda376e": "Esse endereço leva a {host}, outra máquina. Adicione-a como um ambiente próprio.", + "0c0150a90b582a7a": "A URL do ambiente é inválida.", "693cb5c4fb40f109": "Só é possível editar ambientes bearer salvos.", "5f5844b910cb1544": "A credencial bearer salva não está disponível.", "51b0133f1ed3cf5c": "O rótulo do ambiente não pode ficar vazio.", - "0c0150a90b582a7a": "A URL do ambiente é inválida.", "3aa15bfbe1920376": "Atualize o T3 Code em {host} manualmente; ele não consegue se atualizar sozinho.", "71907f57b7ec64d5": "{host} não voltou em uma versão compatível do T3 Code.", "e77ac580a4ddcd3b": "Disponível", @@ -3622,7 +3622,15 @@ "009e2ca841fdc1ef": "este ambiente", "8cb2e5692c4f05ab": "Abra este thread em {label} para ver este visual.", "745a0b899008618c": "Não foi possível carregar os turnos anteriores. Tente novamente.", + "4ab24e2807a0d82f": "Conectado a {label}", + "b797c7beccf2dc46": "Este dispositivo está pareado com ele e pode usar suas threads.", + "d8c4a71a728fcf68": "Conectando a {label}…", + "93e690821c726e13": "{label} não está acessível a partir deste dispositivo", + "a5424a5a76e10aa3": "Entre em uma rede em que ele esteja, como a rede Tailscale dele, e tente novamente. Você pode continuar lendo aqui.", + "1942567fd95da447": "{label} precisa de um código de pareamento", + "0f62d432499e13f9": "Crie um nele e adicione-o a este dispositivo como ambiente.", "0014ce0aaf1bd68a": "Somente leitura", + "10ca916def8211d4": "Inserir código", "d0bda35aeec66684": [ "Lendo de ", { @@ -3633,6 +3641,7 @@ "…" ], "c3e8cd9bf44e2f43": "Mostrando o que foi lido antes.", + "a446e3bda256c2b3": "Conectar para interagir", "eb6e0584cf4a2a1d": "Linguagem: {language}", "d76c606a3c519b78": "Desativar quebra de linha", "2b683498cee8c8a7": "Quebrar linhas", @@ -7304,8 +7313,10 @@ "53c162d8868a1d0e": "Adicionar ambiente", "53339e47accf021a": "Pesquise hosts ou digite devbox", "d808738388ab80b0": "Adicionar uma rota para {environment}", + "8a333daf9b7fd03f": "Conectar a {environment}", "7662025844bf543f": "Adicionar ambiente", "65b1d784a5e84254": "Pareie esta máquina novamente por outro endereço, como o nome dela no Tailscale. Ele se junta às rotas existentes em vez de adicionar uma segunda máquina.", + "e1cb1c8599e84e26": "Crie um código de pareamento em {environment}, em Configurações → Compartilhamento e acesso ou com `t3 auth pairing create`, e insira-o aqui.", "1bea4864d46d70d0": "Parear outro ambiente com este cliente.", "9b24ef052b321e57": "Informe o host do backend e um código de pareamento.", "3e20f17f71edf0ad": "Usa a configuração SSH local, o agent e túneis para o backend.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 9d9c58696fd16..31b603d4b2b59 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "T3 Code на {host} был слишком занят, чтобы ответить.", "5c5941732d5dfac6": "Данные сопряжения недействительны.", "b8ca23ad7dda376e": "Этот адрес ведёт к {host}, другому компьютеру. Добавьте его как отдельное окружение.", + "0c0150a90b582a7a": "URL окружения недействителен.", "693cb5c4fb40f109": "Изменять можно только сохранённые окружения с bearer-токеном.", "5f5844b910cb1544": "Сохранённые bearer-учётные данные недоступны.", "51b0133f1ed3cf5c": "Название окружения не может быть пустым.", - "0c0150a90b582a7a": "URL окружения недействителен.", "3aa15bfbe1920376": "Обновите T3 Code на {host} вручную: он не может обновиться сам.", "71907f57b7ec64d5": "{host} не вернулся с совместимой версией T3 Code.", "e77ac580a4ddcd3b": "Доступно", @@ -3622,7 +3622,15 @@ "009e2ca841fdc1ef": "это окружение", "8cb2e5692c4f05ab": "Откройте этот тред на {label}, чтобы увидеть это визуальное представление.", "745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.", + "4ab24e2807a0d82f": "Подключено к {label}", + "b797c7beccf2dc46": "Это устройство сопряжено с ним и может работать с его тредами.", + "d8c4a71a728fcf68": "Подключение к {label}…", + "93e690821c726e13": "{label} недоступно с этого устройства", + "a5424a5a76e10aa3": "Подключитесь к сети, в которой оно находится, например к его сети Tailscale, и повторите попытку. Здесь можно продолжать чтение.", + "1942567fd95da447": "Для {label} нужен код сопряжения", + "0f62d432499e13f9": "Создайте его там и добавьте эту машину на устройство как окружение.", "0014ce0aaf1bd68a": "Только чтение", + "10ca916def8211d4": "Ввести код", "d0bda35aeec66684": [ "Чтение с ", { @@ -3633,6 +3641,7 @@ "…" ], "c3e8cd9bf44e2f43": "Показано то, что было прочитано раньше.", + "a446e3bda256c2b3": "Подключиться для взаимодействия", "eb6e0584cf4a2a1d": "Язык: {language}", "d76c606a3c519b78": "Отключить перенос строк", "2b683498cee8c8a7": "Переносить строки", @@ -7304,8 +7313,10 @@ "53c162d8868a1d0e": "Добавить окружение", "53339e47accf021a": "Поиск хостов или введите devbox", "d808738388ab80b0": "Добавить маршрут к {environment}", + "8a333daf9b7fd03f": "Подключиться к {environment}", "7662025844bf543f": "Добавить окружение", "65b1d784a5e84254": "Выполните сопряжение с этой машиной заново по другому адресу, например по имени в Tailscale. Он добавится к существующим маршрутам, а не создаст вторую машину.", + "e1cb1c8599e84e26": "Создайте код сопряжения на {environment} в разделе «Настройки → Общий доступ» или командой `t3 auth pairing create` и введите его здесь.", "1bea4864d46d70d0": "Выполните сопряжение этого клиента с другим окружением.", "9b24ef052b321e57": "Введите хост бэкенда и код сопряжения.", "3e20f17f71edf0ad": "Использовать локальные конфигурацию SSH, агент и туннели для бэкенда.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 0a645b45857ae..a0f86175e48e3 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "T3 Code på {host} var för upptagen för att svara.", "5c5941732d5dfac6": "Uppgifterna för parkopplingen är ogiltiga.", "b8ca23ad7dda376e": "Den adressen leder till {host}, en annan dator. Lägg till den som en egen miljö i stället.", + "0c0150a90b582a7a": "Miljöns URL är ogiltig.", "693cb5c4fb40f109": "Bara sparade bearer-miljöer kan redigeras.", "5f5844b910cb1544": "Den sparade bearer-uppgiften är inte tillgänglig.", "51b0133f1ed3cf5c": "Miljöns etikett får inte vara tom.", - "0c0150a90b582a7a": "Miljöns URL är ogiltig.", "3aa15bfbe1920376": "Uppdatera T3 Code på {host} manuellt; det kan inte uppdatera sig självt.", "71907f57b7ec64d5": "{host} kom inte tillbaka med en kompatibel version av T3 Code.", "e77ac580a4ddcd3b": "Tillgänglig", @@ -3622,7 +3622,15 @@ "009e2ca841fdc1ef": "den här miljön", "8cb2e5692c4f05ab": "Öppna den här tråden på {label} för att se den här visualiseringen.", "745a0b899008618c": "Kunde inte läsa in tidigare omgångar. Försök igen.", + "4ab24e2807a0d82f": "Ansluten till {label}", + "b797c7beccf2dc46": "Den här enheten är parkopplad med den och kan använda dess trådar.", + "d8c4a71a728fcf68": "Ansluter till {label}…", + "93e690821c726e13": "{label} kan inte nås från den här enheten", + "a5424a5a76e10aa3": "Anslut till ett nätverk som den finns på, till exempel dess Tailscale-nätverk, och försök igen. Du kan fortsätta läsa här.", + "1942567fd95da447": "{label} behöver en parkopplingskod", + "0f62d432499e13f9": "Skapa en där och lägg till den på den här enheten som en miljö.", "0014ce0aaf1bd68a": "Skrivskyddad", + "10ca916def8211d4": "Ange kod", "d0bda35aeec66684": [ "Läser från ", { @@ -3633,6 +3641,7 @@ "…" ], "c3e8cd9bf44e2f43": "Visar det som lästes tidigare.", + "a446e3bda256c2b3": "Anslut för att interagera", "eb6e0584cf4a2a1d": "Språk: {language}", "d76c606a3c519b78": "Inaktivera radbrytning", "2b683498cee8c8a7": "Bryt rader", @@ -7310,8 +7319,10 @@ "53c162d8868a1d0e": "Lägg till miljö", "53339e47accf021a": "Sök värdar eller skriv devbox", "d808738388ab80b0": "Lägg till en rutt till {environment}", + "8a333daf9b7fd03f": "Anslut till {environment}", "7662025844bf543f": "Lägg till miljö", "65b1d784a5e84254": "Parkoppla den här datorn igen via en annan adress, till exempel dess Tailscale-namn. Den ansluter till de befintliga rutterna i stället för att lägga till en andra dator.", + "e1cb1c8599e84e26": "Skapa en parkopplingskod på {environment}, i dess Inställningar → Delning och åtkomst eller med `t3 auth pairing create`, och ange den här.", "1bea4864d46d70d0": "Parkoppla en annan miljö med den här klienten.", "9b24ef052b321e57": "Ange en backend-värd och en parkopplingskod.", "3e20f17f71edf0ad": "Använd lokal SSH-konfiguration, agent och tunnlar för backenden.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index b933baac631c6..312065925ba94 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -458,10 +458,10 @@ "93e37fedae7eaa5b": "{host} 上的 T3 Code 太忙,未能响应。", "5c5941732d5dfac6": "配对信息无效。", "b8ca23ad7dda376e": "该地址指向另一台机器 {host}。请将其添加为独立环境。", + "0c0150a90b582a7a": "环境 URL 无效。", "693cb5c4fb40f109": "只能编辑已保存的 bearer 环境。", "5f5844b910cb1544": "已保存的 bearer 凭据不可用。", "51b0133f1ed3cf5c": "环境名称不能为空。", - "0c0150a90b582a7a": "环境 URL 无效。", "3aa15bfbe1920376": "请手动更新 {host} 上的 T3 Code;它无法自行更新。", "71907f57b7ec64d5": "{host} 重启后未运行兼容的 T3 Code 版本。", "e77ac580a4ddcd3b": "可用", @@ -3627,7 +3627,15 @@ "009e2ca841fdc1ef": "此环境", "8cb2e5692c4f05ab": "在 {label} 上打开此会话即可查看此可视内容。", "745a0b899008618c": "无法加载更早的对话。请重试。", + "4ab24e2807a0d82f": "已连接到 {label}", + "b797c7beccf2dc46": "此设备已与其配对,可以使用其中的会话。", + "d8c4a71a728fcf68": "正在连接 {label}…", + "93e690821c726e13": "无法从此设备访问 {label}", + "a5424a5a76e10aa3": "请加入它所在的网络(例如其 Tailscale 网络),然后重试。你仍可在此继续阅读。", + "1942567fd95da447": "{label} 需要配对码", + "0f62d432499e13f9": "在该机器上创建配对码,然后将其作为环境添加到此设备。", "0014ce0aaf1bd68a": "只读", + "10ca916def8211d4": "输入配对码", "d0bda35aeec66684": [ "正在从 ", { @@ -3638,6 +3646,7 @@ " 读取…" ], "c3e8cd9bf44e2f43": "正在显示之前读取的内容。", + "a446e3bda256c2b3": "连接以进行交互", "eb6e0584cf4a2a1d": "语言:{language}", "d76c606a3c519b78": "取消自动换行", "2b683498cee8c8a7": "自动换行", @@ -7319,8 +7328,10 @@ "53c162d8868a1d0e": "添加环境", "53339e47accf021a": "搜索主机或输入 devbox", "d808738388ab80b0": "为 {environment} 添加线路", + "8a333daf9b7fd03f": "连接到 {environment}", "7662025844bf543f": "添加环境", "65b1d784a5e84254": "使用其他地址(例如 Tailscale 名称)再次配对此机器。该地址将加入现有线路,不会重复添加机器。", + "e1cb1c8599e84e26": "在 {environment} 的设置 → 共享与访问中或使用 `t3 auth pairing create` 创建配对码,然后在此输入。", "1bea4864d46d70d0": "将其他环境与此客户端配对。", "9b24ef052b321e57": "输入后端主机和配对码。", "3e20f17f71edf0ad": "使用本地 SSH 配置、认证代理和隧道连接后端。", diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index 63145c73119d6..7dfc41a9f617f 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -1,6 +1,7 @@ -import { useAtomValue } from "@effect/atom-react"; -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { useAtom, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { + connectLinkedEnvironment, type LinkedThreadOpen, resolveLinkedThreadOpen, } from "@t3tools/client-runtime/linked-thread"; @@ -10,11 +11,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; import { useRightPanelStore } from "../rightPanelStore"; +import { connectPairing, reachesEnvironment } from "../connection/onboarding"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; import { buildThreadRouteParams } from "../threadRoutes"; import { useEnvironment } from "./environments"; import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks"; import { useEnvironmentQuery } from "./query"; +import { useAtomCommand } from "./use-atom-command"; /** * How a click opens a thread that the thread `panelRef` says is on a linked environment: in place @@ -127,6 +130,108 @@ export function useLinkedThreadView( }; } +/** A linked environment the add-environment dialog opens for, with what is known about it filled in. */ +export interface AddEnvironmentPrefill { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly host: string | null; +} + +export const addEnvironmentPrefillAtom = Atom.make(null).pipe( + Atom.withLabel("add-environment-prefill"), +); + +export type LinkedEnvironmentConnectState = + | { readonly phase: "idle" | "connecting" } + | { readonly phase: "unreachable"; readonly label: string } + /** The user pairs with a code of their own; `prefill` reopens the dialog for it. */ + | { readonly phase: "manual"; readonly prefill: AddEnvironmentPrefill }; + +// Kept like the tab's reads, so the tab still says what happened after a visit to Settings. +const linkedEnvironmentConnectAtom = Atom.family((key: string) => + Atom.make({ phase: "idle" }).pipe( + Atom.setIdleTTL(5 * 60_000), + Atom.withLabel(`linked-environment-connect:${key}`), + ), +); + +/** + * Connects this client to the environment `surface`'s thread lives in. One step when the linking + * environment can get a pairing for this client: the thread then opens there and the tab closes. + * Otherwise the add-environment dialog opens for that machine. + */ +export function useConnectLinkedEnvironment( + panelRef: ScopedThreadRef, + surface: LinkedThreadSurface, +) { + const navigate = useNavigate(); + const setPrefill = useAtomSet(addEnvironmentPrefillAtom); + const mayPair = useAtomValue( + peerLinkEnvironment.pairClient.permissionAtom(surface.viaEnvironmentId), + ); + const quiet = { reportFailure: false, reportDefect: false } as const; + const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet); + const reaches = useAtomCommand(reachesEnvironment, quiet); + const pair = useAtomCommand(connectPairing, quiet); + const [state, setState] = useAtom( + linkedEnvironmentConnectAtom(`${scopedThreadKey(panelRef)}:${surface.id}`), + ); + const addWithCode = (prefill: AddEnvironmentPrefill) => { + setPrefill(prefill); + void navigate({ to: "/settings/connections" }); + }; + const connect = async () => { + setState({ phase: "connecting" }); + const outcome = await connectLinkedEnvironment({ + label: surface.label, + requestPairing: async () => { + // Without it the linking environment refuses; the user can still pair by hand. + if (!mayPair) return null; + const result = await requestPairing({ + environmentId: surface.viaEnvironmentId, + input: { environmentId: surface.environmentId }, + }); + return result._tag === "Success" ? result.value : null; + }, + reaches: async (host) => { + const result = await reaches({ host, environmentId: surface.environmentId }); + return result._tag === "Success" && result.value; + }, + pair: async ({ host, pairingCode }) => { + const result = await pair({ + host, + pairingCode, + expectedEnvironmentId: surface.environmentId, + }); + return result._tag === "Success"; + }, + }); + if (outcome.type === "unreachable") { + setState({ phase: "unreachable", label: outcome.label }); + return outcome; + } + if (outcome.type === "connected") { + setState({ phase: "idle" }); + // The thread opens where every thread on a connected environment does, so its tab is done. + useRightPanelStore.getState().closeSurface(panelRef, surface.id); + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(surface.environmentId, surface.threadId)), + }); + return outcome; + } + const prefill = { + environmentId: surface.environmentId, + label: outcome.label, + host: outcome.host, + }; + setState({ phase: "manual", prefill }); + addWithCode(prefill); + return outcome; + }; + return { state, connect, addWithCode }; +} + /** Where a linked thread's expanded rows read an item in full: through the linking environment. */ export const linkedThreadItemSource = ( target: Pick, diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index 9d0ebabb48158..ea64b8523541b 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -79,7 +79,8 @@ declared as reads in [McpToolAccess](../../apps/server/src/mcp/McpToolAccess.ts) where every tool must declare who may call it to compile. Any other grant adds `orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions, and for a [peer link](remote.md#peer-links)'s session alone the thread routes in -[linkThreadHttp](../../apps/server/src/peer/linkThreadHttp.ts), which only read. Every other HTTP and WebSocket +[linkThreadHttp](../../apps/server/src/peer/linkThreadHttp.ts), which only read, and the +client pairing described below. Every other HTTP and WebSocket path rejects that subject, because the RPC surface would let the agent act above its ceiling. Inside MCP the credential sets the limits and tool parameters only pick targets; see @@ -91,6 +92,17 @@ discovery: the handlers still refuse such a call with `thread_credential_required`. A secret card belongs to a thread's run, so an outside agent that needs a secret starts a thread and lets that agent ask. +A full-access [peer link](../../apps/server/src/peer/PeerClientPairing.ts) may +mint a one-time pairing for a client of the environment that holds it. Its +agents already run as this machine's user and could run `t3 auth pairing create`, +so this adds no authority; a narrower link would gain some, so it is refused +here, on the linked side, whatever the linking side sent. The pairing carries +the client's scopes on the linking environment intersected with a normal +pairing's. A person starts it: the linking environment exposes it as a WebSocket +RPC behind `access:write`, and the linked side as an HTTP route that accepts only +a link's session. It is not an MCP tool, because a tool is reachable by whatever +holds a thread credential, and hiding one from tool listings is only discovery. + Issuer and resource URLs come from the request's Host and `X-Forwarded-Proto`, so one server answers over loopback, Tailscale Serve and a T3 Connect tunnel. A proxy that rewrites Host or drops the protocol header diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 1f6e221b3ebe5..a3efb1de076d1 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -487,7 +487,16 @@ it opens as a tab in the right panel, beside the thread you are in, and shows the same timeline as any other thread. - The view is marked **Read-only** with both machines' names. To reply, approve - or stop the thread, connect this app to that machine. + or stop the thread, choose **Connect to interact**. When the link has full + access, this app pairs with that machine in one step and opens the thread + there; you need permission to manage access on the machine you are connected + to. Otherwise the add-environment form opens for that machine and asks for a + pairing code you create on it. +- This app connects to that machine directly, so it must be able to reach one of + the addresses the link uses. If it cannot, the view says so and stays + read-only. The new connection appears in that machine's **Settings → Sharing & + access**, named after this device and the machine it came through, and is + revoked there like any other. - Files, images and published visuals stay on that machine and do not load here. A command's output shows as of when you open its row. - If this app is already connected to that machine, the thread opens there as diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.ts index 4f804090853a8..aa74cc1088758 100644 --- a/packages/client-runtime/src/connection/onboarding.ts +++ b/packages/client-runtime/src/connection/onboarding.ts @@ -83,6 +83,11 @@ export class ConnectionOnboarding extends Context.Service< readonly updateBearer: ( input: BearerConnectionUpdateInput, ) => Effect.Effect; + /** Whether `host` answers this device as `environmentId`. Nothing is sent but the question. */ + readonly reaches: (input: { + readonly host: string; + readonly environmentId: EnvironmentId; + }) => Effect.Effect; } >()("@t3tools/client-runtime/connection/onboarding/ConnectionOnboarding") {} @@ -214,6 +219,27 @@ const registerPairingConnection = Effect.fn( return registration.target.environmentId; }); +const REACHABILITY_TIMEOUT_MS = 6_000; + +const reachesEnvironment = Effect.fn("clientRuntime.connection.onboarding.reachesEnvironment")( + function* (input: { readonly host: string; readonly environmentId: EnvironmentId }) { + const httpBaseUrl = yield* Effect.try({ + try: () => normalizeHttpBaseUrl(input.host), + catch: () => + new ConnectionBlockedError({ + reason: "configuration", + ...translatableDetail(msg("The environment URL is invalid.")), + }), + }); + const descriptor = yield* fetchRemoteEnvironmentDescriptor({ + httpBaseUrl, + timeoutMs: REACHABILITY_TIMEOUT_MS, + }); + return descriptor.environmentId === input.environmentId; + }, + Effect.orElseSucceed(() => false), +); + const isBearerProfile = Schema.is(BearerConnectionProfile); const updateBearerConnection = Effect.fn( @@ -378,6 +404,12 @@ export const make = Effect.gen(function* () { Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry), Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials), ), + reaches: Effect.fnUntraced( + function* (input) { + return yield* reachesEnvironment(input); + }, + Effect.provideService(HttpClient.HttpClient, httpClient), + ), }); }); diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 694363d5c135a..8b2d4e105e5b1 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -1,9 +1,12 @@ import { + EnvironmentId, EventId, type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadStreamItem, + type PeerLinkClientPairingResult, } from "@t3tools/contracts"; -import { expect, it } from "@effect/vitest"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Queue from "effect/Queue"; @@ -11,6 +14,7 @@ import * as Stream from "effect/Stream"; import { TestClock } from "effect/testing"; import { + connectLinkedEnvironment, followLinkedThread, keepLinkedThreadView, LINKED_THREAD_RETRY_MS, @@ -158,3 +162,78 @@ it.effect("loads the turns before a snapshot's window once per request", () => expect(asked).toEqual(["cursor-1"]); }).pipe(Effect.scoped), ); + +describe("connectLinkedEnvironment", () => { + const lan = "http://192.168.1.20:3773"; + const tailnet = "https://vm.tail.ts.net"; + const target = { + environmentId: EnvironmentId.make("environment-vm"), + label: "VM", + urls: [lan, tailnet], + }; + const credential: PeerLinkClientPairingResult = { + type: "credential", + ...target, + credential: "ONE-TIME", + expiresAt: DateTime.makeUnsafe(0), + }; + const connect = ( + pairing: PeerLinkClientPairingResult | null, + reachable: ReadonlyArray, + paired = true, + ) => { + const pairs: Array<{ host: string; pairingCode: string }> = []; + return connectLinkedEnvironment({ + label: "vm (saved name)", + requestPairing: async () => pairing, + reaches: async (host) => reachable.includes(host), + pair: async (input) => { + pairs.push(input); + return paired; + }, + }).then((outcome) => ({ outcome, pairs })); + }; + + it("redeems the pairing at the first address this device reaches", async () => { + expect(await connect(credential, [tailnet])).toEqual({ + outcome: { type: "connected" }, + pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }], + }); + expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan); + }); + + it("says the machine is out of reach, and spends nothing, when no address answers", async () => { + expect(await connect(credential, [])).toEqual({ + outcome: { type: "unreachable", label: "VM" }, + pairs: [], + }); + }); + + it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => { + const unsupported: PeerLinkClientPairingResult = { + type: "unsupported", + reason: "link_access", + ...target, + }; + const manual = (host: string | null) => ({ + outcome: { type: "manual", label: "VM", host }, + pairs: [], + }); + expect(await connect(unsupported, [tailnet])).toEqual(manual(tailnet)); + // An address the user can correct beats an empty field. + expect(await connect(unsupported, [])).toEqual(manual(lan)); + expect(await connect({ ...unsupported, urls: [] }, [])).toEqual(manual(null)); + // The linking environment never answered, so only the client's own name is known. + expect((await connect(null, [lan])).outcome).toEqual({ + type: "manual", + label: "vm (saved name)", + host: null, + }); + // The one-time pairing was refused where it was redeemed. + expect((await connect(credential, [lan], false)).outcome).toEqual({ + type: "manual", + label: "VM", + host: lan, + }); + }); +}); diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index a5316a99008b7..15364cddf54ea 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -3,6 +3,7 @@ import type { OrchestrationV2ThreadHistoryPage, OrchestrationV2ThreadProjection, OrchestrationV2ThreadStreamItem, + PeerLinkClientPairingResult, ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -56,6 +57,46 @@ export function resolveLinkedThreadOpen(input: { return input.own === undefined ? "unavailable" : "direct"; } +export type LinkedEnvironmentConnection = + /** This client paired with the linked environment and saved it. */ + | { readonly type: "connected" } + /** No address the linking environment knows answers from this device. */ + | { readonly type: "unreachable"; readonly label: string } + /** The user pairs with a code of their own, in the add-environment flow, with this filled in. */ + | { readonly type: "manual"; readonly label: string; readonly host: string | null }; + +/** + * Connects this client to a linked environment. The linking environment asks it for a one-time + * pairing over a full-access link, and the client redeems that at an address it can reach itself. + * Anything short of that leaves the user to pair by hand. + */ +export async function connectLinkedEnvironment(options: { + readonly label: string; + /** Asks the linking environment for a pairing; null when it could not answer. */ + readonly requestPairing: () => Promise; + /** Whether an address answers this device as the linked environment. */ + readonly reaches: (host: string) => Promise; + /** Pairs at `host` with the one-time credential and saves the environment. */ + readonly pair: (input: { + readonly host: string; + readonly pairingCode: string; + }) => Promise; +}): Promise { + const pairing = await options.requestPairing(); + if (pairing === null) return { type: "manual", label: options.label, host: null }; + const { label, urls } = pairing; + // Asked together, taken in the linking environment's order of preference. + const answers = await Promise.all(urls.map((url) => options.reaches(url))); + const host = urls.find((_, index) => answers[index]) ?? null; + if (pairing.type === "unsupported") { + return { type: "manual", label, host: host ?? urls[0] ?? null }; + } + if (host === null) return { type: "unreachable", label }; + return (await options.pair({ host, pairingCode: pairing.credential })) + ? { type: "connected" } + : { type: "manual", label, host }; +} + const hasStringField = (value: unknown, key: K): value is Record => typeof value === "object" && value !== null && diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index fe6579d9d0c75..0f76e9cfb3dea 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -115,6 +115,15 @@ export function createPeerLinkEnvironmentAtoms( tag: WS_METHODS.peerLinksThreadItem, idleTtlMs: 0, }), + /** Asks for a one-time pairing with a linked environment. Its answer is a credential: never cached. */ + pairClient: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:pair-client", + tag: WS_METHODS.peerLinksPairClient, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => JSON.stringify([environmentId, input.environmentId]), + }, + }), // An agent's link card. One answer per card at a time. answerRequest: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:answer-request", diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 0b6164871a0ad..47f24f576735e 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -86,6 +86,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope, // A link lets every agent here reach the other environment: Settings' bar. [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope, + [WS_METHODS.peerLinksPairClient]: AuthAccessWriteScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index b1a4c9ea18fcd..8ccdc7293a6e1 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -191,6 +191,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ /** Serves a thread's stream, history pages and item detail to a link's session (`PEER_LINK_THREAD_STREAM_ROUTE`), so a client of the linking environment can read it. */ linkThreadStream: Schema.optionalKey(Schema.Boolean), + /** A full-access link can ask this server for a one-time pairing credential for a client + of the linking environment. Absent on servers from before it. */ + linkClientPairing: Schema.optionalKey(Schema.Boolean), /** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */ mcpApprovalCodes: Schema.optionalKey(Schema.Boolean), peerLinkPairingCodes: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index c9a348efa72e8..fa51a25a1110b 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -70,6 +70,7 @@ import { EnvironmentSpeechStatus, EnvironmentSpeechTranscriptionResult, } from "./speech.ts"; +import { PeerLinkClientPairingCredential, PeerLinkClientPairingRequest } from "./peerLink.ts"; import { SecretReference } from "./secretReference.ts"; import { OrchestrationV2ShellHttpSnapshot, @@ -1052,6 +1053,23 @@ class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect") }), ) {} +/** + * What a linking environment asks of this one over its link, outside `/mcp`. The handler accepts + * only a peer link's own session, so no agent's tool list ever carries it. + */ +class EnvironmentPeerLinkHttpApi extends HttpApiGroup.make("peerLink").add( + HttpApiEndpoint.post("clientPairing", "/api/peer-link/client-pairing", { + headers: OptionalBearerHeaders, + payload: PeerLinkClientPairingRequest, + success: PeerLinkClientPairingCredential, + error: [ + EnvironmentHttpUnauthorizedError, + EnvironmentHttpForbiddenError, + EnvironmentHttpInternalServerError, + ], + }), +) {} + // Path tokens and optional body signatures authenticate webhooks; read raw bytes to verify signatures. const WebhookParams = Schema.Struct({ hookId: TrimmedNonEmptyString, @@ -1081,4 +1099,5 @@ export class EnvironmentHttpApi extends HttpApi.make("environment") .add(EnvironmentProjectsHttpApi) .add(EnvironmentVoiceHttpApi) .add(EnvironmentConnectHttpApi) - .add(EnvironmentWebhooksHttpApi) {} + .add(EnvironmentWebhooksHttpApi) + .add(EnvironmentPeerLinkHttpApi) {} diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index bf25a34e07cf7..3b367c04eaecb 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -import { AuthMcpClientAccess } from "./auth.ts"; +import { AuthEnvironmentScope, AuthMcpClientAccess } from "./auth.ts"; import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts"; /** @@ -156,6 +156,60 @@ export class PeerLinkThreadReadError extends Schema.TaggedError Date: Fri, 20 Nov 2026 12:19:48 -0800 Subject: [PATCH 5/7] feat: subagents, side chats and linked threads open the same way (#39515) Co-authored-by: Claude Fable 5.2 --- .../settings/DesktopClientSettings.test.ts | 1 + apps/mobile/src/Stack.tsx | 5 + .../features/threads/LinkedThreadSheet.tsx | 71 +++--- .../features/threads/ThreadAgentsSheet.tsx | 7 +- .../features/threads/ThreadRouteScreen.tsx | 8 +- .../src/features/threads/linkedThreadRoute.ts | 22 ++ .../threads/thread-inspector-header.tsx | 38 ++++ .../thread-inspector-navigation.test.tsx | 64 +++++- .../threads/thread-inspector-navigation.ts | 15 +- .../threads/thread-inspector-preview.tsx | 77 ++++--- .../threads/thread-subagent-group.tsx | 15 +- .../features/threads/useOpenLinkedThread.ts | 53 +++++ .../src/features/threads/useOpenThreadLink.ts | 13 +- apps/web/src/closedViewStore.test.ts | 8 +- apps/web/src/closedViewStore.ts | 17 +- .../src/components/ChatView.browser.test.tsx | 40 +++- apps/web/src/components/ChatView.tsx | 25 ++- .../components/ReopenClosedViewShortcut.tsx | 8 +- apps/web/src/components/RightPanelTabs.tsx | 43 +++- apps/web/src/components/ThreadRouteView.tsx | 2 +- .../src/components/chat/LinkedThreadPage.tsx | 65 ++++++ .../src/components/chat/LinkedThreadPane.tsx | 87 +++++--- .../chat/MarkdownThreadLink.browser.test.tsx | 10 + .../components/chat/MarkdownThreadLink.tsx | 38 ++-- .../chat/MessagesTimeline.browser.test.tsx | 3 +- .../src/components/chat/MessagesTimeline.tsx | 3 + .../chat/ReadOnlyThreadTimeline.tsx | 75 ++++--- .../chat/RightPanelSurfaceContent.tsx | 8 +- apps/web/src/components/chat/SideChatPane.tsx | 166 -------------- .../src/components/chat/SideThreadPane.tsx | 210 ++++++++++++++++++ .../chat/ThreadLineageWorkflowRow.tsx | 9 +- ...hreadRelationshipsControl.browser.test.tsx | 22 +- .../chat/ThreadRelationshipsControl.tsx | 49 +++- .../chat/TimelineUserMessageRow.tsx | 4 +- .../src/components/chat/V2LifecycleRow.tsx | 35 ++- .../components/chat/WorkflowOpeningBlock.tsx | 9 +- .../src/components/chat/timelineRowContext.ts | 3 + .../components/chat/useRightPanelActions.ts | 21 +- apps/web/src/components/chat/useSideChat.ts | 2 +- .../components/chat/useThreadLifecycle.tsx | 20 +- .../components/settings/SettingsPanels.tsx | 61 +++++ .../settings/settingsSearch.test.ts | 6 + .../src/components/settings/settingsSearch.ts | 10 + .../web/src/hooks/useOpenSurfaceInMainView.ts | 30 +++ .../src/hooks/useRightPanelSurfaceClose.ts | 15 +- apps/web/src/hooks/useSideThreadTrigger.ts | 65 ++++++ apps/web/src/i18n/translations/de.json | 24 +- apps/web/src/i18n/translations/en.json | 24 +- apps/web/src/i18n/translations/es.json | 24 +- apps/web/src/i18n/translations/fr.json | 24 +- apps/web/src/i18n/translations/ja.json | 24 +- apps/web/src/i18n/translations/ko.json | 24 +- apps/web/src/i18n/translations/pt-BR.json | 24 +- apps/web/src/i18n/translations/ru.json | 24 +- apps/web/src/i18n/translations/sv.json | 24 +- apps/web/src/i18n/translations/zh.json | 24 +- .../lib/assistantCitationNavigation.test.ts | 2 +- .../src/lib/assistantCitationNavigation.ts | 2 +- apps/web/src/lib/sideChatPane.test.ts | 30 ++- apps/web/src/lib/sideChatPane.ts | 86 ++++++- apps/web/src/linkedThreadSurface.ts | 11 + apps/web/src/reopenClosedView.ts | 4 +- apps/web/src/rightPanelStore.test.ts | 38 ++++ apps/web/src/rightPanelStore.ts | 58 ++++- apps/web/src/routeTree.gen.ts | 25 +++ ...d.$linkedEnvironmentId.$linkedThreadId.tsx | 21 ++ apps/web/src/state/linkedThreadView.ts | 82 ++++--- apps/web/src/threadRoutes.test.ts | 12 + apps/web/test/appScenarios.renders.tsx | 4 +- apps/web/test/fakeEnvironment.ts | 20 +- docs/user/remote-access.md | 8 +- docs/user/thread-sidebar.md | 33 ++- packages/client-runtime/package.json | 4 + .../client-runtime/src/sideThread.test.ts | 108 +++++++++ packages/client-runtime/src/sideThread.ts | 94 ++++++++ packages/contracts/src/settings.ts | 11 + 76 files changed, 1907 insertions(+), 544 deletions(-) create mode 100644 apps/mobile/src/features/threads/linkedThreadRoute.ts create mode 100644 apps/mobile/src/features/threads/thread-inspector-header.tsx create mode 100644 apps/web/src/components/chat/LinkedThreadPage.tsx delete mode 100644 apps/web/src/components/chat/SideChatPane.tsx create mode 100644 apps/web/src/components/chat/SideThreadPane.tsx create mode 100644 apps/web/src/hooks/useOpenSurfaceInMainView.ts create mode 100644 apps/web/src/hooks/useSideThreadTrigger.ts create mode 100644 apps/web/src/routes/_chat.linked.$viaEnvironmentId.$linkedEnvironmentId.$linkedThreadId.tsx create mode 100644 packages/client-runtime/src/sideThread.test.ts create mode 100644 packages/client-runtime/src/sideThread.ts diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 90c8740f83725..d66ca346aabb3 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -27,6 +27,7 @@ const clientSettings: ClientSettings = { browserDefaultAppearance: "dark", browserRecordingFrameRate: 60, browserLinkTarget: "app", + sideThreadOpenTarget: "main", browserAutoShowFloatingPreview: false, browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }], browserDefaultProfileId: "work", diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index b9281945f11f6..696b01ce29692 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -789,6 +789,11 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: LinkedThreadSheet, options: sheetRoute({ detent: 0.9, android: "fullScreen" }), }), + // Maximized from the inspector, like ThreadInspectorFullscreen. + LinkedThreadFullscreen: createNativeStackScreen({ + screen: LinkedThreadSheet, + options: modalRoute({ header: "glass", itemStyle: "editor", duoMinimize: "onScrollUp" }), + }), ThreadGuestShare: createNativeStackScreen({ screen: ThreadGuestShareSheet, options: sheetRoute({ detent: 0.5 }), diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 7c9ee3c17e9a7..0096c9d576a91 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -17,7 +17,7 @@ import { } from "@t3tools/client-runtime/work-log/item-detail"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { T, useGT, useLocale, useMessages } from "gt-react-native"; -import { useRef, useState, useSyncExternalStore } from "react"; +import { useEffect, useRef, useState, useSyncExternalStore } from "react"; import type * as React from "react"; import { AppState, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -26,7 +26,6 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { AppText as Text } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; import { ScreenContent } from "../../components/ui/ScreenContent"; -import { SheetHeader } from "../../components/ui/SheetHeader"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useEnvironments } from "../../state/environments"; import { @@ -40,30 +39,11 @@ import { useConnectLinkedEnvironment, useLinkedThreadView } from "../../state/li import { peerLinkEnvironment } from "../../state/peerLinks"; import { useEnvironmentQuery } from "../../state/query"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; +import type { LinkedThreadRouteParams } from "./linkedThreadRoute"; import { ReadOnlyComposerBar } from "./ReadOnlyComposerBar"; +import { ThreadInspectorHeader, type ThreadInspectorPresentation } from "./thread-inspector-header"; import { useOpenLinkedThread } from "./useOpenLinkedThread"; -type LinkedThreadRouteParams = { - readonly viaEnvironmentId: string; - readonly environmentId: string; - readonly threadId: string; - readonly label: string; - readonly title?: string; -}; - -/** The route params that open a linked environment's thread read-only. */ -export const linkedThreadRouteParams = ( - thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, - linked: { readonly viaEnvironmentId: EnvironmentId; readonly label: string }, - title: string | null, -): LinkedThreadRouteParams => ({ - viaEnvironmentId: linked.viaEnvironmentId, - environmentId: thread.environmentId, - threadId: thread.threadId, - label: linked.label, - ...(title === null ? {} : { title }), -}); - function ActivityRow(props: { readonly activity: ThreadFeedActivity; readonly target: LinkedThreadTarget; @@ -263,12 +243,23 @@ const subscribeAppState = (onChange: () => void) => { }; const appIsActive = () => AppState.currentState === "active"; -function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { +/** + * A linked environment's thread, read through the environment this app is connected to. The app + * never connects to the linked one, so the view only reads. It shows in the inspector, where + * `presentation` maximizes it, or as its own screen, where `presentation` closes it. + */ +export function LinkedThreadView(props: { + readonly target: LinkedThreadTarget; + /** Closes the screen by going back when absent. */ + readonly presentation?: ThreadInspectorPresentation; +}) { const { target } = props; const gt = useGT(); const m = useMessages(); const locale = useLocale(); const navigation = useNavigation(); + const presentation = props.presentation ?? { onClose: () => navigation.goBack() }; + const inInspector = "onMaximize" in presentation; const insets = useSafeAreaInsets(); const via = useEnvironments().environments.find( @@ -299,23 +290,34 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { const connection = useConnectLinkedEnvironment(target); const connectState = connection.state; const openThread = useOpenLinkedThread(); + const shown = useRef(true); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records unmount, so a connect that resolves after the view is gone navigates nowhere + useEffect(() => { + shown.current = true; + return () => { + shown.current = false; + }; + }, []); const connect = async () => { const outcome = await connection.connect(); - if (outcome.type === "unreachable") return; - // This sheet closes either way: the thread opens where the app is now connected, or the - // add-environment screen takes its place. + if (outcome.type === "unreachable" || !shown.current) return; + // The read-only view gives way either way: the thread opens where the app is now connected, + // or the add-environment screen takes its place. In the inspector the thread replaces it there. if (outcome.type === "connected") { - navigation.goBack(); + if (!inInspector) navigation.goBack(); openThread({ environmentId: target.environmentId, threadId: target.threadId }); return; } - navigation.dispatch(StackActions.replace("ConnectionsNew", { linked: target.environmentId })); + if (inInspector) navigation.navigate("ConnectionsNew", { linked: target.environmentId }); + else { + navigation.dispatch(StackActions.replace("ConnectionsNew", { linked: target.environmentId })); + } }; return ( - - + navigation.goBack()} /> ) { const { viaEnvironmentId, environmentId, threadId, label, title } = route.params; return ( diff --git a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx index 0299b688dd86a..e2c3d6d04bbf7 100644 --- a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx @@ -30,10 +30,10 @@ import { SubagentStopButton } from "./SubagentStopButton"; import { ThreadWorkflowGroup } from "./ThreadWorkflowGroup"; import { ScreenContent } from "../../components/ui/ScreenContent"; import { subagentThreadTarget, type SubagentThreadTarget } from "./threadAgentsPresentation"; -import { linkedThreadRouteParams } from "./LinkedThreadSheet"; import { useLinkedThreadReach } from "../../state/linkedThread"; import { useOpenThreadInspector } from "./thread-inspector-navigation"; +import { useOpenLinkedThreadRead } from "./useOpenLinkedThread"; type AgentsTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; @@ -53,6 +53,7 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps) { const target = route.params; const navigation = useNavigation(); const openInspector = useOpenThreadInspector(); + const openLinkedRead = useOpenLinkedThreadRead(); const insets = useSafeAreaInsets(); const gt = useGT(); const messages = useMessages(); @@ -73,9 +74,7 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps) { const openChildThread = (child: SubagentThreadTarget, title: string | null = null) => { void Haptics.selectionAsync(); if (child.linked !== undefined) { - navigation.dispatch( - StackActions.replace("LinkedThread", linkedThreadRouteParams(child, child.linked, title)), - ); + openLinkedRead(child, child.linked, title, { source: target, replace: true }); return; } if ( diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 9d9cddd644e36..6feb3750d6f52 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -127,12 +127,8 @@ import { useWorkspaceBackNavigation, } from "../layout/workspace/useAndroidWorkspaceNavigation"; import { openSettings } from "../settings/settings-navigation"; -import { - InspectorContentScope, - ThreadInspectorHeader, - ThreadInspectorPreview, - type ThreadInspectorPresentation, -} from "./thread-inspector-preview"; +import { ThreadInspectorHeader, type ThreadInspectorPresentation } from "./thread-inspector-header"; +import { InspectorContentScope, ThreadInspectorPreview } from "./thread-inspector-preview"; import { useStartSideChat } from "./useStartSideChat"; import { useThreadStatusAnnouncements } from "./useThreadStatusAnnouncements"; import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation"; diff --git a/apps/mobile/src/features/threads/linkedThreadRoute.ts b/apps/mobile/src/features/threads/linkedThreadRoute.ts new file mode 100644 index 0000000000000..e428e57a2834f --- /dev/null +++ b/apps/mobile/src/features/threads/linkedThreadRoute.ts @@ -0,0 +1,22 @@ +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; + +export type LinkedThreadRouteParams = { + readonly viaEnvironmentId: string; + readonly environmentId: string; + readonly threadId: string; + readonly label: string; + readonly title?: string; +}; + +/** The route params that open a linked environment's thread read-only. */ +export const linkedThreadRouteParams = ( + thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, + linked: { readonly viaEnvironmentId: EnvironmentId; readonly label: string }, + title: string | null, +): LinkedThreadRouteParams => ({ + viaEnvironmentId: linked.viaEnvironmentId, + environmentId: thread.environmentId, + threadId: thread.threadId, + label: linked.label, + ...(title === null ? {} : { title }), +}); diff --git a/apps/mobile/src/features/threads/thread-inspector-header.tsx b/apps/mobile/src/features/threads/thread-inspector-header.tsx new file mode 100644 index 0000000000000..f3d738d3238ed --- /dev/null +++ b/apps/mobile/src/features/threads/thread-inspector-header.tsx @@ -0,0 +1,38 @@ +import { useGT } from "gt-react-native"; + +import { AppBar } from "../../components/ui/AppBar"; +import { SheetHeader } from "../../components/ui/SheetHeader"; + +/** A thread shown outside its route: in the inspector pane, or presented full screen with a close. */ +export type ThreadInspectorPresentation = + | { readonly onMaximize: () => void } + | { readonly onClose: () => void }; + +export function ThreadInspectorHeader( + props: ThreadInspectorPresentation & { readonly title: string; readonly subtitle?: string }, +) { + const gt = useGT(); + if ("onMaximize" in props) { + return ( + + ); + } + return ( + + ); +} diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx index d09bd106941c0..404d28184d7b8 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx @@ -3,17 +3,19 @@ import * as NodeModule from "node:module"; import * as React from "react"; import { act, useLayoutEffect } from "react"; import { createRoot } from "react-dom/client"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; const harness = vi.hoisted(() => ({ dispatch: (_action: unknown) => {}, getState: (): unknown => undefined, getRoute: (): unknown => undefined, + inspectorSupported: true, })); vi.mock("react-native", () => ({ Platform: { OS: "ios" } })); vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({ - useWorkspacePaneState: () => ({ fileInspector: { supported: true } }), + useWorkspacePaneState: () => ({ fileInspector: { supported: harness.inspectorSupported } }), })); vi.mock("@react-navigation/native", async () => { const { createRequire } = await import("node:module"); @@ -28,7 +30,7 @@ vi.mock("@react-navigation/native", async () => { }); import { useOpenThreadInspector } from "./thread-inspector-navigation"; -import { useOpenLinkedThread } from "./useOpenLinkedThread"; +import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread"; const requireNavigation = NodeModule.createRequire( NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"), @@ -38,11 +40,12 @@ const { StackRouter, StackActions } = requireNavigation("@react-navigation/route StackActions: typeof import("@react-navigation/native").StackActions; }; -function setup(fromAgents: boolean, fullscreen = false) { +function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = true) { + harness.inspectorSupported = inspectorSupported; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const router = StackRouter({}); const options = { - routeNames: ["Home", "Thread", "ThreadAgents", "ThreadInspectorFullscreen"], + routeNames: ["Home", "Thread", "ThreadAgents", "ThreadInspectorFullscreen", "LinkedThread"], routeParamList: {}, routeGetIdList: {}, }; @@ -66,12 +69,15 @@ function setup(fromAgents: boolean, fullscreen = false) { ); let openInspector: ReturnType; let openLinkedThread: ReturnType; + let openLinkedThreadRead: ReturnType; function Probe() { const open = useOpenThreadInspector(); const openLinked = useOpenLinkedThread(); + const openLinkedRead = useOpenLinkedThreadRead(); useLayoutEffect(() => { openInspector = open; openLinkedThread = openLinked; + openLinkedThreadRead = openLinkedRead; }); return null; } @@ -94,6 +100,9 @@ function setup(fromAgents: boolean, fullscreen = false) { openLinked(threadId: string) { act(() => openLinkedThread({ environmentId: source.environmentId, threadId })); }, + openLinkedRead(...input: Parameters) { + act(() => openLinkedThreadRead(...input)); + }, [Symbol.dispose]() { act(() => root.unmount()); }, @@ -134,6 +143,53 @@ it("opens a completion link in the parent inspector", () => { }); }); +it.each([ + { inspectorSupported: true, fromAgents: false }, + { inspectorSupported: true, fromAgents: true }, + { inspectorSupported: false, fromAgents: false }, + { inspectorSupported: false, fromAgents: true }, +])( + "opens a linked environment's thread in the inspector where there is one ($inspectorSupported, from Agents $fromAgents)", + ({ inspectorSupported, fromAgents }) => { + using screen = setup(fromAgents, false, inspectorSupported); + const thread = { + environmentId: EnvironmentId.make("linked-vm"), + threadId: ThreadId.make("there"), + }; + const linked = { viaEnvironmentId: EnvironmentId.make("remote-environment"), label: "fs-17" }; + screen.openLinkedRead(thread, linked, "Fix the build", { + source: screen.source, + replace: fromAgents, + }); + if (inspectorSupported) { + // Beside the parent, like a subagent or a side chat; the Agents sheet gives way. + expect(screen.state.routes.map((route) => route.name)).toEqual(["Home", "Thread"]); + expect(screen.state.routes.at(-1)).toMatchObject({ + key: screen.parentKey, + params: { + inspector: { + type: "linkedThread", + ...thread, + linked: { ...linked, title: "Fix the build" }, + }, + }, + }); + return; + } + // A phone has no inspector: the read-only thread takes the screen, replacing the sheet. + expect(screen.state.routes.map((route) => route.name)).toEqual([ + "Home", + "Thread", + "LinkedThread", + ]); + expect(screen.state.routes.at(-1)?.params).toEqual({ + ...thread, + ...linked, + title: "Fix the build", + }); + }, +); + it("switches between subagents and devices in the same parent route", () => { using screen = setup(false); screen.open({ type: "thread", environmentId: screen.source.environmentId, threadId: "child" }); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.ts b/apps/mobile/src/features/threads/thread-inspector-navigation.ts index fa60cf45a84ae..966dd1a92a632 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.ts +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.ts @@ -2,14 +2,22 @@ import { StackActions, useNavigation } from "@react-navigation/native"; import { createContext, use } from "react"; import { Platform } from "react-native"; +import { resolveMobileSideThreadPresentation } from "@t3tools/client-runtime/side-thread"; + import { useWorkspacePaneState } from "../layout/AdaptiveWorkspaceLayout"; export type ThreadInspectorMode = "route" | "git" | "files" | "preview"; export type ThreadInspectorTarget = { - readonly type: "thread" | "device" | "localPreview"; + /** "linkedThread" is a thread on a linked environment, read through `linked.viaEnvironmentId`. */ + readonly type: "thread" | "linkedThread" | "device" | "localPreview"; readonly environmentId: string; readonly threadId: string; + readonly linked?: { + readonly viaEnvironmentId: string; + readonly label: string; + readonly title?: string; + }; readonly deviceKey?: string; /** The environment's localhost page a "localPreview" shows. */ readonly url?: string; @@ -27,7 +35,10 @@ export function useOpenThreadInspector() { source: { readonly environmentId: string; readonly threadId: string }, target: ThreadInspectorTarget, ) => { - if (Platform.OS !== "ios" || !fileInspector.supported) return false; + const presentation = resolveMobileSideThreadPresentation({ + inspectorAvailable: Platform.OS === "ios" && fileInspector.supported, + }); + if (presentation === "full-screen") return false; if (openInInspector) openInInspector(target); else { const parent = navigation.getState()?.routes.findLast((route) => route.name === "Thread"); diff --git a/apps/mobile/src/features/threads/thread-inspector-preview.tsx b/apps/mobile/src/features/threads/thread-inspector-preview.tsx index e8ea059b54f2b..f3934aad9accc 100644 --- a/apps/mobile/src/features/threads/thread-inspector-preview.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-preview.tsx @@ -1,11 +1,8 @@ import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { useGT } from "gt-react-native"; import { type ReactNode } from "react"; import { View } from "react-native"; -import { AppBar } from "../../components/ui/AppBar"; -import { SheetHeader } from "../../components/ui/SheetHeader"; import { LocalPreviewScreen } from "../browser/LocalPreviewRouteScreen"; import { DevicePreviewScreen } from "../devices/DevicePreviewRouteScreen"; import { @@ -16,42 +13,11 @@ import { ThreadInspectorNavigationContext, type ThreadInspectorTarget, } from "./thread-inspector-navigation"; +import { linkedThreadRouteParams } from "./linkedThreadRoute"; +import { LinkedThreadView } from "./LinkedThreadSheet"; +import type { ThreadInspectorPresentation } from "./thread-inspector-header"; import { ThreadPreviewRoute } from "./thread-preview-route"; -/** A thread shown outside its route: in the inspector pane, or presented full screen with a close. */ -export type ThreadInspectorPresentation = - | { readonly onMaximize: () => void } - | { readonly onClose: () => void }; - -export function ThreadInspectorHeader( - props: ThreadInspectorPresentation & { readonly title: string; readonly subtitle?: string }, -) { - const gt = useGT(); - if ("onMaximize" in props) { - return ( - - ); - } - return ( - - ); -} - /** A thread shown beside or over the workspace does not take the workspace's content width. */ export function InspectorContentScope({ children }: { readonly children: ReactNode }) { return ( @@ -102,6 +68,12 @@ export function ThreadInspectorPreview(props: { }); }} /> + ) : target.type === "linkedThread" && target.linked ? ( + ) : target.type === "device" ? ( ); } + +/** A linked environment's read-only thread in the inspector; Maximize gives it the whole screen. */ +function LinkedThread(props: { + readonly thread: Pick; + readonly linked: NonNullable; +}) { + const navigation = useNavigation(); + const params = linkedThreadRouteParams( + { + environmentId: EnvironmentId.make(props.thread.environmentId), + threadId: ThreadId.make(props.thread.threadId), + }, + { + viaEnvironmentId: EnvironmentId.make(props.linked.viaEnvironmentId), + label: props.linked.label, + }, + props.linked.title ?? null, + ); + return ( + navigation.navigate("LinkedThreadFullscreen", params) }} + /> + ); +} diff --git a/apps/mobile/src/features/threads/thread-subagent-group.tsx b/apps/mobile/src/features/threads/thread-subagent-group.tsx index 0ef23f27a06b4..e953e0c56a8c5 100644 --- a/apps/mobile/src/features/threads/thread-subagent-group.tsx +++ b/apps/mobile/src/features/threads/thread-subagent-group.tsx @@ -28,11 +28,11 @@ import { useServerConfigs } from "../../state/entities"; import { SubagentRow } from "./SubagentRow"; import { useVisibleSecondClock } from "./use-visible-second-clock"; import { subagentThreadTarget } from "./threadAgentsPresentation"; -import { linkedThreadRouteParams } from "./LinkedThreadSheet"; import { useLinkedThreadReach } from "../../state/linkedThread"; import { WorkLogBlock } from "./work-log-layout"; import { useOpenThreadInspector } from "./thread-inspector-navigation"; +import { useOpenLinkedThreadRead } from "./useOpenLinkedThread"; type SubagentItem = Extract; type AgentTiming = Pick; @@ -114,6 +114,7 @@ export function ThreadSubagentGroup(props: { const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); const navigation = useNavigation(); const openInspector = useOpenThreadInspector(); + const openLinkedRead = useOpenLinkedThreadRead(); const members = props.activities.flatMap(({ projectedItem }) => projectedItem.item.type === "subagent" ? [projectedItem.item] : [], ); @@ -224,12 +225,12 @@ export function ThreadSubagentGroup(props: { onPress={() => { if (target === null) return; if (target.linked !== undefined) { - navigation.dispatch( - StackActions.push( - "LinkedThread", - linkedThreadRouteParams(target, target.linked, agent.title), - ), - ); + openLinkedRead(target, target.linked, agent.title, { + source: { + environmentId: props.environmentId, + threadId: members[0]!.threadId, + }, + }); return; } if ( diff --git a/apps/mobile/src/features/threads/useOpenLinkedThread.ts b/apps/mobile/src/features/threads/useOpenLinkedThread.ts index 2fc70a6298d7d..dc7217cfbc862 100644 --- a/apps/mobile/src/features/threads/useOpenLinkedThread.ts +++ b/apps/mobile/src/features/threads/useOpenLinkedThread.ts @@ -1,8 +1,12 @@ import { StackActions, useNavigation, useRoute, type Route } from "@react-navigation/native"; import { use } from "react"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; + import { linkedThreadStep } from "../../lib/android-workspace-navigation"; +import { linkedThreadRouteParams } from "./linkedThreadRoute"; import { ThreadInspectorNavigationContext, + type ThreadInspectorTarget, useOpenThreadInspector, } from "./thread-inspector-navigation"; @@ -33,3 +37,52 @@ export function useOpenLinkedThread() { else if (step === "push") navigation.dispatch(StackActions.push("Thread", target)); }; } + +/** + * Opens a linked environment's thread read-only, read through `linked.viaEnvironmentId`: in the + * inspector where the layout has one, as subagents and side chats do, else as its own screen. + * `source` is the thread it opens from when the caller is not that thread's own screen. + */ +export function useOpenLinkedThreadRead() { + const navigation = useNavigation(); + const route = useRoute>(); + const openInspector = useOpenThreadInspector(); + const openInInspector = use(ThreadInspectorNavigationContext); + return ( + thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, + linked: { readonly viaEnvironmentId: EnvironmentId; readonly label: string }, + title: string | null, + options?: { + readonly source?: { readonly environmentId: string; readonly threadId: string }; + /** Replaces the calling sheet instead of stacking on it. */ + readonly replace?: boolean; + }, + ) => { + const params = linkedThreadRouteParams(thread, linked, title); + const target: ThreadInspectorTarget = { + type: "linkedThread", + environmentId: params.environmentId, + threadId: params.threadId, + linked: { + viaEnvironmentId: params.viaEnvironmentId, + label: params.label, + ...(params.title === undefined ? {} : { title: params.title }), + }, + }; + if (openInInspector) { + openInInspector(target); + return; + } + const source = + options?.source ?? + (route.name === "Thread" && route.params?.environmentId && route.params.threadId + ? { environmentId: route.params.environmentId, threadId: route.params.threadId } + : null); + if (source !== null && openInspector(source, target)) return; + navigation.dispatch( + options?.replace + ? StackActions.replace("LinkedThread", params) + : StackActions.push("LinkedThread", params), + ); + }; +} diff --git a/apps/mobile/src/features/threads/useOpenThreadLink.ts b/apps/mobile/src/features/threads/useOpenThreadLink.ts index 27e5c5ecdea75..08e04898c7aac 100644 --- a/apps/mobile/src/features/threads/useOpenThreadLink.ts +++ b/apps/mobile/src/features/threads/useOpenThreadLink.ts @@ -1,19 +1,17 @@ -import { StackActions, useNavigation } from "@react-navigation/native"; import { resolveLinkedThreadOpen } from "@t3tools/client-runtime/linked-thread"; import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; import { useEnvironments } from "../../state/environments"; import { useLinkedEnvironments } from "../../state/peerLinks"; -import { linkedThreadRouteParams } from "./LinkedThreadSheet"; -import { useOpenLinkedThread } from "./useOpenLinkedThread"; +import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread"; /** * Opens a thread that a link or chip in `viaEnvironmentId` points at: in place when this app is * connected to its environment, else read-only through `viaEnvironmentId`'s link to it. */ export function useOpenThreadLink(viaEnvironmentId: EnvironmentId | null) { - const navigation = useNavigation(); const openThread = useOpenLinkedThread(); + const openLinkedRead = useOpenLinkedThreadRead(); const linkedEnvironments = useLinkedEnvironments(viaEnvironmentId); const { presentationById } = useEnvironments(); return (thread: ScopedThreadRef, title: string | null = null) => { @@ -29,12 +27,7 @@ export function useOpenThreadLink(viaEnvironmentId: EnvironmentId | null) { linked: true, }) === "linked" ) { - navigation.dispatch( - StackActions.push( - "LinkedThread", - linkedThreadRouteParams(thread, { viaEnvironmentId, label }, title), - ), - ); + openLinkedRead(thread, { viaEnvironmentId, label }, title); return; } openThread({ diff --git a/apps/web/src/closedViewStore.test.ts b/apps/web/src/closedViewStore.test.ts index 6b12b53330825..59b36cda4ad7f 100644 --- a/apps/web/src/closedViewStore.test.ts +++ b/apps/web/src/closedViewStore.test.ts @@ -58,7 +58,7 @@ describe("closedViewStore", () => { id: "bad", kind: "panel-tab", threadRef: refA, - surface: { kind: "side-chat", id: "side-chat:x" }, + surface: { kind: "thread", id: "thread:x" }, }, { id: "bad", @@ -100,7 +100,8 @@ describe("closedViewStore", () => { const sideChatId = store.remember({ kind: "panel-tab", threadRef: refA, - surface: { id: "side-chat:side", kind: "side-chat", threadId: ThreadId.make("side") }, + // Saved before a side chat's tab became a `thread` surface. + surface: { id: "side-chat:side", kind: "side-chat", threadId: "side" } as never, }); const publicId = store.remember(diff(refA)); const browserId = store.remember({ @@ -134,6 +135,9 @@ describe("closedViewStore", () => { publicId, sideChatId, ]); + expect(useClosedViewStore.getState().entries.at(-1)).toMatchObject({ + surface: { id: "thread:side", kind: "thread", threadId: "side" }, + }); const saved = JSON.stringify(await storage!.getItem(name!)); expect(saved).not.toContain("private.example"); expect(saved).not.toContain("Private page"); diff --git a/apps/web/src/closedViewStore.ts b/apps/web/src/closedViewStore.ts index 12087195cc67b..6587eb3eddf0d 100644 --- a/apps/web/src/closedViewStore.ts +++ b/apps/web/src/closedViewStore.ts @@ -12,7 +12,7 @@ import { createJSONStorage, persist } from "zustand/middleware"; import { decodeLinkedThreadSurface } from "./linkedThreadSurface"; import { resolveStorage } from "./lib/storage"; import { randomUUID } from "./lib/utils"; -import { type RightPanelSurface } from "./rightPanelStore"; +import { decodeThreadSurface, type RightPanelSurface } from "./rightPanelStore"; export type ClosedView = | { @@ -84,8 +84,8 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => { typeof surface.target.name === "string" && (surface.target.platform === "ios" || surface.target.platform === "android"))) ); - case "side-chat": - return typeof surface.threadId === "string" && surface.id === `side-chat:${surface.threadId}`; + case "thread": + return typeof surface.threadId === "string" && surface.id === `thread:${surface.threadId}`; case "linked-thread": return ( (surface.title === null || typeof surface.title === "string") && @@ -116,6 +116,13 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => { } }; +/** A closed side chat tab saved before its surface became `thread`. */ +const renamedSideChatTab = (entry: unknown): unknown => { + const view = entry as { kind?: unknown; surface?: { kind?: unknown } | null } | null; + if (view?.kind !== "panel-tab" || view.surface?.kind !== "side-chat") return entry; + return { ...view, surface: decodeThreadSurface(view.surface) }; +}; + export const useClosedViewStore = create()( persist( (set) => ({ @@ -145,13 +152,13 @@ export const useClosedViewStore = create()( storage: createJSONStorage(() => resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), ), - version: 2, + version: 3, migrate: (persisted) => { const entries = (persisted as Partial> | null) ?.entries; return { entries: Array.isArray(entries) - ? entries.filter(isClosedViewEntry).filter(isPersistentView) + ? entries.map(renamedSideChatTab).filter(isClosedViewEntry).filter(isPersistentView) : [], }; }, diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 96a870efeb9ea..ae6628ba6733c 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -774,8 +774,8 @@ it("selecting a side-chat tab focuses that side chat's composer", async () => { onboardingCompletedAt: "2026-01-01T00:00:00.000Z", }); const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id); - useRightPanelStore.getState().openSideChat(parentRef, otherSide.id); - useRightPanelStore.getState().openSideChat(parentRef, side.id); + useRightPanelStore.getState().openThread(parentRef, otherSide.id); + useRightPanelStore.getState().openThread(parentRef, side.id); const router = getRouter( createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }), ); @@ -805,6 +805,42 @@ it("selecting a side-chat tab focuses that side chat's composer", async () => { await expect.element(mainEditor).toHaveTextContent("main draft"); }); +it("a subagent tab shows its read-only bar under no header of its own", async () => { + const parent = threadWithHistory("subagent-parent", 1); + const subagent = { + ...threadWithHistory("subagent-child", 1), + providerSubagentOf: parent.id, + olderSettled: true as const, + }; + await page.viewport(1400, 900); + using _environment = installFakeEnvironment([parent, subagent]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id); + useRightPanelStore.getState().openThread(parentRef, subagent.id); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }), + ); + await router.load(); + await using screen = await render(, { + // AppRoot brings its own router. + router: false, + }); + const pane = screen.getByTestId("side-thread-pane"); + // No header of its own: the tab names it, and only a side chat has actions to put in one. + await expect.element(pane.getByRole("heading", { name: subagent.title })).not.toBeInTheDocument(); + await expect.element(pane.getByText("Runs on its own")).toBeVisible(); + await expect.element(pane.getByRole("button", { name: "Add to chat" })).not.toBeInTheDocument(); + await expect + .element(screen.getByRole("textbox", { name: `Message ${subagent.title}`, exact: true })) + .not.toBeInTheDocument(); + await expect + .element(screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true })) + .toBeVisible(); +}); + it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => { await page.viewport(1400, 900); const thread = threadWithHistory("side-attachments", 1); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 128f3b16d1dde..f0c4543b6c24a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -72,7 +72,6 @@ import { type AssistantCitation, type ResponseContextRecord, type ChatFileAttachment, - isProviderNativeSubagentThread, type EnvironmentId, type MessageId, type ModelSelection, @@ -309,6 +308,8 @@ import { getTriggerDisplayModelName } from "./chat/providerIconUtils"; import { resolveScrollToEndClearance } from "./composerFooterLayout"; import { ChatHeader } from "./chat/ChatHeader"; import { useSideChat } from "./chat/useSideChat"; +import { sideThreadComposer, sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; +import { useOpenSurfaceInMainView } from "../hooks/useOpenSurfaceInMainView"; import { useRemoteOpenState } from "~/remoteOpen"; import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut"; @@ -460,6 +461,7 @@ export default function ChatView(props: ChatViewProps) { embedded: parentPanel, } = props; const embedded = parentPanel !== undefined; + const panelHostShell = useQuietThreadShell(parentPanel?.hostRef ?? null); const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); const draftId = routeKind === "draft" ? props.draftId : null; @@ -858,8 +860,9 @@ export default function ChatView(props: ChatViewProps) { serverProjection === null ? null : deriveRunlessWorkStartedAt(serverProjection); const providerSubagentStatus = serverProjection === null ? null : deriveProviderSubagentStatus(serverProjection); + const sideThreadKind = serverThread === null ? null : sideThreadKindOf(serverThread.source); const isProviderSubagent = - serverThread !== null && isProviderNativeSubagentThread(serverThread.source); + sideThreadKind !== null && sideThreadComposer(sideThreadKind) === "read-only"; const supportsProviderSwitchingViaHandoff = threadSupportsProviderHandoff(serverProjection); const activeLatestRun = isServerThread ? serverLatestRun : (activeThread?.latestRun ?? null); const activeActivityRun = isServerThread ? serverActivityRun : (activeThread?.latestRun ?? null); @@ -942,8 +945,16 @@ export default function ChatView(props: ChatViewProps) { }; } if (parentSubagentThreadRef !== null) { + const title = parentSubagentThread?.title ?? gt("Parent thread"); + // Embedded in its parent's panel, the parent is the view around it. + if ( + parentPanel !== undefined && + scopedThreadKey(parentPanel.hostRef) === scopedThreadKey(parentSubagentThreadRef) + ) { + return { title }; + } return { - title: parentSubagentThread?.title ?? gt("Parent thread"), + title, open: (): void => { void navigate({ to: "/$environmentId/$threadId", @@ -2888,6 +2899,9 @@ export default function ChatView(props: ChatViewProps) { if (activeThread) setThreadError(activeThread.id, message); }, }); + // An embedded thread's commands run in its host's terminal, which is the host's checkout. + const runsOutsideHostCheckout = + embedded && (activeThread?.worktreePath ?? null) !== (panelHostShell?.worktreePath ?? null); // A maximized panel covers the terminal drawer the command runs in. const runSideChatShellCommandStable = useStableCallback((command: string) => { if (activeThreadRef) useRightPanelStore.getState().setMaximized(activeThreadRef, false); @@ -2913,6 +2927,7 @@ export default function ChatView(props: ChatViewProps) { ? gt("Available once the thread's worktree is set up.") : null; const openSideChatStable = useStableCallback(() => void sideChat.open()); + const openSurfaceInMainView = useOpenSurfaceInMainView(activeThreadRef); const sendSideChatStable = useStableCallback(sideChat.open); const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } = useTimelineRewind({ @@ -3290,6 +3305,7 @@ export default function ChatView(props: ChatViewProps) { ); // Above the early return, where React Compiler can cache it for the side chat pane. const sideChatParentPanel = { + hostRef: scopeThreadRef(environmentId, threadId), openToolDiff: onOpenToolDiffStable, runShellCommand: runSideChatShellCommandStable, }; @@ -3516,7 +3532,7 @@ export default function ChatView(props: ChatViewProps) { citationHistory={citationHistory} onCiteAssistantText={citeAssistantTextStable} onReplyToResponse={replyToResponseStable} - {...(activeProject + {...(activeProject && !runsOutsideHostCheckout ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable } : {})} isWorking={isWorking} @@ -4091,6 +4107,7 @@ export default function ChatView(props: ChatViewProps) { terminalLabelsById={activeTerminalLabelsById} onActivate={activateRightPanelSurfaceStable} onCloseSurface={closeRightPanelSurfaceStable} + onOpenInMainView={openSurfaceInMainView} onRenameDevice={(surfaceId, title) => { if (activeThreadRef) useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 83e0d3deaf990..551dbc98d8abc 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -33,6 +33,7 @@ import { selectThreadRightPanelState, useRightPanelStore, } from "../rightPanelStore"; +import { serverEnvironment } from "../state/server"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { readProject, readThreadShell } from "../state/entities"; import { previewEnvironment } from "../state/preview"; @@ -117,8 +118,11 @@ export function ReopenClosedViewShortcut() { ownerExists: readThreadShell(ref) !== null || drafts.getDraftThreadByRef(ref) !== null, sideChatExists: entry.kind !== "panel-tab" || - entry.surface.kind !== "side-chat" || - readThreadShell(scopeThreadRef(ref.environmentId, entry.surface.threadId)) !== null, + entry.surface.kind !== "thread" || + readThreadShell(scopeThreadRef(ref.environmentId, entry.surface.threadId)) !== null || + // The shell leaves idle subagents out, so one it does not list may still exist. + appAtomRegistry.get(serverEnvironment.configValueAtom(ref.environmentId)) + ?.shellThreadFamilies === true, shellLive: appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live", panel, diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index c1ec9a53ca622..f076a2794c68f 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -27,6 +27,7 @@ import type { ThreadId, } from "@t3tools/contracts"; import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; +import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { closestCenter, DndContext, @@ -39,6 +40,7 @@ import { restrictToFirstScrollableAncestor, restrictToHorizontalAxis } from "@dn import { horizontalListSortingStrategy, SortableContext, useSortable } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { + Bot, CircleDotIcon, Smartphone, ChevronDown, @@ -136,6 +138,10 @@ export interface RightPanelTabsProps { onActivate: (surface: RightPanelSurface) => void; onRenameDevice?: (surfaceId: string, title: string) => void; onCloseSurface: (surface: RightPanelSurface) => void; + /** Moves a subagent, side chat or linked thread tab to the main screen. */ + onOpenInMainView?: ( + surface: Extract, + ) => void; onCloseOtherSurfaces: (surface: RightPanelSurface) => void; onCloseSurfacesToRight: (surface: RightPanelSurface) => void; onCloseAllSurfaces: () => void; @@ -217,6 +223,7 @@ const SURFACE_UNAVAILABLE_HINTS = { } as const; type TabContextMenuAction = + | "open-in-main-view" | "rename" | "copy-path" | "toggle-mute" @@ -613,8 +620,9 @@ function surfaceTitle( return /^\d+$/.test(surface.key) ? `#${surface.key}` : surface.key; case "device": return surface.title ?? surface.target?.name ?? resolve(msg("Device")); - case "side-chat": - return resolve(msg("Side chat")); + case "thread": + // Until the thread's own title loads. + return resolve(msg("Thread")); case "linked-thread": return linkedThreadTitle( surface, @@ -710,7 +718,7 @@ function SurfaceIcon({ return ; case "issue": return ; - case "side-chat": + case "thread": return ; case "linked-thread": return ; @@ -743,16 +751,16 @@ function sideChatTabState(shell: EnvironmentThreadShell | null) { return threadRuntimeIsActive(shell.runtime) ? "running" : null; } -// Static dots: a side chat tab can stay open for a whole run. +// Static dots: a side chat or subagent tab can stay open for a whole run. function SideChatTabIcon(props: { environmentId: EnvironmentId | null; threadId: ThreadId }) { - const state = sideChatTabState( - useQuietThreadShell( - props.environmentId === null ? null : scopeThreadRef(props.environmentId, props.threadId), - ), + const shell = useQuietThreadShell( + props.environmentId === null ? null : scopeThreadRef(props.environmentId, props.threadId), ); + const state = sideChatTabState(shell); + const Icon = shell !== null && shell.lineage.sideChat !== true ? Bot : MessagesSquare; return ( <> - + {state === null ? null : ( @@ -1279,6 +1292,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (surfaceIndex < 0) return; const items: ContextMenuItem[] = []; + if ((surface.kind === "thread" || surface.kind === "linked-thread") && props.onOpenInMainView) { + items.push({ id: "open-in-main-view", label: gt("Open in main view") }); + } if (surface.kind === "device" && props.onRenameDevice) items.push({ id: "rename", label: gt("Rename") }); if (surface.kind === "file" && surface.attachment === undefined) { @@ -1320,6 +1336,11 @@ export function RightPanelTabs(props: RightPanelTabsProps) { const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY }); switch (action) { + case "open-in-main-view": + if (surface.kind === "thread" || surface.kind === "linked-thread") { + props.onOpenInMainView?.(surface); + } + break; case "rename": setRenamingDevice(surface.id); break; diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index 5217b068f9a35..48b86b8ddfe56 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -31,7 +31,7 @@ import { * Keeps the family of an open thread the shell leaves out (an older settled thread) in the shell * rows until the route leaves it, so every reader of its shell row finds it. */ -function useOpenThreadFamily(threadRef: ScopedThreadRef | null, missing: boolean) { +export function useOpenThreadFamily(threadRef: ScopedThreadRef | null, missing: boolean) { const key = threadRef === null ? null : scopedThreadKey(threadRef); // Sticks to the route thread, so the row the family brings in does not release it. const [mountedKey, setMountedKey] = useState(null); diff --git a/apps/web/src/components/chat/LinkedThreadPage.tsx b/apps/web/src/components/chat/LinkedThreadPage.tsx new file mode 100644 index 0000000000000..08d216a212650 --- /dev/null +++ b/apps/web/src/components/chat/LinkedThreadPage.tsx @@ -0,0 +1,65 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { Navigate } from "@tanstack/react-router"; +import { useGT } from "gt-react"; + +import { isElectron } from "~/env"; +import { linkedThreadSurface } from "../../linkedThreadSurface"; +import { useEnvironment } from "../../state/environments"; +import { useLinkedEnvironments } from "../../state/peerLinks"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { SidebarInset } from "../ui/sidebar"; +import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem } from "../WorkspaceBreadcrumb"; +import { WorkspacePageHeader } from "../WorkspacePageHeader"; +import { LinkedThread } from "./LinkedThreadPane"; + +/** + * A linked environment's thread on the main screen, read through `viaEnvironmentId`. Once this + * client is connected to the thread's own environment, the thread opens there instead. + */ +export function LinkedThreadPage(props: { + readonly viaEnvironmentId: EnvironmentId; + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}) { + const { viaEnvironmentId, environmentId, threadId } = props; + const gt = useGT(); + const own = useEnvironment(environmentId); + const connected = own?.connection.phase === "connected"; + const linkedLabel = useLinkedEnvironments(connected ? null : viaEnvironmentId).get(environmentId); + if (connected) { + return ( + + ); + } + const surface = linkedThreadSurface({ + viaEnvironmentId, + environmentId, + threadId, + label: own?.label ?? linkedLabel ?? gt("a linked environment"), + title: null, + }); + return ( + + ( + + + +

    {title}

    +
    +
    +
    + )} + /> +
    + ); +} diff --git a/apps/web/src/components/chat/LinkedThreadPane.tsx b/apps/web/src/components/chat/LinkedThreadPane.tsx index 514e75b3c1e34..798ef2c80e405 100644 --- a/apps/web/src/components/chat/LinkedThreadPane.tsx +++ b/apps/web/src/components/chat/LinkedThreadPane.tsx @@ -42,7 +42,7 @@ function LinkedThreadComposer(props: { const { label, via } = props; const gt = useGT(); return ( -
    +
    {props.notice ? : null} @@ -76,12 +76,14 @@ const ignore = () => {}; * and drawn by the timeline every thread uses. The client never connects to the linked one, so * the view only reads: what would need that connection is absent. Key it by its surface id. */ -export function LinkedThreadPane(props: { - /** The thread whose panel shows the tab. */ - readonly panelRef: ScopedThreadRef; +export function LinkedThread(props: { + /** The thread whose panel shows it as a tab, or null on the main screen. */ + readonly panelRef: ScopedThreadRef | null; readonly surface: LinkedThreadSurface; - /** Whether the tab is showing; the stream runs only while it is. */ + /** Whether it is showing; the stream runs only while it is. */ readonly visible: boolean; + /** What sits above the timeline on the main screen; a tab already names the thread. */ + readonly renderHeader?: (title: string) => ReactNode; }) { const { surface, panelRef } = props; const gt = useGT(); @@ -173,30 +175,36 @@ export function LinkedThreadPane(props: { onLoadEarlier: view.loadEarlier, }; return ( -
    -

    - {linkedThreadTitle( + // `data-chat-canvas` gives the timeline the side gutters it has in a thread's own chat. +
    + {props.renderHeader?.( + linkedThreadTitle( { title: projection?.thread.title || surface.title }, gt("Thread on {label}", { label }), - )} -

    + ), + )} {projection === null ? ( <> -
    - {failure === null ? ( -
    - - - Reading from {label}… - -
    - ) : ( - - {failure.title} - {failure.detail} - {retryAction} - - )} +
    +
    + {failure === null ? ( +
    + + + Reading from {label}… + +
    + ) : ( + + {failure.title} + {failure.detail} + {retryAction} + + )} +
    ( <> {failure === null ? null : ( -
    - - {failure.title} - - {failure.detail} Showing what was read before. - - {retryAction} - +
    +
    + + {failure.title} + + {failure.detail} Showing what was read before. + + {retryAction} + +
    )} ); } + +/** A linked environment's thread as a right panel tab. Key it by its surface id. */ +export function LinkedThreadPane(props: { + /** The thread whose panel shows the tab. */ + readonly panelRef: ScopedThreadRef; + readonly surface: LinkedThreadSurface; + /** Whether the tab is showing. */ + readonly visible: boolean; +}) { + return ; +} diff --git a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx index 4455c29c7ea1e..919420c838bce 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx @@ -6,6 +6,7 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../test/render"; +import { isMacPlatform } from "../../lib/utils"; import { linkedThreadSurface } from "../../linkedThreadSurface"; import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore"; import { MarkdownThreadLink } from "./MarkdownThreadLink"; @@ -35,6 +36,9 @@ vi.mock(import("../../state/entities"), () => ({ ref?.projectId === "essay-project" ? ({ title: "Essays" } as never) : null, })); vi.mock(import("../../state/environments"), () => ({ + // The click rule reads the client setting, whose module asks for these. + useEnvironments: (() => []) as never, + usePrimaryEnvironment: (() => null) as never, useEnvironmentIdentities: () => [ { environmentId: EnvironmentId.make("environment"), label: "Here" }, { environmentId: EnvironmentId.make("remote"), label: "Remote" }, @@ -211,6 +215,12 @@ it.for([ await chip.click(); expect(panel().surfaces).toHaveLength(1); expect(screen.router?.state.location.pathname).toBe("/"); + // The modifier reads it on the main screen instead, through the same environment. + await chip.click({ modifiers: [isMacPlatform(navigator.platform) ? "Meta" : "Control"] }); + await vi.waitFor(() => + expect(screen.router?.state.location.pathname).toBe(`/linked/environment/${linkedId}/there`), + ); + expect(panel().surfaces).toHaveLength(1); }); it("reads through the link when a disconnected machine's thread is only cached here", async () => { diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 1e4c823b458b4..320951a9e312d 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -1,4 +1,5 @@ import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; import { useGT, useMessages } from "gt-react"; import { MessagesSquareIcon } from "lucide-react"; import { @@ -13,7 +14,8 @@ import { resolveLinkedThreadOpen } from "@t3tools/client-runtime/linked-thread"; import { configuredHostedAppUrl } from "../../hostedPairing"; import { useThreadRefs, useThreadShell } from "../../state/entities"; import { useConnectedEnvironmentIds, useEnvironmentIdentities } from "../../state/environments"; -import { useRightPanelStore } from "../../rightPanelStore"; +import { useSideThreadTrigger } from "../../hooks/useSideThreadTrigger"; +import { openLinkedThreadRead } from "../../lib/sideChatPane"; import { useLinkedEnvironments } from "../../state/peerLinks"; import { orchestrationEnvironment } from "../../state/orchestration"; import { useEnvironmentQuery } from "../../state/query"; @@ -25,14 +27,16 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; /** `label` is the link's written text; an autolink has none. */ export function MarkdownThreadLink(props: { readonly environmentId: EnvironmentId; - /** The thread the link is written in; a linked environment's thread opens in its right panel. */ + /** The thread the link is written in; a linked environment's thread can open in its right panel. */ readonly threadRef?: ScopedThreadRef | undefined; readonly link: ThreadLink; readonly label: string | null; }) { const gt = useGT(); const messages = useMessages(); - const panelRef = props.threadRef; + const navigate = useNavigate(); + const trigger = useSideThreadTrigger(); + const panelRef = props.threadRef ?? null; const candidates = threadLinkCandidates(props.link, props.environmentId); const writtenRef = candidates[0]!; const written = useThreadShell(writtenRef); @@ -44,10 +48,8 @@ export function MarkdownThreadLink(props: { const linkedLabel = useLinkedEnvironments( connected || writtenRef.environmentId === props.environmentId ? null : props.environmentId, ).get(writtenRef.environmentId); - // A shell cached from an earlier connection does not make the thread open there now. Outside a - // thread there is no panel to read it in, so the link behaves as it does without one. + // A shell cached from an earlier connection does not make the thread open there now. const linked = - panelRef !== undefined && resolveLinkedThreadOpen({ environmentId: writtenRef.environmentId, viaEnvironmentId: props.environmentId, @@ -94,14 +96,22 @@ export function MarkdownThreadLink(props: { render={ - } - /> - - {canAddToChat - ? gt("Adds this side chat to the main thread's next message.") - : gt("Available after the first message.")} - - - - -
    - {shell === null ? ( - snapshotLoaded ? ( -

    - This side chat was deleted. -

    - ) : null - ) : ( - - - - - - )} -
    - ); -} diff --git a/apps/web/src/components/chat/SideThreadPane.tsx b/apps/web/src/components/chat/SideThreadPane.tsx new file mode 100644 index 0000000000000..9f32d90c4f8a7 --- /dev/null +++ b/apps/web/src/components/chat/SideThreadPane.tsx @@ -0,0 +1,210 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; +import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; +import { + isAtomCommandInterrupted, + settlePromise, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; +import { T, useGT } from "gt-react"; +import { Trash2Icon, XIcon } from "lucide-react"; +import { useEffect, useState } from "react"; + +import { useComposerDraftStore } from "../../composerDraftStore"; +import { ComposerHandleContext } from "../../composerHandleContext"; +import { useClientSettings } from "../../hooks/useSettings"; +import { releaseComposerDraftUploads } from "../../lib/composerDraftUploads"; +import type { SideChatParentPanel } from "../../lib/sideChatPane"; +import { readLocalApi } from "../../localApi"; +import { hostRightPanel, type ThreadSurface, useRightPanelStore } from "../../rightPanelStore"; +import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities"; +import { useEnvironmentScope } from "../../state/session"; +import { useEnvironmentShellStatus } from "../../state/shell"; +import { threadEnvironment, useEnvironmentThread } from "../../state/threads"; +import { + isThreadRouteSnapshotAuthoritative, + resolveThreadRouteRenderState, +} from "../../threadRoutes"; +import { useOpenThreadFamily } from "../ThreadRouteView"; +import { useAtomCommand } from "../../state/use-atom-command"; +import ChatView from "../ChatView"; +import { Button } from "../ui/button"; +import { toastManager } from "../ui/toast"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { BackgroundThreadContext } from "./backgroundThread"; + +/** + * A side chat or a subagent as a tab: the thread's own chat, which decides its bottom, the + * composer or the read-only bar, as it does on the main screen. The tab names it and closes it, + * so only a side chat, which has actions of its own, gets a header. + */ +export default function SideThreadPane(props: { + /** The thread whose panel shows the tab. */ + readonly parentRef: ScopedThreadRef; + readonly surface: ThreadSurface; + readonly parentPanel: SideChatParentPanel; + readonly onClose: () => void; +}) { + const { parentRef, surface } = props; + const { threadId } = surface; + const gt = useGT(); + const threadRef = scopeThreadRef(parentRef.environmentId, threadId); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store + useEffect( + () => hostRightPanel(scopeThreadRef(parentRef.environmentId, threadId), parentRef), + [parentRef, threadId], + ); + const shell = useQuietThreadShell(threadRef); + const bootstrapComplete = isThreadRouteSnapshotAuthoritative( + useEnvironmentShellStatus(parentRef.environmentId), + ); + // The shell can leave an idle subagent out, so its own detail says whether it still exists. + const unlistedDetail = useEnvironmentThread( + shell === null ? parentRef.environmentId : null, + shell === null ? threadId : null, + ); + useOpenThreadFamily(threadRef, bootstrapComplete && shell === null); + const renderState = resolveThreadRouteRenderState({ + bootstrapComplete, + serverThreadExists: shell !== null, + serverThreadDeleted: shell?.deletedAt != null, + unlistedThreadDetail: unlistedDetail, + draftThreadExists: false, + }); + const projection = useQuietThreadProjection(threadRef)?.projection; + const thread = shell ?? projection?.thread ?? null; + // A tab opens for side chats and subagents only, so an unloaded one is still one of them. + const kind = sideThreadKindOf(thread) ?? "subagent"; + const isSideChat = kind === "side-chat"; + const canOperate = useEnvironmentScope(parentRef.environmentId, AuthOrchestrationOperateScope); + const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false }); + const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete); + const [deleting, setDeleting] = useState(false); + // Closing an unused side chat deletes it, which would leave the link unreadable. + const canAddToChat = shell !== null && shell.latestUserMessageAt !== null; + const addToChat = () => { + if (!canAddToChat) return; + useComposerDraftStore + .getState() + .addThreadContexts(parentRef, [threadContextRecord(threadRef, shell.title)], { + insertAtCaret: false, + }); + }; + + const deleteSideChat = async () => { + if (!canOperate || shell === null || deleting) return; + if (confirmThreadDelete) { + const api = readLocalApi(); + if (!api) return; + const confirmed = await settlePromise(() => + api.dialogs.confirm( + [ + gt('Delete side chat "{title}"?', { title: shell.title }), + gt("This permanently clears its conversation history."), + ].join("\n"), + { variant: "destructive" }, + ), + ); + if (confirmed._tag === "Failure" || !confirmed.value) return; + } + setDeleting(true); + const result = await deleteThread({ + environmentId: parentRef.environmentId, + input: { threadId }, + }); + setDeleting(false); + if (result._tag === "Success") { + releaseComposerDraftUploads(threadRef); + useComposerDraftStore.getState().clearDraftThread(threadRef); + useRightPanelStore.getState().closeSurface(parentRef, surface.id); + } else if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: gt("Could not delete the side chat"), + ...(error instanceof Error ? { description: error.message } : {}), + }); + } + }; + + const title = + thread === null + ? isSideChat + ? gt("Side chat") + : gt("Subagent") + : isSideChat + ? thread.title + : formatSubagentDisplayTitle(thread.title); + + return ( +
    + {isSideChat ? ( +
    +

    {title}

    + + + Add to chat + + } + /> + + {canAddToChat + ? gt("Adds this side chat to the main thread's next message.") + : gt("Available after the first message.")} + + + + +
    + ) : null} + {renderState === "missing" ? ( +

    + {isSideChat ? ( + This side chat was deleted. + ) : ( + This thread is no longer available. + )} +

    + ) : renderState === "loading" && thread === null ? null : ( + + + + + + )} +
    + ); +} diff --git a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx index bb56a8a7d9bc9..5f47073bb965b 100644 --- a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx +++ b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx @@ -3,6 +3,8 @@ import { type SubagentWorkflowGroup, type RuntimeSubagent, } from "@t3tools/client-runtime/state/subagentRuntime"; +import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import { useSideThreadTrigger } from "../../hooks/useSideThreadTrigger"; import type { ProviderDriverKind, ProviderInstanceId, ServerProvider } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; import { ChevronDownIcon, SquareIcon } from "lucide-react"; @@ -73,9 +75,10 @@ function WorkflowMemberRow({ providers: ReadonlyArray | undefined; providerEntries: ReadonlyArray; driver: ProviderDriverKind | undefined; - onOpen: (threadId: string) => void; + onOpen: (threadId: string, intent: SideThreadOpenIntent) => void; }) { const gt = useGT(); + const trigger = useSideThreadTrigger(); const threadId = member.childThreadId; const canOpen = threadId !== null; return ( @@ -88,7 +91,7 @@ function WorkflowMemberRow({ part="row" aria-label={gt("Open {title} chat", { title: member.title })} disabled={!canOpen} - onClick={() => canOpen && onOpen(threadId)} + {...(canOpen ? trigger((intent) => onOpen(threadId, intent)) : {})} /> } > @@ -147,7 +150,7 @@ export function ThreadLineageWorkflowRow({ readonly providers: ReadonlyArray | undefined; readonly providerEntries: ReadonlyArray; readonly driver: ProviderDriverKind | undefined; - readonly onOpenThread: (threadId: string) => void; + readonly onOpenThread: (threadId: string, intent: SideThreadOpenIntent) => void; readonly onStop?: (() => void) | undefined; readonly stopping: boolean; readonly stopDisabled: boolean; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 914adf19777ad..052a5742b7aab 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -42,6 +42,9 @@ vi.mock(import("../../state/entities"), () => ({ useAnyEnvironmentHiding: (() => false) as never, })); vi.mock(import("../../state/environments"), () => ({ + // The click rule reads the client setting, whose module asks for these. + useEnvironments: (() => []) as never, + usePrimaryEnvironment: (() => null) as never, useEnvironment: (() => null) as never, useEnvironmentProviders: (() => new Map()) as never, })); @@ -61,7 +64,11 @@ vi.mock(import("../../state/use-atom-command"), () => ({ : AsyncResult.failure(Cause.fail(new Error("Connection lost")))) as never, })); +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; + import { render } from "../../../test/render"; +import { isMacPlatform } from "../../lib/utils"; +import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore"; import { makeThreadProjectionFixture } from "../../test-fixtures"; import { ScrollArea } from "../ui/scroll-area"; import { ToastProvider } from "../ui/toast"; @@ -71,6 +78,7 @@ const environmentId = EnvironmentId.make("environment"); const threadId = ThreadId.make("fork"); function setup() { + useRightPanelStore.setState(useRightPanelStore.getInitialState()); state.commandSucceeds = false; state.relatedShells = []; state.threadTitles = { source: "Source" }; @@ -168,7 +176,7 @@ it.each([ } }); -it("opens an idle child from Lineage when its shell has not been loaded", async () => { +it("opens an idle child beside the thread, and in its place with the modifier", async () => { setup(); const projection = makeThreadProjectionFixture(); const childId = ThreadId.make("omitted-child"); @@ -210,10 +218,22 @@ it("opens an idle child from Lineage when its shell has not been loaded", async await screen.getByRole("button", { name: /Previous agents/ }).click(); const child = screen.getByRole("button", { name: /Idle child/ }); await expect.element(child).toBeEnabled(); + const panelRef = scopeThreadRef(environmentId, projection.thread.id); + const panel = () => + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, panelRef); await child.click(); + expect(panel()).toMatchObject({ + isOpen: true, + activeSurfaceId: "thread:omitted-child", + surfaces: [{ kind: "thread", threadId: childId }], + }); + expect(screen.router?.state.location.pathname).toBe("/"); + // Idle children can be omitted from the shell; the route loads the child's own detail. + await child.click({ modifiers: [isMacPlatform(navigator.platform) ? "Meta" : "Control"] }); await vi.waitFor(() => expect(screen.router?.state.location.pathname).toBe("/local/omitted-child"), ); + expect(panel().surfaces).toHaveLength(1); }); it("shows a lineage thread's full title in its tooltip", async () => { diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 1c29eb147fce4..9675a21620d32 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -63,6 +63,7 @@ import type { MessageResolver } from "~/i18n/messages"; import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; import { buildThreadRouteParams } from "../../threadRoutes"; +import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; import { useLinkedThreadOpener } from "../../state/linkedThreadView"; import { useProjects, @@ -86,7 +87,8 @@ import { useEnvironmentQuery } from "../../state/query"; import { AgentElapsed } from "./AgentElapsed"; import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon"; import { ThreadLineageWorkflowRow } from "./ThreadLineageWorkflowRow"; -import { resolveThreadOpenRoute } from "../../lib/sideChatPane"; +import { useSideThreadTrigger } from "../../hooks/useSideThreadTrigger"; +import { openSideThread, resolveThreadOpenRoute } from "../../lib/sideChatPane"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -219,11 +221,11 @@ function relationshipHint( sideChat: boolean, resolve: MessageResolver, ) { - if (sideChat) return resolve(msg("Open side chat in this chat")); + if (sideChat) return resolve(msg("Open side chat")); if (edge.kind === "transfer") return resolve(msg("Open context transfer in this chat")); if (edge.kind === "subagent") { return edge.sourceThreadId === currentThreadId - ? resolve(msg("Open subagent in this chat")) + ? resolve(msg("Open subagent")) : resolve(msg("Open parent agent in this chat")); } return edge.sourceThreadId === currentThreadId @@ -301,13 +303,19 @@ function RemoteSubagentRow(props: { isSubagent: true, }); const opener = useLinkedThreadOpener(props.parentRef, remoteChild, title); + const trigger = useSideThreadTrigger(); return (
  • + } > { + openSideThread({ + threadRef: scopeThreadRef(props.environmentId, threadId), + panelRef: ref, + intent, + navigate: (threadRef) => + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }), + }); + }; + const merge = async () => { if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return; if (mergeErrorToastId.current !== null) { @@ -817,12 +840,12 @@ export function ThreadRelationshipsPanel(props: { ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0" : ""; const project = projects.find((project) => project.id === node?.thread?.projectId); - const hint = relationshipHint( - edge, - props.threadId, - node?.thread?.lineage.sideChat === true && !isParent, - m, - ); + const isSideChat = node?.thread?.lineage.sideChat === true && !isParent; + const hint = relationshipHint(edge, props.threadId, isSideChat, m); + const openProps = + isSideChat || (isSubagent && !isParent) + ? trigger((intent) => openSideThreadRow(threadId, intent)) + : { onClick: () => openThread(threadId) }; const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup; const relationshipTooltip = agent ? ( openThread(threadId)} + {...openProps} /> } > @@ -910,7 +933,9 @@ export function ThreadRelationshipsPanel(props: { providers={providers} providerEntries={providerEntries} driver={providerDriver} - onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)} + onOpenThread={(memberThreadId, intent) => + openSideThreadRow(memberThreadId as ThreadId, intent) + } onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined} stopping={stoppingId === agent.id} stopDisabled={stoppingId !== null} diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 6fc9ccc790e62..dc17bfcf95a72 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -288,7 +288,9 @@ function UserMessageContent({ row }: { row: Extract ctx.onOpenThread(ThreadId.make(threadId))} + onOpenThread={(threadId, intent) => + ctx.onOpenThread(ThreadId.make(threadId), undefined, intent) + } /> ) : resolveUserMessagePresentation(row.message).attribution === "automation" ? ( diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 6e09415faf91a..44d578ee19b73 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -2,8 +2,10 @@ import { T, Var, msg, useGT, useMessages } from "gt-react"; import { ThreadHoverCardPopup } from "../ThreadHoverCard"; import { AgentElapsed } from "./AgentElapsed"; import { projectedSubagentsToRuntime } from "@t3tools/client-runtime/state/subagentRuntime"; -import type { ReactNode } from "react"; +import { use, type ReactNode } from "react"; import { useThreadShell, useProject } from "../../state/entities"; +import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import { SideThreadsOpenContext, useSideThreadTrigger } from "../../hooks/useSideThreadTrigger"; import { useLinkedThreadOpener } from "../../state/linkedThreadView"; import { SubagentTooltipContent } from "./SubagentTooltipContent"; import { useAtomValue } from "@effect/atom-react"; @@ -75,7 +77,11 @@ export function V2LifecycleRow(props: { readonly environmentId: EnvironmentId; readonly resourceSummary?: boolean | undefined; readonly runs: ReadonlyArray; - readonly onOpenThread: (threadId: ThreadId) => void; + readonly onOpenThread: ( + threadId: ThreadId, + environmentId?: EnvironmentId, + intent?: SideThreadOpenIntent, + ) => void; }) { const { item } = props; const gt = useGT(); @@ -375,7 +381,11 @@ export function SubagentNotificationLink(props: { readonly outcome: OrchestrationV2Notification["outcome"]; readonly createdAt: string; readonly timestampFormat: TimestampFormat; - readonly onOpenThread: (threadId: ThreadId) => void; + readonly onOpenThread: ( + threadId: ThreadId, + environmentId?: EnvironmentId, + intent?: SideThreadOpenIntent, + ) => void; readonly fallback: ReactNode; }) { const gt = useGT(); @@ -437,7 +447,11 @@ function SubagentTimelineLink(props: { readonly threadId: ThreadId | null; /** The thread in a linked environment that runs this task, when it runs there. */ readonly remote?: OrchestrationV2RemoteTaskChild | undefined; - readonly onOpenThread: (threadId: ThreadId) => void; + readonly onOpenThread: ( + threadId: ThreadId, + environmentId?: EnvironmentId, + intent?: SideThreadOpenIntent, + ) => void; readonly event?: { readonly status: OrchestrationV2TurnItem["status"] | null; readonly label: string; @@ -454,8 +468,15 @@ function SubagentTimelineLink(props: { const threadId = props.threadId; // A task in a linked environment opens there, or read-only through this one. const remoteOpener = useLinkedThreadOpener(props.parentRef, remote, props.title); - const open = - threadId !== null ? () => props.onOpenThread(threadId) : (remoteOpener?.open ?? null); + const trigger = useSideThreadTrigger(); + const canOpen = use(SideThreadsOpenContext); + const open = !canOpen + ? null + : threadId !== null + ? (intent: SideThreadOpenIntent) => props.onOpenThread(threadId, undefined, intent) + : (remoteOpener?.open ?? null); + // A task on a connected linked environment opens there, on the main screen only. + const panel = threadId !== null || remoteOpener?.mode === "linked"; const liveStatus = agent?.status ?? props.status; const status = props.event ? props.event.status : liveStatus; const statusLabel = props.event?.label ?? m(subagentStatusVisual(liveStatus).label); @@ -540,7 +561,7 @@ function SubagentTimelineLink(props: { data-v2-item-type="subagent" aria-label={gt("Open {title}", { title: props.title })} aria-description={statusLabel} - onClick={open} + {...trigger(open, { panel })} className={cn( className, "cursor-pointer transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70", diff --git a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx index bc2955e0aabc9..19b0a97df033b 100644 --- a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx +++ b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx @@ -1,4 +1,6 @@ import { T, useGT, useMessages } from "gt-react"; +import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import { useSideThreadTrigger } from "../../hooks/useSideThreadTrigger"; import { useAtomValue } from "@effect/atom-react"; import { isTerminalSubagentStatus, @@ -39,7 +41,7 @@ function scriptMarkdown(script: string) { export function WorkflowOpeningBlock(props: { readonly opening: WorkflowOpening; readonly environmentId: EnvironmentId; - readonly onOpenThread: (threadId: string) => void; + readonly onOpenThread: (threadId: string, intent?: SideThreadOpenIntent) => void; }) { const gt = useGT(); const { opening } = props; @@ -113,9 +115,10 @@ function WorkflowMemberRow(props: { readonly providerInstanceId: ProviderInstanceId; readonly providers: ReadonlyArray; readonly driver: ProviderDriverKind | undefined; - readonly onOpenThread: (threadId: string) => void; + readonly onOpenThread: (threadId: string, intent?: SideThreadOpenIntent) => void; }) { const gt = useGT(); + const trigger = useSideThreadTrigger(); const { member } = props; const threadId = member.childThreadId; const failed = member.status === "failed"; @@ -142,7 +145,7 @@ function WorkflowMemberRow(props: { type="button" aria-label={gt("Open {title}", { title: member.title })} aria-description={member.status} - onClick={() => props.onOpenThread(threadId)} + {...trigger((intent) => props.onOpenThread(threadId, intent))} className={cn( className, "cursor-pointer transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70", diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 2373193588f06..5ff5c032db981 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -1,4 +1,5 @@ import type { ToolCallDiffTarget } from "../../diffPanelStore"; +import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; import type { ProviderApprovalDecision, ResponseContextRecord, @@ -85,6 +86,8 @@ export interface TimelineRowSharedState { onOpenThread: ( threadId: OrchestrationV2TurnItem["threadId"], environmentId?: EnvironmentId, + /** How the click asked to open a subagent or side chat; a plain click when absent. */ + intent?: SideThreadOpenIntent, ) => void; workflowOpening: WorkflowOpening | null; /** Absent hides "Fork from this response", as in the guest view. */ diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index c2da4e2f6dd5b..6769f93f2e192 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -8,6 +8,9 @@ import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-action import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { useStableCallback } from "../../hooks/useStableCallback"; import { type ScopedThreadRef, type RunId } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { sideThreadComposer, sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; +import { readThreadShell } from "../../state/entities"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { useEffect } from "react"; import { @@ -207,11 +210,19 @@ export function useRightPanelActions(input: RightPanelActionsInput) { if (surface.kind === "terminal") { focusTerminal(activeThreadRef, surface.activeTerminalId); } - if (surface.kind === "side-chat") { - requestWorkspaceFocus({ - area: "panel", - selector: `[data-side-chat-pane="${CSS.escape(surface.threadId)}"] [data-workspace-area="composer"] [contenteditable="true"]`, - }); + if (surface.kind === "thread") { + const kind = sideThreadKindOf( + readThreadShell(scopeThreadRef(activeThreadRef.environmentId, surface.threadId)), + ); + // A thread with no composer, or one not known yet, takes focus as any other tab does. + requestWorkspaceFocus( + kind !== null && sideThreadComposer(kind) === "composer" + ? { + area: "panel", + selector: `[data-side-chat-pane="${CSS.escape(surface.threadId)}"] [data-workspace-area="composer"] [contenteditable="true"]`, + } + : { area: "panel" }, + ); } if (surface.kind === "diff" && !diffOpen) { onDiffPanelOpen?.(); diff --git a/apps/web/src/components/chat/useSideChat.ts b/apps/web/src/components/chat/useSideChat.ts index 7a423f9f99a1b..805e6394ddb5a 100644 --- a/apps/web/src/components/chat/useSideChat.ts +++ b/apps/web/src/components/chat/useSideChat.ts @@ -120,7 +120,7 @@ export function useSideChat(input: { } else if (modelSelection !== undefined) { useComposerDraftStore.getState().setModelSelection(targetRef, modelSelection); } - useRightPanelStore.getState().openSideChat(threadRef, targetThreadId); + useRightPanelStore.getState().openThread(threadRef, targetThreadId); return true; }; const open = async (message?: SideChatMessage) => { diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx index 54989e73c4bc6..31dceea0ce919 100644 --- a/apps/web/src/components/chat/useThreadLifecycle.tsx +++ b/apps/web/src/components/chat/useThreadLifecycle.tsx @@ -79,7 +79,8 @@ import { useAtomValue } from "@effect/atom-react"; import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution"; import { Atom } from "effect/reactivity"; import { environmentThreadDetails } from "../../state/threads"; -import { resolveThreadOpenRoute } from "../../lib/sideChatPane"; +import { type SideThreadOpenIntent, sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; +import { openSideThread, resolveThreadOpenRoute } from "../../lib/sideChatPane"; import type { useLocalDispatchState } from "./useLocalDispatchState"; const RELATED_THREAD_SHELL_WAIT_MS = 1_000; @@ -474,9 +475,11 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork); const openRelatedThreadGenerationRef = useRef(0); // A task delegated to a linked environment opens there; the default is this thread's own. + // `intent` comes from the rows that open a subagent, and says the thread is one. const onOpenRelatedThread = async ( threadId: ThreadId, threadEnvironmentId: EnvironmentId = environmentId, + intent?: SideThreadOpenIntent, ) => { const generation = ++openRelatedThreadGenerationRef.current; const threadRef = scopeThreadRef(threadEnvironmentId, threadId); @@ -504,6 +507,21 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { toastManager.add({ type: "info", title: m(msg("This thread is no longer available")) }); return; } + // A subagent or side chat opens beside this thread or in its place; its own parent, like any + // other thread, only in its place. + if ( + (intent !== undefined || sideThreadKindOf(shell) !== null) && + activeThread?.lineage.parentThreadId !== threadId + ) { + openSideThread({ + threadRef, + panelRef: activeThreadRef, + intent: intent ?? "primary", + navigate: (ref) => + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }), + }); + return; + } const routeRef = resolveThreadOpenRoute(threadRef, shell); if (scopedThreadKey(routeRef) === routeThreadKey) return; void navigate({ diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index e0a12417848fa..493d8a1e79565 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -579,6 +579,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.followUpBehavior !== DEFAULT_UNIFIED_SETTINGS.followUpBehavior ? [gt("Follow-up behavior")] : []), + ...(settings.sideThreadOpenTarget !== DEFAULT_UNIFIED_SETTINGS.sideThreadOpenTarget + ? [gt("Open subagents and side chats in")] + : []), ...(settings.toolCallVisibility !== DEFAULT_UNIFIED_SETTINGS.toolCallVisibility ? [gt("Tool calls in chat")] : []), @@ -710,6 +713,7 @@ export function useSettingsRestore(onRestored?: () => void) { composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled, sendShortcut: DEFAULT_UNIFIED_SETTINGS.sendShortcut, followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior, + sideThreadOpenTarget: DEFAULT_UNIFIED_SETTINGS.sideThreadOpenTarget, toolCallVisibility: DEFAULT_UNIFIED_SETTINGS.toolCallVisibility, screenReaderAnnouncements: DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements, screenReaderWindowTitle: DEFAULT_UNIFIED_SETTINGS.screenReaderWindowTitle, @@ -1393,6 +1397,63 @@ export function ChatSettingsPanel() { /> + + + updateSettings({ + sideThreadOpenTarget: DEFAULT_UNIFIED_SETTINGS.sideThreadOpenTarget, + }) + } + /> + ) : null + } + control={ + + } + /> + + diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 52dadd9c8fb29..3949a9109190f 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -81,6 +81,12 @@ describe("searchSettings", () => { expect(searchSettings("1password").map((item) => item.to)).not.toContain("/settings/secrets"); }); + it("finds where subagents and side chats open by any of its names", () => { + for (const query of ["side panel", "subagent", "side chat", "linked thread", "middle click"]) { + expect(searchSettings(query).map((item) => item.id)).toContain("side-thread-open-target"); + } + }); + it("finds the Scheduled tasks page", () => { expect(searchSettings("scheduled tasks")[0]).toMatchObject({ id: "scheduled-tasks", diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 51ac4d7e19add..24d93790eb72a 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -805,6 +805,16 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/chat", searchTerms: [msg("queue steer running turn send default behavior composer")], }, + { + id: "side-thread-open-target", + title: msg("Open subagents and side chats in"), + to: "/settings/chat", + searchTerms: [ + msg( + "subagent side chat linked thread click right panel side panel main view command ctrl middle click", + ), + ], + }, { id: "provider-update-checks", title: msg("Provider update checks"), diff --git a/apps/web/src/hooks/useOpenSurfaceInMainView.ts b/apps/web/src/hooks/useOpenSurfaceInMainView.ts new file mode 100644 index 0000000000000..293569b3c4dd1 --- /dev/null +++ b/apps/web/src/hooks/useOpenSurfaceInMainView.ts @@ -0,0 +1,30 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; + +import { type LinkedThreadSurface, linkedThreadRouteParams } from "../linkedThreadSurface"; +import { type ThreadSurface, useRightPanelStore } from "../rightPanelStore"; +import { buildThreadRouteParams } from "../threadRoutes"; + +/** + * Moves a side thread's tab from `panelRef`'s panel to the main screen. The tab closes, without + * the cleanup Close does, so the way back does not show the thread beside itself. + */ +export function useOpenSurfaceInMainView(panelRef: ScopedThreadRef | null) { + const navigate = useNavigate(); + return (surface: ThreadSurface | LinkedThreadSurface) => { + if (panelRef === null) return; + useRightPanelStore.getState().closeSurface(panelRef, surface.id); + if (surface.kind === "linked-thread") { + void navigate({ + to: "/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId", + params: linkedThreadRouteParams(surface), + }); + return; + } + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(panelRef.environmentId, surface.threadId)), + }); + }; +} diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.ts b/apps/web/src/hooks/useRightPanelSurfaceClose.ts index e3a4dc72a79a0..978090d3ee61a 100644 --- a/apps/web/src/hooks/useRightPanelSurfaceClose.ts +++ b/apps/web/src/hooks/useRightPanelSurfaceClose.ts @@ -20,11 +20,9 @@ import { useRightPanelStore, type RightPanelSurface, } from "../rightPanelStore"; -import { appAtomRegistry } from "../rpc/atomRegistry"; import { readThreadShell } from "../state/entities"; import { previewEnvironment } from "../state/preview"; import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; -import { environmentShell } from "../state/shell"; import { threadEnvironment } from "../state/threads"; import { useAtomCommand } from "../state/use-atom-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; @@ -72,13 +70,12 @@ export function useRightPanelSurfaceClose(input: { } } if ( - surface.kind === "side-chat" && - readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope) && - // A live shell without the side chat means it is already deleted. - !( - appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live" && - readThreadShell(scopeThreadRef(ref.environmentId, surface.threadId)) === null - ) + surface.kind === "thread" && + // Only a side chat the shell still lists is thrown away with its tab; a subagent belongs to + // its parent's work, and an unlisted side chat is already deleted. + readThreadShell(scopeThreadRef(ref.environmentId, surface.threadId))?.lineage.sideChat === + true && + readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope) ) { // The server keeps a side chat with a run or message. Reopen skips one it deleted. void deleteThread({ diff --git a/apps/web/src/hooks/useSideThreadTrigger.ts b/apps/web/src/hooks/useSideThreadTrigger.ts new file mode 100644 index 0000000000000..381f042446e4a --- /dev/null +++ b/apps/web/src/hooks/useSideThreadTrigger.ts @@ -0,0 +1,65 @@ +import { + type SideThreadOpenIntent, + sideThreadOpenIntentOf, +} from "@t3tools/client-runtime/side-thread"; +import { useGT } from "gt-react"; +import { createContext, use, type KeyboardEvent, type MouseEvent } from "react"; + +import { contextMenuSourceOf } from "../contextMenuSource"; +import { isMacPlatform } from "../lib/utils"; +import { readLocalApi } from "../localApi"; + +/** + * False where the threads a view names cannot be opened from it, such as a read-only timeline + * with no environment behind it. Nothing that would open one is offered there. + */ +export const SideThreadsOpenContext = createContext(true); + +/** + * The handlers every row, card and chip that opens a subagent, a side chat or a linked thread + * shares: click and Enter open it where the setting says, the modifier or a middle click in the + * other place, and the context menu names both. Pass `panel: false` where no panel can show it. + * Where threads cannot be opened (`SideThreadsOpenContext`) it gives no handlers at all. + */ +export function useSideThreadTrigger() { + const gt = useGT(); + const canOpen = use(SideThreadsOpenContext); + return (open: (intent: SideThreadOpenIntent) => void, options?: { readonly panel?: boolean }) => { + if (!canOpen) return {}; + const mac = isMacPlatform(navigator.platform); + return { + onClick: (event: MouseEvent) => open(sideThreadOpenIntentOf(event, mac)), + // Middle button: keeps the browser's autoscroll from starting under the click. + onMouseDown: (event: MouseEvent) => { + if (event.button === 1) event.preventDefault(); + }, + onAuxClick: (event: MouseEvent) => { + if (event.button !== 1) return; + event.preventDefault(); + open("alternate"); + }, + onKeyDown: (event: KeyboardEvent) => { + if (event.key !== "Enter" || sideThreadOpenIntentOf(event, mac) !== "alternate") return; + event.preventDefault(); + open("alternate"); + }, + onContextMenu: (event: MouseEvent) => { + const api = readLocalApi(); + if (!api) return; + event.preventDefault(); + event.stopPropagation(); + const items = [ + ...(options?.panel === false + ? [] + : ([{ id: "panel", label: gt("Open in side panel") }] as const)), + { id: "main", label: gt("Open in main view") }, + ] as const; + void api.contextMenu + .show(items, { x: event.clientX, y: event.clientY }, contextMenuSourceOf(event)) + .then((clicked) => { + if (clicked === "panel" || clicked === "main") open(clicked); + }); + }, + }; + }; +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 6bf4e782aad8d..f49ef838a02e0 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2367,6 +2367,7 @@ "566810ac726b119a": "{title} stummschalten", "f6d1af395ae7bfcb": "Name des Geräte-Tabs", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "In Hauptansicht öffnen", "69ba5155e6e2ef95": "Umbenennen", "44c90f8f19346bfb": "Andere schließen", "e6cd4726a7513754": "Rechts davon schließen", @@ -2844,6 +2845,7 @@ "276c7fa42a15a542": "Aktualisiere ältere Server, um diese Einstellung zu speichern.", "52163ddccc1eb594": "Einstellung in einigen Umgebungen gespeichert", "fee07035b4a2a1c3": "Gespeichert auf {environments}.", + "2a1ecf7863e204aa": "In Seitenleiste öffnen", "8a7ee5752bb91550": "Kopieren fehlgeschlagen. Gib stattdessen {command} ein.", "7dfdfa116c6a9d86": "Einordnung konnte nicht gestartet werden", "25fe0f5f3ef3bb02": "{description} Führe stattdessen {command} in einem Terminal auf diesem Rechner aus.", @@ -3618,11 +3620,10 @@ " verknüpft. Der Agent kann diese Verknüpfung so verwenden; ändere den Zugriff unter Einstellungen → Umgebungen." ], "000b0df227182d39": "Andere Adresse…", + "fd07b24350a7643f": "einer verknüpften Umgebung", "6bb5b1b35b2796ae": "Auf {label} über {via} · Arbeitet", "a73b7ab25d6e9bdf": "Auf {label} über {via}", "009e2ca841fdc1ef": "diese Umgebung", - "8cb2e5692c4f05ab": "Öffne diesen Thread auf {label}, um diese Darstellung zu sehen.", - "745a0b899008618c": "Frühere Runden konnten nicht geladen werden. Versuche es erneut.", "4ab24e2807a0d82f": "Mit {label} verbunden", "b797c7beccf2dc46": "Dieses Gerät ist damit gekoppelt und kann seine Threads verwenden.", "d8c4a71a728fcf68": "Verbindung mit {label} wird hergestellt…", @@ -3630,8 +3631,11 @@ "a5424a5a76e10aa3": "Tritt einem Netzwerk bei, in dem es sich befindet, etwa seinem Tailscale-Netzwerk, und versuche es erneut. Du kannst hier weiterlesen.", "1942567fd95da447": "{label} benötigt einen Kopplungscode", "0f62d432499e13f9": "Erstelle dort einen und füge es diesem Gerät als Umgebung hinzu.", + "8cb2e5692c4f05ab": "Öffne diesen Thread auf {label}, um diese Darstellung zu sehen.", + "745a0b899008618c": "Frühere Runden konnten nicht geladen werden. Versuche es erneut.", "0014ce0aaf1bd68a": "Schreibgeschützt", "10ca916def8211d4": "Code eingeben", + "a446e3bda256c2b3": "Verbinden, um zu interagieren", "d0bda35aeec66684": [ "Wird von ", { @@ -3642,7 +3646,6 @@ " gelesen …" ], "c3e8cd9bf44e2f43": "Angezeigt wird, was zuvor gelesen wurde.", - "a446e3bda256c2b3": "Verbinden, um zu interagieren", "eb6e0584cf4a2a1d": "Sprache: {language}", "d76c606a3c519b78": "Zeilenumbruch deaktivieren", "2b683498cee8c8a7": "Zeilen umbrechen", @@ -3971,6 +3974,7 @@ "6a116665c8d9ad75": "Nebenchat schließen", "a5e57fdfde50aade": "Zum Chat hinzufügen", "492a438bf9dbd45d": "Dieser Nebenchat wurde gelöscht.", + "255a537ab23ddd2d": "Dieser Thread ist nicht mehr verfügbar.", "7350aa3df15b9802": "Skill {label}", "9ff9f24d1568fbaf": "Für diesen Skill ist keine Beschreibung verfügbar.", "274e087f814611a7": "Anweisungen anzeigen", @@ -4196,9 +4200,9 @@ "5e7eb0f2952de1b2": "Ersetzt", "59bcb9db3f0f59ea": "Inaktiv", "94124ad2133e3aed": "Unbekannt", - "1a6f6154d1cb51a9": "Nebenchat in diesem Chat öffnen", + "000646e27e304b8b": "Nebenchat öffnen", "56567586cbe00c86": "Kontextübergabe in diesem Chat öffnen", - "7fe7d5ae5fb4a655": "Subagent in diesem Chat öffnen", + "405e76cdd602bbcf": "Subagent öffnen", "520c15dbd507b804": "Übergeordneten Agenten in diesem Chat öffnen", "309b160785f6c473": "Fork in diesem Chat öffnen", "6676cd4b8299663f": "Übergeordneten Thread in diesem Chat öffnen", @@ -9833,6 +9837,7 @@ "2407d5d61e7f7206": "Rich-Text-Eingabefeld", "64b8fd2c284c3137": "Tastenkürzel zum Senden", "6163f91bddf474ae": "Verhalten bei Folgenachrichten", + "425021487583cf8a": "Subagenten und Nebenchats öffnen in", "856812e7e1fc445e": "Tool-Aufrufe im Chat", "216ed20b6f40fa6f": "Screenreader-Ansagen", "0ce04933a7047deb": "Fenstertitel für Screenreader", @@ -9890,6 +9895,12 @@ "1ea00f7b1a88ee2e": "Verhalten bei Folgenachrichten auf Standard zurücksetzen", "845e7f34c156ffd4": "Einreihen", "81a74689d0319316": "Umlenken", + "6dc57547546cbe96": "Subagenten und Nebenchats", + "ffbc33f6b6ddc689": "Wo ein Klick einen Subagenten, einen Nebenchat oder einen Thread in einer verknüpften Umgebung öffnet. {modifier}-Klick oder Mittelklick öffnet ihn stattdessen in der Hauptansicht.", + "7b7062c4b277e235": "Wo ein Klick einen Subagenten, einen Nebenchat oder einen Thread in einer verknüpften Umgebung öffnet. {modifier}-Klick oder Mittelklick öffnet ihn stattdessen in der Seitenleiste.", + "1eba4b1f5ae00974": "Öffnungsort für Subagenten und Nebenchats auf Standard zurücksetzen", + "f8062ccf65d4bb2a": "Seitenleiste", + "a8072bdf7ae4a288": "Hauptansicht", "162108e16ed96771": "Screenreader", "18807e775248380c": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", "5848a9c1d77f45b2": "Tool-Aufrufe im Chat auf Standard zurücksetzen", @@ -9973,6 +9984,8 @@ "b9ebecdb8db71466": "Systemstandard folgt dem Uhrzeitformat deines Browsers oder Betriebssystems.", "62f8a7774dc1ffb7": "Einreihen", "c711b55bc1500f08": "Umlenken", + "e79128045796685d": "Seitenleiste", + "d81dc62319ba223e": "Hauptansicht", "54139af0114a2729": "Rot & Grün (Standard)", "8d4a851d370639e4": "Blau & Orange", "b1d7c1ea891b7db5": "Ausgeklappt", @@ -11603,6 +11616,7 @@ "ade91c8927c48175": "eingabefeld rich text tiptap fett kursiv markdown formatiert wysiwyg", "34d74827c2a8b009": "enter return befehl strg ctrl mehrzeilig prompt neue zeile eingabefeld", "9d1013084c46ecce": "warteschlange einreihen umlenken laufende runde senden standardverhalten eingabefeld", + "e5e7f5e1fb1f2e4c": "subagent nebenchat verknüpfter thread klick rechte leiste seitenleiste hauptansicht befehl strg mittelklick", "5b8b854de7ee6f4d": "installierte cli versionen neuer verfügbar codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "fortsetzen laufende aktive unterbrochene arbeit neustart rechner absturz desktop update automatisch", "214a98497c4ed05d": "caffeinate ruhezustand verhindern wach bleiben energie laptop deckel inhibit", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 3ed9b5b0b09ca..ba8a96f2b96ae 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2367,6 +2367,7 @@ "566810ac726b119a": "Mute {title}", "f6d1af395ae7bfcb": "Device tab name", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "Open in main view", "69ba5155e6e2ef95": "Rename", "44c90f8f19346bfb": "Close others", "e6cd4726a7513754": "Close to the right", @@ -2843,6 +2844,7 @@ "276c7fa42a15a542": "Update older servers to save this setting.", "52163ddccc1eb594": "Setting saved on some environments", "fee07035b4a2a1c3": "Saved on {environments}.", + "2a1ecf7863e204aa": "Open in side panel", "8a7ee5752bb91550": "Could not copy. Type {command} instead.", "7dfdfa116c6a9d86": "Could not start triage", "25fe0f5f3ef3bb02": "{description} Run {command} in a terminal on that machine instead.", @@ -3617,11 +3619,10 @@ ". The agent can use that link as it is; change its access in Settings → Environments." ], "000b0df227182d39": "Another address…", + "fd07b24350a7643f": "a linked environment", "6bb5b1b35b2796ae": "On {label} via {via} · Working", "a73b7ab25d6e9bdf": "On {label} via {via}", "009e2ca841fdc1ef": "this environment", - "8cb2e5692c4f05ab": "Open this thread on {label} to see this visual.", - "745a0b899008618c": "Could not load earlier turns. Try again.", "4ab24e2807a0d82f": "Connected to {label}", "b797c7beccf2dc46": "This device is paired with it and can use its threads.", "d8c4a71a728fcf68": "Connecting to {label}…", @@ -3629,8 +3630,11 @@ "a5424a5a76e10aa3": "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.", "1942567fd95da447": "{label} needs a pairing code", "0f62d432499e13f9": "Create one on it, then add it to this device as an environment.", + "8cb2e5692c4f05ab": "Open this thread on {label} to see this visual.", + "745a0b899008618c": "Could not load earlier turns. Try again.", "0014ce0aaf1bd68a": "Read-only", "10ca916def8211d4": "Enter code", + "a446e3bda256c2b3": "Connect to interact", "d0bda35aeec66684": [ "Reading from ", { @@ -3641,7 +3645,6 @@ "…" ], "c3e8cd9bf44e2f43": "Showing what was read before.", - "a446e3bda256c2b3": "Connect to interact", "eb6e0584cf4a2a1d": "Language: {language}", "d76c606a3c519b78": "Disable line wrap", "2b683498cee8c8a7": "Wrap lines", @@ -3969,6 +3972,7 @@ "6a116665c8d9ad75": "Close side chat", "a5e57fdfde50aade": "Add to chat", "492a438bf9dbd45d": "This side chat was deleted.", + "255a537ab23ddd2d": "This thread is no longer available.", "7350aa3df15b9802": "Skill {label}", "9ff9f24d1568fbaf": "No description is available for this skill.", "274e087f814611a7": "View instructions", @@ -4195,9 +4199,9 @@ "5e7eb0f2952de1b2": "Superseded", "59bcb9db3f0f59ea": "Idle", "94124ad2133e3aed": "Unknown", - "1a6f6154d1cb51a9": "Open side chat in this chat", + "000646e27e304b8b": "Open side chat", "56567586cbe00c86": "Open context transfer in this chat", - "7fe7d5ae5fb4a655": "Open subagent in this chat", + "405e76cdd602bbcf": "Open subagent", "520c15dbd507b804": "Open parent agent in this chat", "309b160785f6c473": "Open fork in this chat", "6676cd4b8299663f": "Open parent thread in this chat", @@ -9842,6 +9846,7 @@ "2407d5d61e7f7206": "Rich text composer", "64b8fd2c284c3137": "Send shortcut", "6163f91bddf474ae": "Follow-up behavior", + "425021487583cf8a": "Open subagents and side chats in", "856812e7e1fc445e": "Tool calls in chat", "216ed20b6f40fa6f": "Screen reader announcements", "0ce04933a7047deb": "Screen reader window title", @@ -9899,6 +9904,12 @@ "1ea00f7b1a88ee2e": "Reset follow-up behavior to default", "845e7f34c156ffd4": "Queue", "81a74689d0319316": "Steer", + "6dc57547546cbe96": "Subagents and side chats", + "ffbc33f6b6ddc689": "Where a click opens a subagent, a side chat, or a thread on a linked environment. {modifier}-click or middle-click opens it in the main view instead.", + "7b7062c4b277e235": "Where a click opens a subagent, a side chat, or a thread on a linked environment. {modifier}-click or middle-click opens it in the side panel instead.", + "1eba4b1f5ae00974": "Reset where subagents and side chats open to default", + "f8062ccf65d4bb2a": "Side panel", + "a8072bdf7ae4a288": "Main view", "162108e16ed96771": "Screen reader", "18807e775248380c": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", "5848a9c1d77f45b2": "Reset tool calls in chat to default", @@ -9982,6 +9993,8 @@ "b9ebecdb8db71466": "System default follows your browser or OS clock preference.", "62f8a7774dc1ffb7": "Queue", "c711b55bc1500f08": "Steer", + "e79128045796685d": "Side panel", + "d81dc62319ba223e": "Main view", "54139af0114a2729": "Red & green (default)", "8d4a851d370639e4": "Blue & orange", "b1d7c1ea891b7db5": "Expanded", @@ -11611,6 +11624,7 @@ "ade91c8927c48175": "composer rich text tiptap bold italic markdown styled wysiwyg", "34d74827c2a8b009": "enter return command ctrl multiline prompt new line composer", "9d1013084c46ecce": "queue steer running turn send default behavior composer", + "e5e7f5e1fb1f2e4c": "subagent side chat linked thread click right panel side panel main view command ctrl middle click", "5b8b854de7ee6f4d": "installed cli versions newer available codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "resume running active interrupted work restart reboot machine crash desktop update automatically", "214a98497c4ed05d": "caffeinate sleep prevent stay awake power laptop lid inhibit", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index dd9280abac65f..2dc62e4340467 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2367,6 +2367,7 @@ "566810ac726b119a": "Silenciar {title}", "f6d1af395ae7bfcb": "Nombre de la pestaña del dispositivo", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "Abrir en la vista principal", "69ba5155e6e2ef95": "Cambiar nombre", "44c90f8f19346bfb": "Cerrar las demás", "e6cd4726a7513754": "Cerrar las de la derecha", @@ -2843,6 +2844,7 @@ "276c7fa42a15a542": "Actualiza los servidores antiguos para guardar este ajuste.", "52163ddccc1eb594": "Ajuste guardado en algunos entornos", "fee07035b4a2a1c3": "Guardado en {environments}.", + "2a1ecf7863e204aa": "Abrir en el panel lateral", "8a7ee5752bb91550": "No se pudo copiar. Escribe {command} en su lugar.", "7dfdfa116c6a9d86": "No se pudo iniciar el análisis", "25fe0f5f3ef3bb02": "{description} Ejecuta {command} en una terminal de esa máquina en su lugar.", @@ -3617,11 +3619,10 @@ ". El agente puede usar ese vínculo tal cual; cambia su acceso en Ajustes → Entornos." ], "000b0df227182d39": "Otra dirección…", + "fd07b24350a7643f": "un entorno vinculado", "6bb5b1b35b2796ae": "En {label} a través de {via} · Trabajando", "a73b7ab25d6e9bdf": "En {label} a través de {via}", "009e2ca841fdc1ef": "este entorno", - "8cb2e5692c4f05ab": "Abre este hilo en {label} para ver este elemento visual.", - "745a0b899008618c": "No se pudieron cargar los turnos anteriores. Vuelve a intentarlo.", "4ab24e2807a0d82f": "Conectado a {label}", "b797c7beccf2dc46": "Este dispositivo está emparejado con él y puede usar sus hilos.", "d8c4a71a728fcf68": "Conectando con {label}…", @@ -3629,8 +3630,11 @@ "a5424a5a76e10aa3": "Únete a una red en la que esté, como su red de Tailscale, y vuelve a intentarlo. Puedes seguir leyendo aquí.", "1942567fd95da447": "{label} necesita un código de emparejamiento", "0f62d432499e13f9": "Crea uno allí y añádelo a este dispositivo como entorno.", + "8cb2e5692c4f05ab": "Abre este hilo en {label} para ver este elemento visual.", + "745a0b899008618c": "No se pudieron cargar los turnos anteriores. Vuelve a intentarlo.", "0014ce0aaf1bd68a": "Solo lectura", "10ca916def8211d4": "Introducir código", + "a446e3bda256c2b3": "Conectar para interactuar", "d0bda35aeec66684": [ "Leyendo desde ", { @@ -3641,7 +3645,6 @@ "…" ], "c3e8cd9bf44e2f43": "Se muestra lo que se leyó antes.", - "a446e3bda256c2b3": "Conectar para interactuar", "eb6e0584cf4a2a1d": "Lenguaje: {language}", "d76c606a3c519b78": "Desactivar ajuste de línea", "2b683498cee8c8a7": "Ajustar líneas", @@ -3967,6 +3970,7 @@ "6a116665c8d9ad75": "Cerrar chat lateral", "a5e57fdfde50aade": "Añadir al chat", "492a438bf9dbd45d": "Este chat lateral se eliminó.", + "255a537ab23ddd2d": "Este hilo ya no está disponible.", "7350aa3df15b9802": "Skill {label}", "9ff9f24d1568fbaf": "No hay descripción disponible para esta skill.", "274e087f814611a7": "Ver instrucciones", @@ -4193,9 +4197,9 @@ "5e7eb0f2952de1b2": "Reemplazado", "59bcb9db3f0f59ea": "Inactivo", "94124ad2133e3aed": "Desconocido", - "1a6f6154d1cb51a9": "Abrir el chat lateral en este chat", + "000646e27e304b8b": "Abrir chat lateral", "56567586cbe00c86": "Abrir la transferencia de contexto en este chat", - "7fe7d5ae5fb4a655": "Abrir el subagente en este chat", + "405e76cdd602bbcf": "Abrir subagente", "520c15dbd507b804": "Abrir el agente principal en este chat", "309b160785f6c473": "Abrir la bifurcación en este chat", "6676cd4b8299663f": "Abrir el hilo principal en este chat", @@ -9830,6 +9834,7 @@ "2407d5d61e7f7206": "Cuadro de mensaje con texto enriquecido", "64b8fd2c284c3137": "Atajo de envío", "6163f91bddf474ae": "Comportamiento de los seguimientos", + "425021487583cf8a": "Abrir subagentes y chats laterales en", "856812e7e1fc445e": "Llamadas a herramientas en el chat", "216ed20b6f40fa6f": "Anuncios del lector de pantalla", "0ce04933a7047deb": "Título de ventana para el lector de pantalla", @@ -9887,6 +9892,12 @@ "1ea00f7b1a88ee2e": "Restablecer el comportamiento de los seguimientos al valor predeterminado", "845e7f34c156ffd4": "Poner en cola", "81a74689d0319316": "Redirigir", + "6dc57547546cbe96": "Subagentes y chats laterales", + "ffbc33f6b6ddc689": "Dónde abre un clic un subagente, un chat lateral o un hilo de un entorno vinculado. {modifier}-clic o el clic central lo abren en la vista principal.", + "7b7062c4b277e235": "Dónde abre un clic un subagente, un chat lateral o un hilo de un entorno vinculado. {modifier}-clic o el clic central lo abren en el panel lateral.", + "1eba4b1f5ae00974": "Restablecer dónde se abren los subagentes y chats laterales al valor predeterminado", + "f8062ccf65d4bb2a": "Panel lateral", + "a8072bdf7ae4a288": "Vista principal", "162108e16ed96771": "Lector de pantalla", "18807e775248380c": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", "5848a9c1d77f45b2": "Restablecer las llamadas a herramientas en el chat al valor predeterminado", @@ -9970,6 +9981,8 @@ "b9ebecdb8db71466": "Con «Del sistema» se usa el formato de hora de tu navegador o sistema operativo.", "62f8a7774dc1ffb7": "Poner en cola", "c711b55bc1500f08": "Redirigir", + "e79128045796685d": "Panel lateral", + "d81dc62319ba223e": "Vista principal", "54139af0114a2729": "Rojo y verde (predeterminado)", "8d4a851d370639e4": "Azul y naranja", "b1d7c1ea891b7db5": "Expandidos", @@ -11596,6 +11609,7 @@ "ade91c8927c48175": "cuadro mensaje compositor texto enriquecido tiptap negrita cursiva markdown con estilo wysiwyg", "34d74827c2a8b009": "enter intro comando ctrl multilínea prompt nueva línea cuadro mensaje compositor", "9d1013084c46ecce": "cola redirigir turno en ejecución enviar comportamiento predeterminado cuadro mensaje compositor", + "e5e7f5e1fb1f2e4c": "subagente chat lateral hilo vinculado clic panel derecho panel lateral vista principal comando ctrl clic central", "5b8b854de7ee6f4d": "instalado cli versiones más recientes disponibles codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "reanudar en ejecución activo interrumpido trabajo reiniciar máquina fallo actualización de escritorio automáticamente", "214a98497c4ed05d": "caffeinate reposo evitar mantener activo energía portátil tapa inhibir", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f4c23672f0cef..5b6f8fe3684fe 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2367,6 +2367,7 @@ "566810ac726b119a": "Couper le son de {title}", "f6d1af395ae7bfcb": "Nom de l’onglet de l’appareil", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "Ouvrir dans la vue principale", "69ba5155e6e2ef95": "Renommer", "44c90f8f19346bfb": "Fermer les autres", "e6cd4726a7513754": "Fermer les onglets à droite", @@ -2843,6 +2844,7 @@ "276c7fa42a15a542": "Mettez à jour les anciens serveurs pour enregistrer ce paramètre.", "52163ddccc1eb594": "Paramètre enregistré sur certains environnements", "fee07035b4a2a1c3": "Enregistré sur {environments}.", + "2a1ecf7863e204aa": "Ouvrir dans le panneau latéral", "8a7ee5752bb91550": "Copie impossible. Saisissez plutôt {command}.", "7dfdfa116c6a9d86": "Impossible de lancer le tri", "25fe0f5f3ef3bb02": "{description} Exécutez plutôt {command} dans un terminal sur cette machine.", @@ -3617,11 +3619,10 @@ ". L’agent peut utiliser cette association telle quelle ; modifiez son accès dans Paramètres → Environnements." ], "000b0df227182d39": "Autre adresse…", + "fd07b24350a7643f": "un environnement associé", "6bb5b1b35b2796ae": "Sur {label} via {via} · En cours", "a73b7ab25d6e9bdf": "Sur {label} via {via}", "009e2ca841fdc1ef": "cet environnement", - "8cb2e5692c4f05ab": "Ouvrez ce fil sur {label} pour voir ce visuel.", - "745a0b899008618c": "Impossible de charger les tours précédents. Réessayez.", "4ab24e2807a0d82f": "Connecté à {label}", "b797c7beccf2dc46": "Cet appareil y est appairé et peut utiliser ses fils.", "d8c4a71a728fcf68": "Connexion à {label}…", @@ -3629,8 +3630,11 @@ "a5424a5a76e10aa3": "Rejoignez un réseau sur lequel il se trouve, comme son réseau Tailscale, puis réessayez. Vous pouvez continuer à lire ici.", "1942567fd95da447": "{label} nécessite un code d’appairage", "0f62d432499e13f9": "Créez-en un dessus, puis ajoutez-le à cet appareil comme environnement.", + "8cb2e5692c4f05ab": "Ouvrez ce fil sur {label} pour voir ce visuel.", + "745a0b899008618c": "Impossible de charger les tours précédents. Réessayez.", "0014ce0aaf1bd68a": "Lecture seule", "10ca916def8211d4": "Saisir le code", + "a446e3bda256c2b3": "Se connecter pour interagir", "d0bda35aeec66684": [ "Lecture depuis ", { @@ -3641,7 +3645,6 @@ "…" ], "c3e8cd9bf44e2f43": "Affichage de ce qui a été lu auparavant.", - "a446e3bda256c2b3": "Se connecter pour interagir", "eb6e0584cf4a2a1d": "Langage : {language}", "d76c606a3c519b78": "Désactiver le retour à la ligne", "2b683498cee8c8a7": "Retour à la ligne", @@ -3968,6 +3971,7 @@ "6a116665c8d9ad75": "Fermer la discussion annexe", "a5e57fdfde50aade": "Ajouter à la discussion", "492a438bf9dbd45d": "Cette discussion annexe a été supprimée.", + "255a537ab23ddd2d": "Ce fil n’est plus disponible.", "7350aa3df15b9802": "Skill {label}", "9ff9f24d1568fbaf": "Aucune description n’est disponible pour ce skill.", "274e087f814611a7": "Voir les instructions", @@ -4194,9 +4198,9 @@ "5e7eb0f2952de1b2": "Remplacé", "59bcb9db3f0f59ea": "Inactif", "94124ad2133e3aed": "Inconnu", - "1a6f6154d1cb51a9": "Ouvrir la discussion annexe dans cette discussion", + "000646e27e304b8b": "Ouvrir la discussion annexe", "56567586cbe00c86": "Ouvrir le transfert de contexte dans cette discussion", - "7fe7d5ae5fb4a655": "Ouvrir le sous-agent dans cette discussion", + "405e76cdd602bbcf": "Ouvrir le sous-agent", "520c15dbd507b804": "Ouvrir l’agent parent dans cette discussion", "309b160785f6c473": "Ouvrir le fork dans cette discussion", "6676cd4b8299663f": "Ouvrir le fil parent dans cette discussion", @@ -9832,6 +9836,7 @@ "2407d5d61e7f7206": "Zone de saisie en texte enrichi", "64b8fd2c284c3137": "Raccourci d’envoi", "6163f91bddf474ae": "Comportement des relances", + "425021487583cf8a": "Ouvrir les sous-agents et discussions annexes dans", "856812e7e1fc445e": "Appels d’outils dans la discussion", "216ed20b6f40fa6f": "Annonces du lecteur d’écran", "0ce04933a7047deb": "Titre de fenêtre pour le lecteur d’écran", @@ -9889,6 +9894,12 @@ "1ea00f7b1a88ee2e": "Réinitialiser le comportement des relances à la valeur par défaut", "845e7f34c156ffd4": "File d’attente", "81a74689d0319316": "Réorienter", + "6dc57547546cbe96": "Sous-agents et discussions annexes", + "ffbc33f6b6ddc689": "Où un clic ouvre un sous-agent, une discussion annexe ou un fil d’un environnement associé. {modifier}-clic ou un clic du milieu l’ouvre plutôt dans la vue principale.", + "7b7062c4b277e235": "Où un clic ouvre un sous-agent, une discussion annexe ou un fil d’un environnement associé. {modifier}-clic ou un clic du milieu l’ouvre plutôt dans le panneau latéral.", + "1eba4b1f5ae00974": "Réinitialiser l’emplacement d’ouverture des sous-agents et discussions annexes à la valeur par défaut", + "f8062ccf65d4bb2a": "Panneau latéral", + "a8072bdf7ae4a288": "Vue principale", "162108e16ed96771": "Lecteur d’écran", "18807e775248380c": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", "5848a9c1d77f45b2": "Réinitialiser les appels d’outils dans la discussion à la valeur par défaut", @@ -9972,6 +9983,8 @@ "b9ebecdb8db71466": "L’option Système suit le format de l’heure de votre navigateur ou de votre OS.", "62f8a7774dc1ffb7": "File d’attente", "c711b55bc1500f08": "Réorienter", + "e79128045796685d": "Panneau latéral", + "d81dc62319ba223e": "Vue principale", "54139af0114a2729": "Rouge et vert (par défaut)", "8d4a851d370639e4": "Bleu et orange", "b1d7c1ea891b7db5": "Développés", @@ -11601,6 +11614,7 @@ "ade91c8927c48175": "zone de saisie texte enrichi tiptap gras italique markdown stylé wysiwyg", "34d74827c2a8b009": "entrée retour commande ctrl multiligne prompt nouvelle ligne zone de saisie", "9d1013084c46ecce": "file d’attente réorienter tour en cours envoyer comportement par défaut zone de saisie", + "e5e7f5e1fb1f2e4c": "sous-agent discussion annexe fil associé clic panneau droit panneau latéral vue principale commande ctrl clic du milieu", "5b8b854de7ee6f4d": "installé cli versions plus récentes disponibles codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "reprendre en cours actif interrompu travail redémarrer redémarrage machine plantage mise à jour bureau automatiquement", "214a98497c4ed05d": "caffeinate veille empêcher rester éveillé alimentation portable capot inhiber", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 7e2d260d010ba..925d388aaac83 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2365,6 +2365,7 @@ "566810ac726b119a": "{title} をミュート", "f6d1af395ae7bfcb": "デバイスタブの名前", "e7ba2fded155ecdd": "{title}、{state}", + "2906d1220b6a2872": "メインビューで開く", "69ba5155e6e2ef95": "名前を変更", "44c90f8f19346bfb": "その他を閉じる", "e6cd4726a7513754": "右側を閉じる", @@ -2841,6 +2842,7 @@ "276c7fa42a15a542": "この設定を保存するには古いサーバーを更新してください。", "52163ddccc1eb594": "一部の環境で設定を保存しました", "fee07035b4a2a1c3": "{environments} に保存しました。", + "2a1ecf7863e204aa": "サイドパネルで開く", "8a7ee5752bb91550": "コピーできませんでした。代わりに {command} と入力してください。", "7dfdfa116c6a9d86": "トリアージを開始できませんでした", "25fe0f5f3ef3bb02": "{description} 代わりに、そのマシンのターミナルで {command} を実行してください。", @@ -3612,11 +3614,10 @@ " にリンクされています。エージェントはそのリンクをそのまま使用できます。アクセス権は [設定] → [環境] で変更してください。" ], "000b0df227182d39": "別のアドレス…", + "fd07b24350a7643f": "リンクされた環境", "6bb5b1b35b2796ae": "{label}({via} 経由) · 作業中", "a73b7ab25d6e9bdf": "{label}({via} 経由)", "009e2ca841fdc1ef": "この環境", - "8cb2e5692c4f05ab": "このビジュアルを見るには、{label} でこのスレッドを開いてください。", - "745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。", "4ab24e2807a0d82f": "{label} に接続しました", "b797c7beccf2dc46": "このデバイスはペアリング済みで、そのスレッドを利用できます。", "d8c4a71a728fcf68": "{label} に接続しています…", @@ -3624,8 +3625,11 @@ "a5424a5a76e10aa3": "Tailscale ネットワークなど、そのマシンが接続しているネットワークに参加してから、もう一度お試しください。ここでは引き続き閲覧できます。", "1942567fd95da447": "{label} にはペアリングコードが必要です", "0f62d432499e13f9": "そのマシンで作成し、このデバイスに環境として追加してください。", + "8cb2e5692c4f05ab": "このビジュアルを見るには、{label} でこのスレッドを開いてください。", + "745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。", "0014ce0aaf1bd68a": "読み取り専用", "10ca916def8211d4": "コードを入力", + "a446e3bda256c2b3": "接続して操作する", "d0bda35aeec66684": [ "読み取り中: ", { @@ -3636,7 +3640,6 @@ "…" ], "c3e8cd9bf44e2f43": "以前に読み取った内容を表示しています。", - "a446e3bda256c2b3": "接続して操作する", "eb6e0584cf4a2a1d": "言語: {language}", "d76c606a3c519b78": "行の折り返しを無効にする", "2b683498cee8c8a7": "行を折り返す", @@ -3958,6 +3961,7 @@ "6a116665c8d9ad75": "サイドチャットを閉じる", "a5e57fdfde50aade": "チャットに追加", "492a438bf9dbd45d": "このサイドチャットは削除されました。", + "255a537ab23ddd2d": "このスレッドは利用できなくなりました。", "7350aa3df15b9802": "スキル {label}", "9ff9f24d1568fbaf": "このスキルには説明がありません。", "274e087f814611a7": "指示を表示", @@ -4184,9 +4188,9 @@ "5e7eb0f2952de1b2": "置き換え済み", "59bcb9db3f0f59ea": "アイドル", "94124ad2133e3aed": "不明", - "1a6f6154d1cb51a9": "このチャットでサイドチャットを開く", + "000646e27e304b8b": "サイドチャットを開く", "56567586cbe00c86": "このチャットでコンテキストの引き継ぎを開く", - "7fe7d5ae5fb4a655": "このチャットでサブエージェントを開く", + "405e76cdd602bbcf": "サブエージェントを開く", "520c15dbd507b804": "このチャットで親エージェントを開く", "309b160785f6c473": "このチャットでフォークを開く", "6676cd4b8299663f": "このチャットで親スレッドを開く", @@ -9784,6 +9788,7 @@ "2407d5d61e7f7206": "リッチテキスト入力欄", "64b8fd2c284c3137": "送信ショートカット", "6163f91bddf474ae": "フォローアップの動作", + "425021487583cf8a": "サブエージェントとサイドチャットを開く場所", "856812e7e1fc445e": "チャット内のツール呼び出し", "216ed20b6f40fa6f": "スクリーンリーダーの読み上げ", "0ce04933a7047deb": "スクリーンリーダー用のウィンドウタイトル", @@ -9841,6 +9846,12 @@ "1ea00f7b1a88ee2e": "フォローアップの動作をデフォルトにリセット", "845e7f34c156ffd4": "キュー", "81a74689d0319316": "軌道修正", + "6dc57547546cbe96": "サブエージェントとサイドチャット", + "ffbc33f6b6ddc689": "クリックでサブエージェント、サイドチャット、リンクされた環境のスレッドを開く場所です。{modifier} を押しながらクリックするか中クリックすると、代わりにメインビューで開きます。", + "7b7062c4b277e235": "クリックでサブエージェント、サイドチャット、リンクされた環境のスレッドを開く場所です。{modifier} を押しながらクリックするか中クリックすると、代わりにサイドパネルで開きます。", + "1eba4b1f5ae00974": "サブエージェントとサイドチャットを開く場所をデフォルトにリセット", + "f8062ccf65d4bb2a": "サイドパネル", + "a8072bdf7ae4a288": "メインビュー", "162108e16ed96771": "スクリーンリーダー", "18807e775248380c": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", "5848a9c1d77f45b2": "チャット内のツール呼び出しをデフォルトにリセット", @@ -9924,6 +9935,8 @@ "b9ebecdb8db71466": "「システムのデフォルト」を選ぶと、ブラウザーまたは OS の時刻形式に従います。", "62f8a7774dc1ffb7": "キュー", "c711b55bc1500f08": "軌道修正", + "e79128045796685d": "サイドパネル", + "d81dc62319ba223e": "メインビュー", "54139af0114a2729": "赤と緑 (デフォルト)", "8d4a851d370639e4": "青とオレンジ", "b1d7c1ea891b7db5": "展開", @@ -11551,6 +11564,7 @@ "ade91c8927c48175": "入力欄 リッチテキスト Tiptap 太字 斜体 Markdown スタイル WYSIWYG rich text", "34d74827c2a8b009": "Enter Return Command Ctrl 複数行 プロンプト 改行 入力欄 shortcut", "9d1013084c46ecce": "キュー 軌道修正 実行中 ターン 送信 デフォルト 動作 入力欄 queue steer", + "e5e7f5e1fb1f2e4c": "サブエージェント サイドチャット リンクされたスレッド クリック 右パネル サイドパネル メインビュー コマンド ctrl 中クリック", "5b8b854de7ee6f4d": "インストール済み CLI バージョン 新しい 利用可能 Codex Claude Cursor Grok fx Kiro OpenCode update", "64f12530d55d2ad1": "再開 実行中 アクティブ 中断 作業 再起動 マシン クラッシュ デスクトップ 更新 自動 resume", "214a98497c4ed05d": "caffeinate スリープ 防止 スリープしない 電源 ノートパソコン 蓋 inhibit sleep", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 6e9795c9f0fd6..f3db2a16565c7 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2366,6 +2366,7 @@ "566810ac726b119a": "{title} 음소거", "f6d1af395ae7bfcb": "기기 탭 이름", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "메인 보기에서 열기", "69ba5155e6e2ef95": "이름 바꾸기", "44c90f8f19346bfb": "다른 탭 닫기", "e6cd4726a7513754": "오른쪽 탭 닫기", @@ -2842,6 +2843,7 @@ "276c7fa42a15a542": "이 설정을 저장하려면 이전 서버를 업데이트하세요.", "52163ddccc1eb594": "일부 환경에만 설정이 저장됨", "fee07035b4a2a1c3": "{environments}에 저장되었습니다.", + "2a1ecf7863e204aa": "사이드 패널에서 열기", "8a7ee5752bb91550": "복사할 수 없습니다. 대신 {command}을(를) 입력하세요.", "7dfdfa116c6a9d86": "분류를 시작할 수 없습니다", "25fe0f5f3ef3bb02": "{description} 대신 해당 머신의 터미널에서 {command}을(를) 실행하세요.", @@ -3612,11 +3614,10 @@ "에 연결되어 있습니다. 에이전트는 이 연결을 그대로 사용할 수 있으며, 액세스는 설정 → 환경에서 변경하세요." ], "000b0df227182d39": "다른 주소…", + "fd07b24350a7643f": "연결된 환경", "6bb5b1b35b2796ae": "{label} ({via} 경유) · 작업 중", "a73b7ab25d6e9bdf": "{label} ({via} 경유)", "009e2ca841fdc1ef": "이 환경", - "8cb2e5692c4f05ab": "이 시각 자료를 보려면 {label}에서 이 스레드를 여세요.", - "745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.", "4ab24e2807a0d82f": "{label}에 연결됨", "b797c7beccf2dc46": "이 기기가 페어링되어 해당 스레드를 사용할 수 있습니다.", "d8c4a71a728fcf68": "{label}에 연결하는 중…", @@ -3624,8 +3625,11 @@ "a5424a5a76e10aa3": "Tailscale 네트워크처럼 해당 머신이 연결된 네트워크에 참여한 후 다시 시도하세요. 여기에서 계속 읽을 수 있습니다.", "1942567fd95da447": "{label}에 페어링 코드가 필요합니다", "0f62d432499e13f9": "해당 머신에서 코드를 만든 다음 이 기기에 환경으로 추가하세요.", + "8cb2e5692c4f05ab": "이 시각 자료를 보려면 {label}에서 이 스레드를 여세요.", + "745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.", "0014ce0aaf1bd68a": "읽기 전용", "10ca916def8211d4": "코드 입력", + "a446e3bda256c2b3": "연결하여 상호작용", "d0bda35aeec66684": [ "읽는 중: ", { @@ -3636,7 +3640,6 @@ "…" ], "c3e8cd9bf44e2f43": "이전에 읽은 내용을 표시하고 있습니다.", - "a446e3bda256c2b3": "연결하여 상호작용", "eb6e0584cf4a2a1d": "언어: {language}", "d76c606a3c519b78": "줄 바꿈 끄기", "2b683498cee8c8a7": "줄 바꿈", @@ -3956,6 +3959,7 @@ "6a116665c8d9ad75": "사이드 채팅 닫기", "a5e57fdfde50aade": "채팅에 추가", "492a438bf9dbd45d": "이 사이드 채팅은 삭제되었습니다.", + "255a537ab23ddd2d": "이 스레드를 더 이상 사용할 수 없습니다.", "7350aa3df15b9802": "스킬 {label}", "9ff9f24d1568fbaf": "이 스킬에 대한 설명이 없습니다.", "274e087f814611a7": "지침 보기", @@ -4181,9 +4185,9 @@ "5e7eb0f2952de1b2": "대체됨", "59bcb9db3f0f59ea": "유휴", "94124ad2133e3aed": "알 수 없음", - "1a6f6154d1cb51a9": "이 채팅에서 사이드 채팅 열기", + "000646e27e304b8b": "사이드 채팅 열기", "56567586cbe00c86": "이 채팅에서 컨텍스트 전달 열기", - "7fe7d5ae5fb4a655": "이 채팅에서 서브에이전트 열기", + "405e76cdd602bbcf": "서브에이전트 열기", "520c15dbd507b804": "이 채팅에서 상위 에이전트 열기", "309b160785f6c473": "이 채팅에서 포크 열기", "6676cd4b8299663f": "이 채팅에서 상위 스레드 열기", @@ -9787,6 +9791,7 @@ "2407d5d61e7f7206": "서식 있는 텍스트 입력창", "64b8fd2c284c3137": "보내기 단축키", "6163f91bddf474ae": "후속 메시지 동작", + "425021487583cf8a": "서브에이전트와 사이드 채팅을 여는 위치", "856812e7e1fc445e": "채팅의 도구 호출", "216ed20b6f40fa6f": "화면 낭독기 알림", "0ce04933a7047deb": "화면 낭독기 창 제목", @@ -9844,6 +9849,12 @@ "1ea00f7b1a88ee2e": "후속 메시지 동작 기본값으로 재설정", "845e7f34c156ffd4": "대기열", "81a74689d0319316": "방향 조정", + "6dc57547546cbe96": "서브에이전트와 사이드 채팅", + "ffbc33f6b6ddc689": "클릭했을 때 서브에이전트, 사이드 채팅 또는 연결된 환경의 스레드가 열리는 위치입니다. {modifier}-클릭 또는 가운데 클릭은 대신 메인 보기에서 엽니다.", + "7b7062c4b277e235": "클릭했을 때 서브에이전트, 사이드 채팅 또는 연결된 환경의 스레드가 열리는 위치입니다. {modifier}-클릭 또는 가운데 클릭은 대신 사이드 패널에서 엽니다.", + "1eba4b1f5ae00974": "서브에이전트와 사이드 채팅을 여는 위치 기본값으로 재설정", + "f8062ccf65d4bb2a": "사이드 패널", + "a8072bdf7ae4a288": "메인 보기", "162108e16ed96771": "화면 낭독기", "18807e775248380c": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", "5848a9c1d77f45b2": "채팅의 도구 호출 기본값으로 재설정", @@ -9927,6 +9938,8 @@ "b9ebecdb8db71466": "시스템 기본값은 브라우저 또는 OS의 시간 형식 설정을 따릅니다.", "62f8a7774dc1ffb7": "대기열", "c711b55bc1500f08": "방향 조정", + "e79128045796685d": "사이드 패널", + "d81dc62319ba223e": "메인 보기", "54139af0114a2729": "빨강 및 초록(기본값)", "8d4a851d370639e4": "파랑 및 주황", "b1d7c1ea891b7db5": "펼침", @@ -11548,6 +11561,7 @@ "ade91c8927c48175": "입력창 서식 있는 텍스트 tiptap 굵게 기울임 마크다운 스타일 wysiwyg", "34d74827c2a8b009": "enter return command ctrl 여러 줄 프롬프트 새 줄 입력창", "9d1013084c46ecce": "대기열 방향 조정 실행 중 턴 보내기 기본 동작 입력창", + "e5e7f5e1fb1f2e4c": "서브에이전트 사이드 채팅 연결된 스레드 클릭 오른쪽 패널 사이드 패널 메인 보기 커맨드 ctrl 가운데 클릭", "5b8b854de7ee6f4d": "설치된 CLI 버전 최신 사용 가능 Codex Claude Cursor Grok fx Kiro OpenCode", "64f12530d55d2ad1": "재개 실행 중 활성 중단된 작업 다시 시작 재부팅 머신 충돌 데스크톱 업데이트 자동", "214a98497c4ed05d": "caffeinate 절전 방지 깨어 있기 전원 노트북 덮개 inhibit", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index dc0dbfcad030c..13dbeaf291427 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2367,6 +2367,7 @@ "566810ac726b119a": "Silenciar {title}", "f6d1af395ae7bfcb": "Nome da aba do dispositivo", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "Abrir na visualização principal", "69ba5155e6e2ef95": "Renomear", "44c90f8f19346bfb": "Fechar as outras", "e6cd4726a7513754": "Fechar à direita", @@ -2843,6 +2844,7 @@ "276c7fa42a15a542": "Atualize os servidores mais antigos para salvar esta configuração.", "52163ddccc1eb594": "Configuração salva em alguns ambientes", "fee07035b4a2a1c3": "Salvo em {environments}.", + "2a1ecf7863e204aa": "Abrir no painel lateral", "8a7ee5752bb91550": "Não foi possível copiar. Digite {command}.", "7dfdfa116c6a9d86": "Não foi possível iniciar a triagem", "25fe0f5f3ef3bb02": "{description} Execute {command} em um terminal naquela máquina.", @@ -3617,11 +3619,10 @@ ". O agente pode usar esse vínculo como está; altere o acesso em Configurações → Ambientes." ], "000b0df227182d39": "Outro endereço…", + "fd07b24350a7643f": "um ambiente vinculado", "6bb5b1b35b2796ae": "Em {label} via {via} · Trabalhando", "a73b7ab25d6e9bdf": "Em {label} via {via}", "009e2ca841fdc1ef": "este ambiente", - "8cb2e5692c4f05ab": "Abra este thread em {label} para ver este visual.", - "745a0b899008618c": "Não foi possível carregar os turnos anteriores. Tente novamente.", "4ab24e2807a0d82f": "Conectado a {label}", "b797c7beccf2dc46": "Este dispositivo está pareado com ele e pode usar suas threads.", "d8c4a71a728fcf68": "Conectando a {label}…", @@ -3629,8 +3630,11 @@ "a5424a5a76e10aa3": "Entre em uma rede em que ele esteja, como a rede Tailscale dele, e tente novamente. Você pode continuar lendo aqui.", "1942567fd95da447": "{label} precisa de um código de pareamento", "0f62d432499e13f9": "Crie um nele e adicione-o a este dispositivo como ambiente.", + "8cb2e5692c4f05ab": "Abra este thread em {label} para ver este visual.", + "745a0b899008618c": "Não foi possível carregar os turnos anteriores. Tente novamente.", "0014ce0aaf1bd68a": "Somente leitura", "10ca916def8211d4": "Inserir código", + "a446e3bda256c2b3": "Conectar para interagir", "d0bda35aeec66684": [ "Lendo de ", { @@ -3641,7 +3645,6 @@ "…" ], "c3e8cd9bf44e2f43": "Mostrando o que foi lido antes.", - "a446e3bda256c2b3": "Conectar para interagir", "eb6e0584cf4a2a1d": "Linguagem: {language}", "d76c606a3c519b78": "Desativar quebra de linha", "2b683498cee8c8a7": "Quebrar linhas", @@ -3968,6 +3971,7 @@ "6a116665c8d9ad75": "Fechar chat paralelo", "a5e57fdfde50aade": "Adicionar ao chat", "492a438bf9dbd45d": "Este chat paralelo foi excluído.", + "255a537ab23ddd2d": "Esta thread não está mais disponível.", "7350aa3df15b9802": "Skill {label}", "9ff9f24d1568fbaf": "Não há descrição disponível para esta skill.", "274e087f814611a7": "Ver instruções", @@ -4193,9 +4197,9 @@ "5e7eb0f2952de1b2": "Substituído", "59bcb9db3f0f59ea": "Ocioso", "94124ad2133e3aed": "Desconhecido", - "1a6f6154d1cb51a9": "Abrir o chat paralelo neste chat", + "000646e27e304b8b": "Abrir chat paralelo", "56567586cbe00c86": "Abrir a transferência de contexto neste chat", - "7fe7d5ae5fb4a655": "Abrir o subagente neste chat", + "405e76cdd602bbcf": "Abrir subagente", "520c15dbd507b804": "Abrir o agente principal neste chat", "309b160785f6c473": "Abrir o fork neste chat", "6676cd4b8299663f": "Abrir a thread principal neste chat", @@ -9831,6 +9835,7 @@ "2407d5d61e7f7206": "Editor de texto formatado", "64b8fd2c284c3137": "Atalho de envio", "6163f91bddf474ae": "Comportamento de mensagens de acompanhamento", + "425021487583cf8a": "Abrir subagentes e chats paralelos em", "856812e7e1fc445e": "Chamadas de ferramentas no chat", "216ed20b6f40fa6f": "Anúncios do leitor de tela", "0ce04933a7047deb": "Título da janela para leitor de tela", @@ -9888,6 +9893,12 @@ "1ea00f7b1a88ee2e": "Redefinir o comportamento das mensagens de acompanhamento para o padrão", "845e7f34c156ffd4": "Enfileirar", "81a74689d0319316": "Direcionar", + "6dc57547546cbe96": "Subagentes e chats paralelos", + "ffbc33f6b6ddc689": "Onde um clique abre um subagente, um chat paralelo ou uma thread de um ambiente vinculado. {modifier}-clique ou o clique do meio abre na visualização principal.", + "7b7062c4b277e235": "Onde um clique abre um subagente, um chat paralelo ou uma thread de um ambiente vinculado. {modifier}-clique ou o clique do meio abre no painel lateral.", + "1eba4b1f5ae00974": "Redefinir onde subagentes e chats paralelos abrem para o padrão", + "f8062ccf65d4bb2a": "Painel lateral", + "a8072bdf7ae4a288": "Visualização principal", "162108e16ed96771": "Leitor de tela", "18807e775248380c": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", "5848a9c1d77f45b2": "Redefinir as chamadas de ferramentas no chat para o padrão", @@ -9971,6 +9982,8 @@ "b9ebecdb8db71466": "\"Padrão do sistema\" usa o formato de horário do navegador ou do sistema operacional.", "62f8a7774dc1ffb7": "Enfileirar", "c711b55bc1500f08": "Direcionar", + "e79128045796685d": "Painel lateral", + "d81dc62319ba223e": "Visualização principal", "54139af0114a2729": "Vermelho e verde (padrão)", "8d4a851d370639e4": "Azul e laranja", "b1d7c1ea891b7db5": "Expandido", @@ -11600,6 +11613,7 @@ "ade91c8927c48175": "editor de mensagens rich text tiptap negrito itálico markdown estilizado wysiwyg", "34d74827c2a8b009": "enter return command ctrl várias linhas prompt nova linha editor de mensagens", "9d1013084c46ecce": "fila enfileirar direcionar turno em execução enviar comportamento padrão editor de mensagens", + "e5e7f5e1fb1f2e4c": "subagente chat paralelo thread vinculada clique painel direito painel lateral visualização principal comando ctrl clique do meio", "5b8b854de7ee6f4d": "cli instaladas versões mais novas disponíveis codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "retomar em execução ativo interrompido trabalho reiniciar reboot máquina falha atualização do desktop automaticamente", "214a98497c4ed05d": "caffeinate repouso impedir manter acordado energia notebook tampa inibir", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 31b603d4b2b59..fa60799c89a78 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2367,6 +2367,7 @@ "566810ac726b119a": "Выключить звук: {title}", "f6d1af395ae7bfcb": "Название вкладки устройства", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "Открыть в основном окне", "69ba5155e6e2ef95": "Переименовать", "44c90f8f19346bfb": "Закрыть остальные", "e6cd4726a7513754": "Закрыть справа", @@ -2843,6 +2844,7 @@ "276c7fa42a15a542": "Обновите старые серверы, чтобы сохранить эту настройку.", "52163ddccc1eb594": "Настройка сохранена в некоторых окружениях", "fee07035b4a2a1c3": "Сохранено на {environments}.", + "2a1ecf7863e204aa": "Открыть в боковой панели", "8a7ee5752bb91550": "Не удалось скопировать. Введите {command} вручную.", "7dfdfa116c6a9d86": "Не удалось начать разбор проблемы", "25fe0f5f3ef3bb02": "{description} Вместо этого выполните {command} в терминале на той машине.", @@ -3617,11 +3619,10 @@ ". Агент может использовать эту привязку как есть; изменить её доступ можно в «Настройки → Окружения»." ], "000b0df227182d39": "Другой адрес…", + "fd07b24350a7643f": "привязанном окружении", "6bb5b1b35b2796ae": "На {label} через {via} · Работает", "a73b7ab25d6e9bdf": "На {label} через {via}", "009e2ca841fdc1ef": "это окружение", - "8cb2e5692c4f05ab": "Откройте этот тред на {label}, чтобы увидеть это визуальное представление.", - "745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.", "4ab24e2807a0d82f": "Подключено к {label}", "b797c7beccf2dc46": "Это устройство сопряжено с ним и может работать с его тредами.", "d8c4a71a728fcf68": "Подключение к {label}…", @@ -3629,8 +3630,11 @@ "a5424a5a76e10aa3": "Подключитесь к сети, в которой оно находится, например к его сети Tailscale, и повторите попытку. Здесь можно продолжать чтение.", "1942567fd95da447": "Для {label} нужен код сопряжения", "0f62d432499e13f9": "Создайте его там и добавьте эту машину на устройство как окружение.", + "8cb2e5692c4f05ab": "Откройте этот тред на {label}, чтобы увидеть это визуальное представление.", + "745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.", "0014ce0aaf1bd68a": "Только чтение", "10ca916def8211d4": "Ввести код", + "a446e3bda256c2b3": "Подключиться для взаимодействия", "d0bda35aeec66684": [ "Чтение с ", { @@ -3641,7 +3645,6 @@ "…" ], "c3e8cd9bf44e2f43": "Показано то, что было прочитано раньше.", - "a446e3bda256c2b3": "Подключиться для взаимодействия", "eb6e0584cf4a2a1d": "Язык: {language}", "d76c606a3c519b78": "Отключить перенос строк", "2b683498cee8c8a7": "Переносить строки", @@ -3968,6 +3971,7 @@ "6a116665c8d9ad75": "Закрыть боковой чат", "a5e57fdfde50aade": "Добавить в чат", "492a438bf9dbd45d": "Этот боковой чат удалён.", + "255a537ab23ddd2d": "Этот тред больше недоступен.", "7350aa3df15b9802": "Навык {label}", "9ff9f24d1568fbaf": "У этого навыка нет описания.", "274e087f814611a7": "Показать инструкции", @@ -4193,9 +4197,9 @@ "5e7eb0f2952de1b2": "Заменён", "59bcb9db3f0f59ea": "Простаивает", "94124ad2133e3aed": "Неизвестно", - "1a6f6154d1cb51a9": "Открыть боковой чат в этом чате", + "000646e27e304b8b": "Открыть боковой чат", "56567586cbe00c86": "Открыть передачу контекста в этом чате", - "7fe7d5ae5fb4a655": "Открыть субагента в этом чате", + "405e76cdd602bbcf": "Открыть субагента", "520c15dbd507b804": "Открыть родительского агента в этом чате", "309b160785f6c473": "Открыть ответвление в этом чате", "6676cd4b8299663f": "Открыть родительский тред в этом чате", @@ -9834,6 +9838,7 @@ "2407d5d61e7f7206": "Поле ввода с форматированием", "64b8fd2c284c3137": "Сочетание для отправки", "6163f91bddf474ae": "Поведение дополнительных сообщений", + "425021487583cf8a": "Открывать субагентов и боковые чаты в", "856812e7e1fc445e": "Вызовы инструментов в чате", "216ed20b6f40fa6f": "Объявления для экранного диктора", "0ce04933a7047deb": "Заголовок окна для экранного диктора", @@ -9891,6 +9896,12 @@ "1ea00f7b1a88ee2e": "Сбросить поведение дополнительных сообщений к значению по умолчанию", "845e7f34c156ffd4": "Очередь", "81a74689d0319316": "Корректировка", + "6dc57547546cbe96": "Субагенты и боковые чаты", + "ffbc33f6b6ddc689": "Где по щелчку открывается субагент, боковой чат или тред в привязанном окружении. {modifier}-щелчок или щелчок средней кнопкой открывает его в основном окне.", + "7b7062c4b277e235": "Где по щелчку открывается субагент, боковой чат или тред в привязанном окружении. {modifier}-щелчок или щелчок средней кнопкой открывает его в боковой панели.", + "1eba4b1f5ae00974": "Сбросить место открытия субагентов и боковых чатов к значению по умолчанию", + "f8062ccf65d4bb2a": "Боковая панель", + "a8072bdf7ae4a288": "Основное окно", "162108e16ed96771": "Экранный диктор", "18807e775248380c": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", "5848a9c1d77f45b2": "Сбросить вызовы инструментов в чате к значению по умолчанию", @@ -9974,6 +9985,8 @@ "b9ebecdb8db71466": "«Как в системе» использует формат времени браузера или ОС.", "62f8a7774dc1ffb7": "Очередь", "c711b55bc1500f08": "Корректировка", + "e79128045796685d": "Боковая панель", + "d81dc62319ba223e": "Основное окно", "54139af0114a2729": "Красный и зелёный (по умолчанию)", "8d4a851d370639e4": "Синий и оранжевый", "b1d7c1ea891b7db5": "Развёрнуты", @@ -11601,6 +11614,7 @@ "ade91c8927c48175": "поле ввода форматирование tiptap жирный курсив markdown стили wysiwyg", "34d74827c2a8b009": "enter return command ctrl многострочный промпт новая строка поле ввода", "9d1013084c46ecce": "очередь корректировка выполняющийся ход отправить поведение по умолчанию поле ввода", + "e5e7f5e1fb1f2e4c": "субагент боковой чат привязанный тред щелчок правая панель боковая панель основное окно command ctrl средняя кнопка", "5b8b854de7ee6f4d": "установленные cli версии новее доступно codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "возобновить выполняющаяся активная прерванная работа перезапуск перезагрузка компьютер сбой обновление десктоп автоматически", "214a98497c4ed05d": "caffeinate сон не давать уснуть бодрствование питание ноутбук крышка блокировать", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index a0f86175e48e3..7cb5b4f31ead7 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2367,6 +2367,7 @@ "566810ac726b119a": "Stäng av ljudet för {title}", "f6d1af395ae7bfcb": "Namn på enhetsflik", "e7ba2fded155ecdd": "{title}, {state}", + "2906d1220b6a2872": "Öppna i huvudvyn", "69ba5155e6e2ef95": "Byt namn", "44c90f8f19346bfb": "Stäng andra", "e6cd4726a7513754": "Stäng till höger", @@ -2843,6 +2844,7 @@ "276c7fa42a15a542": "Uppdatera äldre servrar för att spara den här inställningen.", "52163ddccc1eb594": "Inställningen sparades i vissa miljöer", "fee07035b4a2a1c3": "Sparat på {environments}.", + "2a1ecf7863e204aa": "Öppna i sidopanelen", "8a7ee5752bb91550": "Kunde inte kopiera. Skriv {command} i stället.", "7dfdfa116c6a9d86": "Kunde inte starta felsökningen", "25fe0f5f3ef3bb02": "{description} Kör {command} i en terminal på den datorn i stället.", @@ -3617,11 +3619,10 @@ ". Agenten kan använda den länken som den är; ändra dess åtkomst under Inställningar → Miljöer." ], "000b0df227182d39": "En annan adress…", + "fd07b24350a7643f": "en länkad miljö", "6bb5b1b35b2796ae": "På {label} via {via} · Arbetar", "a73b7ab25d6e9bdf": "På {label} via {via}", "009e2ca841fdc1ef": "den här miljön", - "8cb2e5692c4f05ab": "Öppna den här tråden på {label} för att se den här visualiseringen.", - "745a0b899008618c": "Kunde inte läsa in tidigare omgångar. Försök igen.", "4ab24e2807a0d82f": "Ansluten till {label}", "b797c7beccf2dc46": "Den här enheten är parkopplad med den och kan använda dess trådar.", "d8c4a71a728fcf68": "Ansluter till {label}…", @@ -3629,8 +3630,11 @@ "a5424a5a76e10aa3": "Anslut till ett nätverk som den finns på, till exempel dess Tailscale-nätverk, och försök igen. Du kan fortsätta läsa här.", "1942567fd95da447": "{label} behöver en parkopplingskod", "0f62d432499e13f9": "Skapa en där och lägg till den på den här enheten som en miljö.", + "8cb2e5692c4f05ab": "Öppna den här tråden på {label} för att se den här visualiseringen.", + "745a0b899008618c": "Kunde inte läsa in tidigare omgångar. Försök igen.", "0014ce0aaf1bd68a": "Skrivskyddad", "10ca916def8211d4": "Ange kod", + "a446e3bda256c2b3": "Anslut för att interagera", "d0bda35aeec66684": [ "Läser från ", { @@ -3641,7 +3645,6 @@ "…" ], "c3e8cd9bf44e2f43": "Visar det som lästes tidigare.", - "a446e3bda256c2b3": "Anslut för att interagera", "eb6e0584cf4a2a1d": "Språk: {language}", "d76c606a3c519b78": "Inaktivera radbrytning", "2b683498cee8c8a7": "Bryt rader", @@ -3968,6 +3971,7 @@ "6a116665c8d9ad75": "Stäng sidochatt", "a5e57fdfde50aade": "Lägg till i chatten", "492a438bf9dbd45d": "Den här sidochatten togs bort.", + "255a537ab23ddd2d": "Den här tråden är inte längre tillgänglig.", "7350aa3df15b9802": "Färdighet {label}", "9ff9f24d1568fbaf": "Ingen beskrivning finns för den här färdigheten.", "274e087f814611a7": "Visa instruktioner", @@ -4194,9 +4198,9 @@ "5e7eb0f2952de1b2": "Ersatt", "59bcb9db3f0f59ea": "Inaktiv", "94124ad2133e3aed": "Okänd", - "1a6f6154d1cb51a9": "Öppna sidochatten i den här chatten", + "000646e27e304b8b": "Öppna sidochatt", "56567586cbe00c86": "Öppna kontextöverföringen i den här chatten", - "7fe7d5ae5fb4a655": "Öppna subagenten i den här chatten", + "405e76cdd602bbcf": "Öppna subagent", "520c15dbd507b804": "Öppna den överordnade agenten i den här chatten", "309b160785f6c473": "Öppna forken i den här chatten", "6676cd4b8299663f": "Öppna den överordnade tråden i den här chatten", @@ -9840,6 +9844,7 @@ "2407d5d61e7f7206": "Inmatningsfält med formaterad text", "64b8fd2c284c3137": "Kortkommando för att skicka", "6163f91bddf474ae": "Beteende för uppföljningar", + "425021487583cf8a": "Öppna subagenter och sidochattar i", "856812e7e1fc445e": "Verktygsanrop i chatten", "216ed20b6f40fa6f": "Uppläsningar för skärmläsare", "0ce04933a7047deb": "Fönstertitel för skärmläsare", @@ -9897,6 +9902,12 @@ "1ea00f7b1a88ee2e": "Återställ beteende för uppföljningar till standard", "845e7f34c156ffd4": "Köa", "81a74689d0319316": "Styr om", + "6dc57547546cbe96": "Subagenter och sidochattar", + "ffbc33f6b6ddc689": "Var ett klick öppnar en subagent, en sidochatt eller en tråd i en länkad miljö. {modifier}-klick eller mittenklick öppnar den i huvudvyn i stället.", + "7b7062c4b277e235": "Var ett klick öppnar en subagent, en sidochatt eller en tråd i en länkad miljö. {modifier}-klick eller mittenklick öppnar den i sidopanelen i stället.", + "1eba4b1f5ae00974": "Återställ var subagenter och sidochattar öppnas till standard", + "f8062ccf65d4bb2a": "Sidopanel", + "a8072bdf7ae4a288": "Huvudvy", "162108e16ed96771": "Skärmläsare", "18807e775248380c": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", "5848a9c1d77f45b2": "Återställ verktygsanrop i chatten till standard", @@ -9980,6 +9991,8 @@ "b9ebecdb8db71466": "Systemstandard följer webbläsarens eller operativsystemets klockinställning.", "62f8a7774dc1ffb7": "Köa", "c711b55bc1500f08": "Styr om", + "e79128045796685d": "Sidopanel", + "d81dc62319ba223e": "Huvudvy", "54139af0114a2729": "Rött och grönt (standard)", "8d4a851d370639e4": "Blått och orange", "b1d7c1ea891b7db5": "Utfällda", @@ -11609,6 +11622,7 @@ "ade91c8927c48175": "inmatningsfält formaterad text tiptap fet kursiv markdown formaterad wysiwyg", "34d74827c2a8b009": "enter retur command ctrl flera rader prompt ny rad inmatningsfält", "9d1013084c46ecce": "kö styr om pågående omgång skicka standardbeteende inmatningsfält", + "e5e7f5e1fb1f2e4c": "subagent sidochatt länkad tråd klick högerpanel sidopanel huvudvy kommando ctrl mittenklick", "5b8b854de7ee6f4d": "installerade cli versioner nyare tillgänglig codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "återuppta pågående aktiv avbrutet arbete omstart starta om dator krasch skrivbord uppdatering automatiskt", "214a98497c4ed05d": "caffeinate viloläge förhindra håll vaken ström laptop lock förhindra", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 312065925ba94..264cdc880110f 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2371,6 +2371,7 @@ "566810ac726b119a": "将 {title} 静音", "f6d1af395ae7bfcb": "设备标签名", "e7ba2fded155ecdd": "{title},{state}", + "2906d1220b6a2872": "在主视图中打开", "69ba5155e6e2ef95": "重命名", "44c90f8f19346bfb": "关闭其他标签", "e6cd4726a7513754": "关闭右侧标签", @@ -2847,6 +2848,7 @@ "276c7fa42a15a542": "请更新旧版服务器后再保存此设置。", "52163ddccc1eb594": "部分环境已保存设置", "fee07035b4a2a1c3": "已在 {environments} 上保存。", + "2a1ecf7863e204aa": "在侧边面板中打开", "8a7ee5752bb91550": "无法复制。请改为输入 {command}。", "7dfdfa116c6a9d86": "无法开始问题排查", "25fe0f5f3ef3bb02": "{description} 请改为在那台机器的终端中运行 {command}。", @@ -3622,11 +3624,10 @@ "。智能体可以直接使用该关联;请在“设置 → 环境”中更改其访问权限。" ], "000b0df227182d39": "其他地址…", + "fd07b24350a7643f": "关联环境", "6bb5b1b35b2796ae": "位于 {label},经由 {via} · 运行中", "a73b7ab25d6e9bdf": "位于 {label},经由 {via}", "009e2ca841fdc1ef": "此环境", - "8cb2e5692c4f05ab": "在 {label} 上打开此会话即可查看此可视内容。", - "745a0b899008618c": "无法加载更早的对话。请重试。", "4ab24e2807a0d82f": "已连接到 {label}", "b797c7beccf2dc46": "此设备已与其配对,可以使用其中的会话。", "d8c4a71a728fcf68": "正在连接 {label}…", @@ -3634,8 +3635,11 @@ "a5424a5a76e10aa3": "请加入它所在的网络(例如其 Tailscale 网络),然后重试。你仍可在此继续阅读。", "1942567fd95da447": "{label} 需要配对码", "0f62d432499e13f9": "在该机器上创建配对码,然后将其作为环境添加到此设备。", + "8cb2e5692c4f05ab": "在 {label} 上打开此会话即可查看此可视内容。", + "745a0b899008618c": "无法加载更早的对话。请重试。", "0014ce0aaf1bd68a": "只读", "10ca916def8211d4": "输入配对码", + "a446e3bda256c2b3": "连接以进行交互", "d0bda35aeec66684": [ "正在从 ", { @@ -3646,7 +3650,6 @@ " 读取…" ], "c3e8cd9bf44e2f43": "正在显示之前读取的内容。", - "a446e3bda256c2b3": "连接以进行交互", "eb6e0584cf4a2a1d": "语言:{language}", "d76c606a3c519b78": "取消自动换行", "2b683498cee8c8a7": "自动换行", @@ -3973,6 +3976,7 @@ "6a116665c8d9ad75": "关闭侧聊", "a5e57fdfde50aade": "添加到对话", "492a438bf9dbd45d": "这段侧聊已删除。", + "255a537ab23ddd2d": "这个会话已不可用。", "7350aa3df15b9802": "技能 {label}", "9ff9f24d1568fbaf": "这个技能没有描述。", "274e087f814611a7": "查看说明", @@ -4200,9 +4204,9 @@ "5e7eb0f2952de1b2": "已被替代", "59bcb9db3f0f59ea": "闲置", "94124ad2133e3aed": "未知", - "1a6f6154d1cb51a9": "在此对话中打开侧聊", + "000646e27e304b8b": "打开侧聊", "56567586cbe00c86": "在此对话中打开上下文转移", - "7fe7d5ae5fb4a655": "在此对话中打开子智能体", + "405e76cdd602bbcf": "打开子智能体", "520c15dbd507b804": "在此对话中打开父智能体", "309b160785f6c473": "在此对话中打开分叉", "6676cd4b8299663f": "在此对话中打开父会话", @@ -9847,6 +9851,7 @@ "2407d5d61e7f7206": "富文本输入框", "64b8fd2c284c3137": "发送快捷键", "6163f91bddf474ae": "追加消息行为", + "425021487583cf8a": "子智能体和侧聊的打开位置", "856812e7e1fc445e": "聊天中的工具调用", "216ed20b6f40fa6f": "屏幕阅读器播报", "0ce04933a7047deb": "屏幕阅读器窗口标题", @@ -9904,6 +9909,12 @@ "1ea00f7b1a88ee2e": "重置后续消息行为为默认值", "845e7f34c156ffd4": "加入队列", "81a74689d0319316": "引导当前执行", + "6dc57547546cbe96": "子智能体和侧聊", + "ffbc33f6b6ddc689": "单击时子智能体、侧聊或关联环境中的会话在哪里打开。按住 {modifier} 单击或中键单击会改为在主视图中打开。", + "7b7062c4b277e235": "单击时子智能体、侧聊或关联环境中的会话在哪里打开。按住 {modifier} 单击或中键单击会改为在侧边面板中打开。", + "1eba4b1f5ae00974": "将子智能体和侧聊的打开位置重置为默认值", + "f8062ccf65d4bb2a": "侧边面板", + "a8072bdf7ae4a288": "主视图", "162108e16ed96771": "屏幕阅读器", "18807e775248380c": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", "5848a9c1d77f45b2": "重置聊天中的工具调用为默认值", @@ -9987,6 +9998,8 @@ "b9ebecdb8db71466": "系统默认使用浏览器或操作系统的时钟偏好。", "62f8a7774dc1ffb7": "加入队列", "c711b55bc1500f08": "引导当前执行", + "e79128045796685d": "侧边面板", + "d81dc62319ba223e": "主视图", "54139af0114a2729": "红色与绿色(默认)", "8d4a851d370639e4": "蓝色与橙色", "b1d7c1ea891b7db5": "展开", @@ -11625,6 +11638,7 @@ "ade91c8927c48175": "输入框 富文本 tiptap 粗体 斜体 markdown 样式 所见即所得", "34d74827c2a8b009": "enter 回车 command ctrl 多行 提示词 换行 输入框", "9d1013084c46ecce": "排队 引导 运行中 轮次 发送 默认行为 输入框", + "e5e7f5e1fb1f2e4c": "子智能体 侧聊 关联会话 单击 右侧面板 侧边面板 主视图 command ctrl 中键单击", "5b8b854de7ee6f4d": "已安装 cli 版本 更新 可用 codex claude cursor grok fx kiro opencode", "64f12530d55d2ad1": "恢复 运行中 活跃 中断 工作 重启 重新启动 机器 崩溃 桌面 更新 自动", "214a98497c4ed05d": "caffeinate 睡眠 阻止 保持唤醒 电源 笔记本 盖子 抑制", diff --git a/apps/web/src/lib/assistantCitationNavigation.test.ts b/apps/web/src/lib/assistantCitationNavigation.test.ts index 0f1816c2db85a..bcbc5c338df2d 100644 --- a/apps/web/src/lib/assistantCitationNavigation.test.ts +++ b/apps/web/src/lib/assistantCitationNavigation.test.ts @@ -175,5 +175,5 @@ function expectSideChatRevealedOnParent(router: ReturnType { expect(route).toEqual(mainRef); expect( selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, mainRef)?.id, - ).toBe("side-chat:side-chat"); + ).toBe("thread:side-chat"); expect( resolveThreadOpenRoute(mainRef, { lineage: { sideChat: false, parentThreadId: null } as never, }), ).toBe(mainRef); }); + +it("opens a side thread beside the thread the click was in, or in its place", () => { + useRightPanelStore.setState(useRightPanelStore.getInitialState()); + const navigated: unknown[] = []; + const open = ( + input: Pick[0], "threadRef" | "panelRef" | "intent">, + ) => openSideThread({ ...input, navigate: (ref) => void navigated.push(ref) }); + const surfaces = () => + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, mainRef).surfaces; + + expect(open({ threadRef: sideChatRef, panelRef: mainRef, intent: "primary" })).toBe("panel"); + expect(surfaces().map((surface) => surface.id)).toEqual(["thread:side-chat"]); + expect(navigated).toEqual([]); + + expect(open({ threadRef: sideChatRef, panelRef: mainRef, intent: "alternate" })).toBe("main"); + expect(navigated).toEqual([sideChatRef]); + + // No panel shows a thread beside itself, of another environment, or where there is none. + const elsewhere = scopeThreadRef(EnvironmentId.make("environment:other"), sideChatRef.threadId); + expect(open({ threadRef: mainRef, panelRef: mainRef, intent: "panel" })).toBe("main"); + expect(open({ threadRef: elsewhere, panelRef: mainRef, intent: "panel" })).toBe("main"); + expect(open({ threadRef: sideChatRef, panelRef: null, intent: "panel" })).toBe("main"); + expect(navigated).toEqual([sideChatRef, mainRef, elsewhere, sideChatRef]); + expect(surfaces()).toHaveLength(1); +}); diff --git a/apps/web/src/lib/sideChatPane.ts b/apps/web/src/lib/sideChatPane.ts index e18b5f5ad129c..990f89e815c7e 100644 --- a/apps/web/src/lib/sideChatPane.ts +++ b/apps/web/src/lib/sideChatPane.ts @@ -1,8 +1,21 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import type { OrchestrationV2ThreadShell, ScopedThreadRef } from "@t3tools/contracts"; +import { + resolveSideThreadOpenTarget, + type SideThreadOpenIntent, +} from "@t3tools/client-runtime/side-thread"; +import type { + OrchestrationV2ThreadShell, + ScopedThreadRef, + SideThreadOpenTarget, +} from "@t3tools/contracts"; import type { ToolCallDiffTarget } from "../diffPanelStore"; -import { useRightPanelStore } from "../rightPanelStore"; +import type { LinkedThreadTarget } from "@t3tools/client-runtime/linked-thread"; +import type { useNavigate } from "@tanstack/react-router"; + +import { getClientSettings } from "../hooks/useSettings"; +import { linkedThreadRouteParams } from "../linkedThreadSurface"; +import { rightPanelHostRef, useRightPanelStore } from "../rightPanelStore"; /** Whether an event started in the side chat pane (`data-side-chat-pane`), which the main chat ignores. */ export function isInSideChatPane(target: EventTarget | null): boolean { @@ -10,11 +23,13 @@ export function isInSideChatPane(target: EventTarget | null): boolean { } /** - * Opens an embedded side chat's tool diffs in its parent's diff panel and runs its shell commands + * Opens an embedded side thread's tool diffs in its parent's diff panel and runs its shell commands * in the parent's terminal drawer, since the embedded view hides its own. Other panel actions reach * the parent through `hostRightPanel`; diff selection and the drawer are not panel state. */ export interface SideChatParentPanel { + /** The thread whose panel shows the embedded one. */ + readonly hostRef: ScopedThreadRef; readonly openToolDiff: (target: ToolCallDiffTarget) => void; readonly runShellCommand: (command: string) => void; } @@ -30,6 +45,69 @@ export function resolveThreadOpenRoute( const parentThreadId = thread?.lineage.sideChat === true ? thread.lineage.parentThreadId : null; if (parentThreadId === null) return threadRef; const parentRef = scopeThreadRef(threadRef.environmentId, parentThreadId); - useRightPanelStore.getState().openSideChat(parentRef, threadRef.threadId); + useRightPanelStore.getState().openThread(parentRef, threadRef.threadId); return parentRef; } + +/** + * Whether `panelRef`'s right panel can show `threadRef` as a tab: a thread of the same environment + * that is not the one the panel belongs to. + */ +function canOpenThreadInPanel( + threadRef: ScopedThreadRef, + panelRef: ScopedThreadRef | null, +): panelRef is ScopedThreadRef { + if (panelRef === null) return false; + const host = rightPanelHostRef(panelRef); + return host.environmentId === threadRef.environmentId && host.threadId !== threadRef.threadId; +} + +/** + * Opens a side chat or subagent where the click asked: as a tab beside `panelRef`, the thread the + * click happened in, or on the main screen through `navigate`. Returns where it went. + */ +export function openSideThread(input: { + readonly threadRef: ScopedThreadRef; + readonly panelRef: ScopedThreadRef | null; + readonly intent: SideThreadOpenIntent; + readonly navigate: (threadRef: ScopedThreadRef) => void; +}): SideThreadOpenTarget { + const { threadRef, panelRef } = input; + const target = resolveSideThreadOpenTarget({ + preference: getClientSettings().sideThreadOpenTarget, + intent: input.intent, + panelAvailable: canOpenThreadInPanel(threadRef, panelRef), + }); + if (target === "panel" && panelRef !== null) { + useRightPanelStore.getState().openThread(panelRef, threadRef.threadId); + } else { + input.navigate(threadRef); + } + return target; +} + +/** + * Opens the read-only view of a linked environment's thread where the click asked: as a tab in + * `panelRef`'s right panel, or on the main screen, which is also where it goes without a panel. + */ +export function openLinkedThreadRead(input: { + readonly panelRef: ScopedThreadRef | null; + readonly target: LinkedThreadTarget; + readonly intent: SideThreadOpenIntent; + readonly navigate: ReturnType; +}) { + const { panelRef, target } = input; + const place = resolveSideThreadOpenTarget({ + preference: getClientSettings().sideThreadOpenTarget, + intent: input.intent, + panelAvailable: panelRef !== null, + }); + if (place === "panel" && panelRef !== null) { + useRightPanelStore.getState().openLinkedThread(panelRef, target); + return; + } + void input.navigate({ + to: "/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId", + params: linkedThreadRouteParams(target), + }); +} diff --git a/apps/web/src/linkedThreadSurface.ts b/apps/web/src/linkedThreadSurface.ts index 344efffe8d472..cc1202c97d2e2 100644 --- a/apps/web/src/linkedThreadSurface.ts +++ b/apps/web/src/linkedThreadSurface.ts @@ -53,3 +53,14 @@ export function linkedThreadTitle( ): string { return surface.title?.trim() || fallback; } + +/** The main-screen route of a linked environment's thread, read through `viaEnvironmentId`. */ +export function linkedThreadRouteParams( + target: Pick, +) { + return { + viaEnvironmentId: target.viaEnvironmentId, + linkedEnvironmentId: target.environmentId, + linkedThreadId: target.threadId, + }; +} diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index f226b5f1efd1e..cff3810a7b348 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -161,8 +161,8 @@ export async function reopenClosedView( case "issue": panels.openIssue(ref, surface); break; - case "side-chat": - panels.openSideChat(ref, surface.threadId); + case "thread": + panels.openThread(ref, surface.threadId); break; case "linked-thread": panels.openLinkedThread(ref, surface); diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index 39ac8336ce38c..32dd581430cb2 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -595,6 +595,44 @@ describe("rightPanelStore", () => { }); }); + it("opens a side chat or subagent once per thread, and never the panel's own thread", () => { + const store = useRightPanelStore.getState(); + const child = ThreadId.make("child"); + store.openThread(refA, child); + store.open(refA, "diff"); + store.openThread(refA, child); + store.openThread(refA, refA.threadId); + const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); + expect(panel.surfaces.map((surface) => surface.id)).toEqual(["thread:child", "diff"]); + expect(panel.activeSurfaceId).toBe("thread:child"); + }); + + it("keeps side chat tabs saved before they became thread surfaces", () => { + const migrated = migratePersistedRightPanelState({ + byThreadKey: { + "env-1:thread-A": { + isOpen: true, + activeSurfaceId: "side-chat:side", + surfaces: [ + { id: "diff", kind: "diff" }, + { id: "side-chat:side", kind: "side-chat", threadId: "side" }, + { id: "side-chat:gone", kind: "side-chat" }, + { id: "thread:stale", kind: "thread", threadId: "sub" }, + ], + }, + }, + }); + expect(selectThreadRightPanelState(migrated.byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "thread:side", + surfaces: [ + { id: "diff", kind: "diff" }, + { id: "thread:side", kind: "thread", threadId: "side" }, + { id: "thread:sub", kind: "thread", threadId: "sub" }, + ], + }); + }); + it("drops the legacy singleton terminal surface during migration", () => { expect( migratePersistedRightPanelState({ diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 6b932ed4a46cf..19d08158e23e9 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -30,7 +30,7 @@ const RIGHT_PANEL_KINDS = [ "pull-request", "pull-requests", "issue", - "side-chat", + "thread", "linked-thread", ] as const; export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number]; @@ -103,12 +103,34 @@ export type RightPanelSurface = key: string; url?: string; } - | { id: `side-chat:${string}`; kind: "side-chat"; threadId: ThreadId } + /** + * A thread of the panel's environment shown beside it: a side chat or a subagent. Which one is + * the thread's own lineage, so the surface only names it. + */ + | ThreadSurface /** A linked environment's thread, read through `viaEnvironmentId`; it has no thread here. */ | LinkedThreadSurface; +export type ThreadSurface = { id: `thread:${string}`; kind: "thread"; threadId: ThreadId }; + +const threadSurface = (threadId: ThreadId): ThreadSurface => ({ + id: `thread:${threadId}`, + kind: "thread", + threadId, +}); + +/** + * A saved thread surface with its id rebuilt, or null when it names no thread. Builds before + * subagents opened here saved it as `side-chat`. + */ +export function decodeThreadSurface(surface: object): ThreadSurface | null { + const { kind, threadId } = surface as Record; + if ((kind !== "thread" && kind !== "side-chat") || typeof threadId !== "string") return null; + return threadId === "" ? null : threadSurface(ThreadId.make(threadId)); +} + const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2"; -const RIGHT_PANEL_STORAGE_VERSION = 15; +const RIGHT_PANEL_STORAGE_VERSION = 16; export const PULL_REQUESTS_PANEL_REF = scopeThreadRef( EnvironmentId.make("pull-requests-panel"), @@ -165,10 +187,11 @@ interface RightPanelStoreState { ref: ScopedThreadRef, kind: Exclude< RightPanelKind, - "file" | "terminal" | "pull-request" | "issue" | "side-chat" | "linked-thread" + "file" | "terminal" | "pull-request" | "issue" | "thread" | "linked-thread" >, ) => void; - openSideChat: (ref: ScopedThreadRef, threadId: ThreadId) => void; + /** Opens a side chat or subagent of `ref`'s environment as a tab; `ref` itself has no tab. */ + openThread: (ref: ScopedThreadRef, threadId: ThreadId) => void; openLinkedThread: (ref: ScopedThreadRef, target: LinkedThreadTarget) => void; /** Records the title the linked environment gave, so the tab and a reopened one show it. */ setLinkedThreadTitle: (ref: ScopedThreadRef, surfaceId: string, title: string) => void; @@ -238,7 +261,7 @@ interface RightPanelStoreState { ref: ScopedThreadRef, kind: Exclude< RightPanelKind, - "file" | "terminal" | "pull-request" | "issue" | "side-chat" | "linked-thread" + "file" | "terminal" | "pull-request" | "issue" | "thread" | "linked-thread" >, ) => void; setThreadPanelOpen: ( @@ -264,7 +287,7 @@ const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { const singletonSurface = ( kind: Exclude< RightPanelKind, - "file" | "preview" | "terminal" | "pull-request" | "issue" | "side-chat" | "linked-thread" + "file" | "preview" | "terminal" | "pull-request" | "issue" | "thread" | "linked-thread" >, ): RightPanelSurface => { switch (kind) { @@ -587,6 +610,10 @@ export function migratePersistedRightPanelState(persistedState: unknown): { ? validThreadState.surfaces.flatMap((surface) => { if (!surface || typeof surface !== "object") return []; const kind = (surface as { kind?: string }).kind; + if (kind === "thread" || kind === "side-chat") { + const decoded = decodeThreadSurface(surface); + return decoded === null ? [] : [decoded]; + } // Also drops kinds this build does not know, such as one a newer build saved. if (!(RIGHT_PANEL_KINDS as ReadonlyArray).includes(kind)) return []; if (surface.kind === "linked-thread") { @@ -684,7 +711,12 @@ export function migratePersistedRightPanelState(persistedState: unknown): { ]; }) : []; - const rawActiveSurfaceId = validThreadState?.activeSurfaceId; + const savedActiveSurfaceId = validThreadState?.activeSurfaceId; + const rawActiveSurfaceId = + typeof savedActiveSurfaceId === "string" && + savedActiveSurfaceId.startsWith("side-chat:") + ? `thread:${savedActiveSurfaceId.slice("side-chat:".length)}` + : savedActiveSurfaceId; const persistedActiveSurfaceId = surfaces.some( (surface) => surface.id === rawActiveSurfaceId, ) @@ -840,11 +872,13 @@ export const useRightPanelStore = create()( ); }), ), - openSideChat: (ref, threadId) => + openThread: (ref, threadId) => set((state) => - userAction(state, scopedThreadKey(ref), (current) => - upsertSurface(current, { id: `side-chat:${threadId}`, kind: "side-chat", threadId }), - ), + rightPanelHostRef(ref).threadId === threadId + ? state + : userAction(state, scopedThreadKey(ref), (current) => + upsertSurface(current, threadSurface(threadId)), + ), ), openLinkedThread: (ref, target) => set((state) => diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 0392f92459406..2d2e74ab58ef2 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -53,6 +53,7 @@ import { Route as ChatSettingsAccessRouteImport } from './routes/_chat.settings. import { Route as ChatSettingsAboutRouteImport } from './routes/_chat.settings.about' import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId' import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId' +import { Route as ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRouteImport } from './routes/_chat.linked.$viaEnvironmentId.$linkedEnvironmentId.$linkedThreadId' const WelcomeRoute = WelcomeRouteImport.update({ id: '/welcome', @@ -279,6 +280,14 @@ const ChatEnvironmentIdThreadIdRoute = path: '/$environmentId/$threadId', getParentRoute: () => ChatRoute, } as any) +const ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute = + ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRouteImport.update( + { + id: '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId', + path: '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId', + getParentRoute: () => ChatRoute, + } as any, + ) export interface FileRoutesByFullPath { '/': typeof ChatIndexRoute @@ -324,6 +333,7 @@ export interface FileRoutesByFullPath { '/settings/voice': typeof ChatSettingsVoiceRoute '/settings/worktrees': typeof ChatSettingsWorktreesRoute '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute + '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId': typeof ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute } export interface FileRoutesByTo { '/approve-agent': typeof ApproveAgentRoute @@ -369,6 +379,7 @@ export interface FileRoutesByTo { '/settings/voice': typeof ChatSettingsVoiceRoute '/settings/worktrees': typeof ChatSettingsWorktreesRoute '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute + '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId': typeof ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -416,6 +427,7 @@ export interface FileRoutesById { '/_chat/settings/voice': typeof ChatSettingsVoiceRoute '/_chat/settings/worktrees': typeof ChatSettingsWorktreesRoute '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute + '/_chat/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId': typeof ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -463,6 +475,7 @@ export interface FileRouteTypes { | '/settings/voice' | '/settings/worktrees' | '/threads/$environmentId/$threadId' + | '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId' fileRoutesByTo: FileRoutesByTo to: | '/approve-agent' @@ -508,6 +521,7 @@ export interface FileRouteTypes { | '/settings/voice' | '/settings/worktrees' | '/threads/$environmentId/$threadId' + | '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId' id: | '__root__' | '/_chat' @@ -554,6 +568,7 @@ export interface FileRouteTypes { | '/_chat/settings/voice' | '/_chat/settings/worktrees' | '/threads/$environmentId/$threadId' + | '/_chat/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -878,6 +893,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatEnvironmentIdThreadIdRouteImport parentRoute: typeof ChatRoute } + '/_chat/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId': { + id: '/_chat/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId' + path: '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId' + fullPath: '/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId' + preLoaderRoute: typeof ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRouteImport + parentRoute: typeof ChatRoute + } } } @@ -954,6 +976,7 @@ interface ChatRouteChildren { ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute + ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute: typeof ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute } const ChatRouteChildren: ChatRouteChildren = { @@ -965,6 +988,8 @@ const ChatRouteChildren: ChatRouteChildren = { ChatIndexRoute: ChatIndexRoute, ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute, ChatDraftDraftIdRoute: ChatDraftDraftIdRoute, + ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute: + ChatLinkedViaEnvironmentIdLinkedEnvironmentIdLinkedThreadIdRoute, } const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren) diff --git a/apps/web/src/routes/_chat.linked.$viaEnvironmentId.$linkedEnvironmentId.$linkedThreadId.tsx b/apps/web/src/routes/_chat.linked.$viaEnvironmentId.$linkedEnvironmentId.$linkedThreadId.tsx new file mode 100644 index 0000000000000..85926925cd3d4 --- /dev/null +++ b/apps/web/src/routes/_chat.linked.$viaEnvironmentId.$linkedEnvironmentId.$linkedThreadId.tsx @@ -0,0 +1,21 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { createFileRoute } from "@tanstack/react-router"; + +import { LinkedThreadPage } from "../components/chat/LinkedThreadPage"; + +// A thread on a linked environment this client is not connected to, read through `viaEnvironmentId`. +// Its params are not named `environmentId` and `threadId`: those mean a thread this client can open. +export const Route = createFileRoute( + "/_chat/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId", +)({ + component: function LinkedThreadRoute() { + const params = Route.useParams(); + return ( + + ); + }, +}); diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index 7dfc41a9f617f..adeb858c23cab 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -1,17 +1,19 @@ import { useAtom, useAtomSet, useAtomValue } from "@effect/atom-react"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; import { connectLinkedEnvironment, type LinkedThreadOpen, resolveLinkedThreadOpen, } from "@t3tools/client-runtime/linked-thread"; import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; -import { useNavigate } from "@tanstack/react-router"; +import { useNavigate, useRouter } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; import { useRightPanelStore } from "../rightPanelStore"; import { connectPairing, reachesEnvironment } from "../connection/onboarding"; +import { openLinkedThreadRead } from "../lib/sideChatPane"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; import { buildThreadRouteParams } from "../threadRoutes"; import { useEnvironment } from "./environments"; @@ -20,10 +22,9 @@ import { useEnvironmentQuery } from "./query"; import { useAtomCommand } from "./use-atom-command"; /** - * How a click opens a thread that the thread `panelRef` says is on a linked environment: in place - * when this client is connected there itself, else as a read-only tab in that thread's right - * panel, read through its environment. Once the link is gone a saved environment opens in place, - * where the client can reconnect to it; with neither, the tab says what to link again. + * How a click opens a thread `panelRef` says is on a linked environment: in place when this client + * is connected there, else read-only through `panelRef`'s environment, in its right panel or on + * the main screen as the click asks. A saved environment whose link is gone opens in place. */ export function useLinkedThreadOpener( panelRef: ScopedThreadRef, @@ -35,7 +36,10 @@ export function useLinkedThreadOpener( } | undefined, title: string | null, -): { readonly mode: Exclude; readonly open: () => void } | null { +): { + readonly mode: Exclude; + readonly open: (intent: SideThreadOpenIntent) => void; +} | null { const navigate = useNavigate(); const viaEnvironmentId = panelRef.environmentId; const own = useEnvironment(thread?.environmentId ?? null); @@ -51,14 +55,19 @@ export function useLinkedThreadOpener( const mode = resolved === "direct" ? "direct" : "linked"; return { mode, - open: () => { + open: (intent) => { if (mode === "linked") { - useRightPanelStore.getState().openLinkedThread(panelRef, { - viaEnvironmentId, - environmentId: thread.environmentId, - threadId: thread.threadId, - label: own?.label ?? thread.label, - title, + openLinkedThreadRead({ + panelRef, + target: { + viaEnvironmentId, + environmentId: thread.environmentId, + threadId: thread.threadId, + label: own?.label ?? thread.label, + title, + }, + intent, + navigate, }); return; } @@ -71,8 +80,9 @@ export function useLinkedThreadOpener( } type TabKey = readonly [ - panelEnvironmentId: EnvironmentId, - panelThreadId: ThreadId, + /** Null on the main screen, where no tab shows the title. */ + panelEnvironmentId: EnvironmentId | null, + panelThreadId: ThreadId | null, surfaceId: string, viaEnvironmentId: EnvironmentId, environmentId: EnvironmentId, @@ -90,30 +100,36 @@ const targetOf = ( const tabViewAtom = Atom.family((key: string) => { const [panelEnvironmentId, panelThreadId, surfaceId, viaEnvironmentId, environmentId, threadId] = JSON.parse(key) as TabKey; - const panelRef = scopeThreadRef(panelEnvironmentId, panelThreadId); + const panelRef = + panelEnvironmentId === null || panelThreadId === null + ? null + : scopeThreadRef(panelEnvironmentId, panelThreadId); const view = peerLinkEnvironment.threadView( targetOf({ viaEnvironmentId, environmentId, threadId }), ); return Atom.make((get) => { const live = get(view); const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; - if (title) useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + if (title && panelRef !== null) { + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + } return live; }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); }); /** - * The thread of `surface`, streamed through the environment that links to it for the tab in - * `panelRef`'s panel. The stream runs only while `visible`; what it last showed stays. + * The thread of `surface`, streamed through the environment that links to it, for the tab in + * `panelRef`'s panel or, with null, the main screen. The stream runs only while `visible`; what + * it last showed stays. */ export function useLinkedThreadView( - panelRef: ScopedThreadRef, + panelRef: ScopedThreadRef | null, surface: Pick, visible: boolean, ) { const key: TabKey = [ - panelRef.environmentId, - panelRef.threadId, + panelRef?.environmentId ?? null, + panelRef?.threadId ?? null, surface.id, surface.viaEnvironmentId, surface.environmentId, @@ -157,14 +173,16 @@ const linkedEnvironmentConnectAtom = Atom.family((key: string) => /** * Connects this client to the environment `surface`'s thread lives in. One step when the linking - * environment can get a pairing for this client: the thread then opens there and the tab closes. - * Otherwise the add-environment dialog opens for that machine. + * environment can get a pairing for this client: the thread then opens there, in place of the + * read-only view. Otherwise the add-environment dialog opens for that machine. `panelRef` is the + * thread whose panel shows the read, or null on the main screen. */ export function useConnectLinkedEnvironment( - panelRef: ScopedThreadRef, + panelRef: ScopedThreadRef | null, surface: LinkedThreadSurface, ) { const navigate = useNavigate(); + const router = useRouter(); const setPrefill = useAtomSet(addEnvironmentPrefillAtom); const mayPair = useAtomValue( peerLinkEnvironment.pairClient.permissionAtom(surface.viaEnvironmentId), @@ -174,7 +192,9 @@ export function useConnectLinkedEnvironment( const reaches = useAtomCommand(reachesEnvironment, quiet); const pair = useAtomCommand(connectPairing, quiet); const [state, setState] = useAtom( - linkedEnvironmentConnectAtom(`${scopedThreadKey(panelRef)}:${surface.id}`), + linkedEnvironmentConnectAtom( + `${panelRef === null ? "main" : scopedThreadKey(panelRef)}:${surface.id}`, + ), ); const addWithCode = (prefill: AddEnvironmentPrefill) => { setPrefill(prefill); @@ -182,6 +202,9 @@ export function useConnectLinkedEnvironment( }; const connect = async () => { setState({ phase: "connecting" }); + const startedOn = router.state.location.href; + // Pairing takes a moment; a user who has gone elsewhere since is not moved again. + const stayed = () => router.state.location.href === startedOn; const outcome = await connectLinkedEnvironment({ label: surface.label, requestPairing: async () => { @@ -213,10 +236,13 @@ export function useConnectLinkedEnvironment( if (outcome.type === "connected") { setState({ phase: "idle" }); // The thread opens where every thread on a connected environment does, so its tab is done. - useRightPanelStore.getState().closeSurface(panelRef, surface.id); + if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id); + if (!stayed()) return outcome; void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(scopeThreadRef(surface.environmentId, surface.threadId)), + // The read-only page has nothing left to go back to. + replace: panelRef === null, }); return outcome; } @@ -226,7 +252,7 @@ export function useConnectLinkedEnvironment( host: outcome.host, }; setState({ phase: "manual", prefill }); - addWithCode(prefill); + if (stayed()) addWithCode(prefill); return outcome; }; return { state, connect, addWithCode }; diff --git a/apps/web/src/threadRoutes.test.ts b/apps/web/src/threadRoutes.test.ts index 9b321b5d43cbc..c4fef5897c5f4 100644 --- a/apps/web/src/threadRoutes.test.ts +++ b/apps/web/src/threadRoutes.test.ts @@ -10,6 +10,7 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/th import { ThreadId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; +import { linkedThreadRouteParams } from "./linkedThreadSurface"; import { makeThreadProjectionFixture } from "./test-fixtures"; import { @@ -70,6 +71,17 @@ describe("threadRoutes", () => { expect(isThreadRoutePathname(router.state.location.pathname, ref)).toBe(false); }); + it("does not take a linked environment's thread route for a thread this client can open", () => { + // The layout reads every match's params untyped, as here. + const params: Record = linkedThreadRouteParams({ + viaEnvironmentId: "env-1" as never, + environmentId: "env-2" as never, + threadId: ThreadId.make("thread-there"), + }); + + expect(resolveThreadRouteTarget(params)).toBeNull(); + }); + it("resolves the backing thread while a draft route is being promoted", () => { const target = resolveThreadRouteTarget({ draftId: "draft-1" }); diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsx index 8a784eea73d11..b27b3ae8994f1 100644 --- a/apps/web/test/appScenarios.renders.tsx +++ b/apps/web/test/appScenarios.renders.tsx @@ -443,7 +443,7 @@ it("app-switch-settings-section", async () => { // Keep git scenarios last: the status they leave cached adds renders to later scenarios. it("app-git-file-counts-with-side-chat", async () => { using _clock = frozenClock(); - useRightPanelStore.getState().openSideChat(scopeThreadRef(ENVIRONMENT_ID, WARM), SIDE_CHAT.id); + useRightPanelStore.getState().openThread(scopeThreadRef(ENVIRONMENT_ID, WARM), SIDE_CHAT.id); await using _app = (await openThread(WARM)).screen; await expect.element(lastAnswer(SIDE_CHAT.id)).toBeVisible(); const gitStatus = vcsEnvironment.status({ @@ -485,7 +485,7 @@ it("app-git-file-counts-with-side-chat", async () => { // ChatView re-renders when the tree goes dirty or clean; the composer and side chat timeline should not. it("app-git-status-updates-with-side-chat", async () => { using _clock = frozenClock(); - useRightPanelStore.getState().openSideChat(scopeThreadRef(ENVIRONMENT_ID, WARM), SIDE_CHAT.id); + useRightPanelStore.getState().openThread(scopeThreadRef(ENVIRONMENT_ID, WARM), SIDE_CHAT.id); await using _app = (await openThread(WARM)).screen; await expect.element(lastAnswer(SIDE_CHAT.id)).toBeVisible(); const local = (insertions: number) => ({ diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 7fd89bf48a9f5..71e8875bb56db 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -227,6 +227,8 @@ function run( export interface FakeThread { /** Makes this a side chat of that thread. */ readonly sideChatOf?: ThreadId; + /** Makes this a subagent the provider started under that thread, which takes no messages. */ + readonly providerSubagentOf?: ThreadId; /** Makes this an older settled thread the shell leaves out; only its family read returns it. */ readonly olderSettled?: true; readonly id: ThreadId; @@ -309,6 +311,8 @@ export function threadWithQuestion(name: string, question: string): FakeThread { }; } +const parentOf = (thread: FakeThread) => thread.sideChatOf ?? thread.providerSubagentOf; + function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { const latest = thread.runs.at(-1); const modelSelection = thread.modelSelection ?? MODEL; @@ -325,14 +329,14 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null, ...(thread.issues === undefined ? {} : { issues: thread.issues }), lineage: { - rootThreadId: thread.sideChatOf ?? thread.id, - parentThreadId: thread.sideChatOf ?? null, - relationshipToParent: null, + rootThreadId: parentOf(thread) ?? thread.id, + parentThreadId: parentOf(thread) ?? null, + relationshipToParent: thread.providerSubagentOf ? "subagent" : null, ...(thread.sideChatOf ? { sideChat: true } : {}), }, forkedFrom: null, - createdBy: "user", - creationSource: "web", + createdBy: thread.providerSubagentOf ? "agent" : "user", + creationSource: thread.providerSubagentOf ? "provider" : "web", latestRunId: latest?.id ?? null, activeRunId: null, // Idle reads as waiting on the user, which shows a per-second duration in the sidebar. @@ -378,8 +382,8 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { activeProviderThreadId: shell.activeProviderThreadId, lineage: shell.lineage, forkedFrom: null, - createdBy: "user", - creationSource: "web", + createdBy: shell.createdBy, + creationSource: shell.creationSource, createdAt: AT, updatedAt: AT, archivedAt: null, @@ -525,7 +529,7 @@ const handlers: Record unknown> = { ); }, [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input: { readonly threadId: ThreadId }) => { - const rootOf = (thread: FakeThread) => thread.sideChatOf ?? thread.id; + const rootOf = (thread: FakeThread) => parentOf(thread) ?? thread.id; const requested = threads.find((candidate) => candidate.id === input.threadId); return Effect.succeed({ snapshotSequence: sequence, diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index a3efb1de076d1..61492760f2a4b 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -483,8 +483,12 @@ You can read a thread on a linked machine without connecting this app to it. Ope a task that was delegated there from the thread's agents, or a thread link that points there, and the thread opens read-only, streamed through the machine you are connected to over its link. It follows the thread live. On web and desktop -it opens as a tab in the right panel, beside the thread you are in, and shows -the same timeline as any other thread. +it opens as a tab in the right panel, beside the thread you are in, or in the +main view with ⌘/Ctrl-click, like +[subagents and side chats](thread-sidebar.md#open-a-thread-beside-the-one-you-are-in). +On mobile it opens in the inspector on layouts that have one, where Maximize +fills the screen, and as its own screen elsewhere. It shows the same timeline as +any other thread on web and desktop, and a shorter read-only list on mobile. - The view is marked **Read-only** with both machines' names. To reply, approve or stop the thread, choose **Connect to interact**. When the link has full diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 4854144f3658b..5950e152bd570 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -269,7 +269,10 @@ the snooze. Enable **Snooze until limits reset** in thread behavior settings to snooze limit stops by default. Providers without a reset time offer manual retry and the normal snooze choices. -On web and desktop, use **Agents** to follow work delegated to subagents. +On web and desktop, use **Agents** to follow work delegated to subagents. Click +a subagent there or on its conversation card to open it in the right panel, +beside the thread you are in. See +[Open a thread beside the one you are in](#open-a-thread-beside-the-one-you-are-in). On mobile, open a subagent from its conversation card or **Agents**. On iOS layouts with an inspector, its thread opens beside the parent. Maximize it to fill the screen; close the full-screen view to return to the parent and inspector. @@ -297,6 +300,31 @@ To choose what the thread details card shows, right-click the card or open shortcuts, such as Open in editor and project scripts. **Reset to default** brings back the standard rows. +## Open a thread beside the one you are in + +On web and desktop, a subagent, a side chat, and a +[thread on a linked machine](remote-access.md#read-a-linked-machines-threads) +all open the same way. Click one to open it as a tab in the right panel, so the +thread you are in stays in view. Hold ⌘ (Ctrl on Windows and Linux) while you +click, or middle-click, to open it in the main view instead. With the keyboard, +Enter and ⌘/Ctrl + Enter do the same. Right-click for **Open in side panel** and +**Open in main view**. + +To make the main view the place a plain click opens them, set **Settings → Chat → +Open subagents and side chats in** to **Main view**. The modifier then opens +the side panel. + +From a tab, **Open in main view** at the top of the tab, or in the tab's +right-click menu, moves it to the main view. The bottom of the view depends on +the thread: a side chat or a subagent you delegated has a composer, a subagent +the agent started is read-only, and a thread on a linked machine is read-only +with **Connect to interact**. + +Other thread links open in the main view as before. + +On mobile these threads open in the inspector on layouts that have one, where +Maximize fills the screen, and full screen everywhere else. + ## Side chats A side chat lets you ask a question about a thread without adding to it. It starts @@ -305,7 +333,8 @@ with what the thread knows, and the thread keeps working while you ask. On web and desktop, start a message with `/side` or `/btw`, then your question. You can also choose **Side chat** from the **+** menu in the right panel. The side chat opens as a tab there, with its own composer. Side chats do not show in the -sidebar. Find one again under **Side chats** in thread details. +sidebar. Find one again under **Side chats** in thread details, where it opens +[like a subagent does](#open-a-thread-beside-the-one-you-are-in). A side chat works in the same folder as the thread and starts with the permissions, model, and reasoning level shown in the thread's composer, including for its first diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 0663ee293e2e8..361bbb32ff62a 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -115,6 +115,10 @@ "types": "./src/linkedThread.ts", "default": "./src/linkedThread.ts" }, + "./side-thread": { + "types": "./src/sideThread.ts", + "default": "./src/sideThread.ts" + }, "./scheduled-task-webhook": { "types": "./src/scheduledTaskWebhook.ts", "default": "./src/scheduledTaskWebhook.ts" diff --git a/packages/client-runtime/src/sideThread.test.ts b/packages/client-runtime/src/sideThread.test.ts new file mode 100644 index 0000000000000..70770aaace22d --- /dev/null +++ b/packages/client-runtime/src/sideThread.test.ts @@ -0,0 +1,108 @@ +import { ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + resolveMobileSideThreadPresentation, + resolveSideThreadOpenTarget, + sideThreadComposer, + sideThreadKindOf, + sideThreadOpenIntentOf, +} from "./sideThread.ts"; + +const parentThreadId = ThreadId.make("parent"); +const lineage = ( + overrides: Partial<{ + parentThreadId: ThreadId | null; + relationshipToParent: "fork" | "subagent" | null; + sideChat: boolean; + }>, +) => ({ + lineage: { + rootThreadId: parentThreadId, + parentThreadId, + relationshipToParent: null, + forkedFrom: null, + ...overrides, + }, +}); + +describe("sideThreadKindOf", () => { + it.each([ + ["a side chat", lineage({ relationshipToParent: "fork", sideChat: true }), "side-chat"], + ["an app subagent", { ...lineage({ relationshipToParent: "subagent" }) }, "subagent"], + [ + "a provider's own subagent", + { ...lineage({ relationshipToParent: "subagent" }), creationSource: "provider" as const }, + "provider-subagent", + ], + ["a fork", lineage({ relationshipToParent: "fork" }), null], + ["a top-level thread", lineage({ parentThreadId: null }), null], + // The flag alone does not make a tab: a side chat is beside some thread. + ["a side chat with no parent", lineage({ parentThreadId: null, sideChat: true }), null], + ])("classifies %s", (_name, thread, kind) => { + expect(sideThreadKindOf(thread as Parameters[0])).toBe(kind); + }); + + it("treats a thread that is not loaded as an ordinary one", () => { + expect(sideThreadKindOf(null)).toBeNull(); + }); +}); + +describe("sideThreadComposer", () => { + it.each([ + ["side-chat", "composer"], + ["subagent", "composer"], + ["provider-subagent", "read-only"], + ["linked", "read-only-connect"], + ] as const)("gives %s the %s", (kind, composer) => { + expect(sideThreadComposer(kind)).toBe(composer); + }); +}); + +describe("resolveSideThreadOpenTarget", () => { + it.each([ + // preference, intent, panelAvailable, target + ["panel", "primary", true, "panel"], + ["panel", "alternate", true, "main"], + ["main", "primary", true, "main"], + ["main", "alternate", true, "panel"], + // The context menu names a place, whatever the preference. + ["panel", "main", true, "main"], + ["main", "panel", true, "panel"], + // With no panel to open in, every way of asking lands on the main view. + ["panel", "primary", false, "main"], + ["main", "alternate", false, "main"], + ["main", "panel", false, "main"], + ] as const)( + "prefers %s, asked %s, panel %s: opens in %s", + (preference, intent, panelAvailable, target) => { + expect(resolveSideThreadOpenTarget({ preference, intent, panelAvailable })).toBe(target); + }, + ); +}); + +describe("sideThreadOpenIntentOf", () => { + const plain = { metaKey: false, ctrlKey: false, button: 0 }; + + it("takes the platform's modifier and the middle button as the other place", () => { + expect(sideThreadOpenIntentOf(plain, true)).toBe("primary"); + expect(sideThreadOpenIntentOf({ ...plain, metaKey: true }, true)).toBe("alternate"); + expect(sideThreadOpenIntentOf({ ...plain, ctrlKey: true }, false)).toBe("alternate"); + expect(sideThreadOpenIntentOf({ ...plain, button: 1 }, false)).toBe("alternate"); + // A key press has no button. + expect(sideThreadOpenIntentOf({ metaKey: true, ctrlKey: false }, true)).toBe("alternate"); + }); + + it("ignores the other platform's modifier", () => { + // Ctrl-click on macOS is the context menu, and the Windows key is not Ctrl. + expect(sideThreadOpenIntentOf({ ...plain, ctrlKey: true }, true)).toBe("primary"); + expect(sideThreadOpenIntentOf({ ...plain, metaKey: true }, false)).toBe("primary"); + }); +}); + +describe("resolveMobileSideThreadPresentation", () => { + it("uses the inspector wherever the layout has one, else the full screen", () => { + expect(resolveMobileSideThreadPresentation({ inspectorAvailable: true })).toBe("inspector"); + expect(resolveMobileSideThreadPresentation({ inspectorAvailable: false })).toBe("full-screen"); + }); +}); diff --git a/packages/client-runtime/src/sideThread.ts b/packages/client-runtime/src/sideThread.ts new file mode 100644 index 0000000000000..8cac3a9552441 --- /dev/null +++ b/packages/client-runtime/src/sideThread.ts @@ -0,0 +1,94 @@ +import type { OrchestrationV2AppThread, SideThreadOpenTarget } from "@t3tools/contracts"; + +/** + * A thread that opens beside the one you are in. `linked` lives on a linked environment this client + * has no connection to; the others are threads of a connected environment. + */ +export type SideThreadKind = "side-chat" | "subagent" | "provider-subagent" | "linked"; + +/** + * Which side thread `thread` is, or null for a thread that opens like any other. A row that does + * not carry how the thread was created cannot tell a provider's own subagent from the app's. + */ +export function sideThreadKindOf( + thread: + | (Pick & + Partial>) + | null + | undefined, +): Exclude | null { + if (!thread) return null; + if (thread.lineage.sideChat === true && thread.lineage.parentThreadId !== null) { + return "side-chat"; + } + if (thread.lineage.relationshipToParent !== "subagent") return null; + return thread.creationSource === "provider" ? "provider-subagent" : "subagent"; +} + +export type SideThreadComposer = + /** The normal composer. */ + | "composer" + /** A bar that says the thread takes no messages. */ + | "read-only" + /** The same bar, offering to connect to the environment the thread is on. */ + | "read-only-connect"; + +/** What stands at the bottom of a side thread, in the panel and on the main screen alike. */ +export function sideThreadComposer(kind: SideThreadKind): SideThreadComposer { + switch (kind) { + case "linked": + return "read-only-connect"; + case "provider-subagent": + return "read-only"; + case "side-chat": + case "subagent": + return "composer"; + } +} + +/** + * How the user asked to open a side thread: a plain click or Enter, the same with the modifier + * (or a middle click), or one of the two places named outright, as a context menu does. + */ +export type SideThreadOpenIntent = "primary" | "alternate" | SideThreadOpenTarget; + +/** + * Where a side thread opens. The preference names the plain click's place and the modifier takes + * the other; without a panel to open in, everything goes to the main view. + */ +export function resolveSideThreadOpenTarget(input: { + readonly preference: SideThreadOpenTarget; + readonly intent: SideThreadOpenIntent; + readonly panelAvailable: boolean; +}): SideThreadOpenTarget { + if (!input.panelAvailable) return "main"; + switch (input.intent) { + case "primary": + return input.preference; + case "alternate": + return input.preference === "panel" ? "main" : "panel"; + default: + return input.intent; + } +} + +/** The intent of a click, an auxiliary click or a key press on a side thread's row. */ +export function sideThreadOpenIntentOf( + event: { + readonly metaKey: boolean; + readonly ctrlKey: boolean; + /** Absent on key events. */ + readonly button?: number; + }, + mac: boolean, +): Extract { + if (event.button === 1) return "alternate"; + return (mac ? event.metaKey : event.ctrlKey) ? "alternate" : "primary"; +} + +/** Where a side thread opens on mobile: the inspector pane where the layout has one. */ +export function resolveMobileSideThreadPresentation(input: { + readonly inspectorAvailable: boolean; +}): "inspector" | "full-screen" { + return input.inspectorAvailable ? "inspector" : "full-screen"; +} diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 378b8af0e466f..b0726b07174c9 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -315,6 +315,13 @@ export { export const BrowserLinkTarget = Schema.Literals(["system", "app"]); export type BrowserLinkTarget = typeof BrowserLinkTarget.Type; export const DEFAULT_BROWSER_LINK_TARGET: BrowserLinkTarget = "system"; +/** + * Where a plain click opens a subagent, a side chat or a linked environment's thread: beside the + * thread you are in, or in its place. A modified click opens it in the other one. + */ +export const SideThreadOpenTarget = Schema.Literals(["panel", "main"]); +export type SideThreadOpenTarget = typeof SideThreadOpenTarget.Type; +const DEFAULT_SIDE_THREAD_OPEN_TARGET: SideThreadOpenTarget = "panel"; /** * What the address bar searches with when the input is not an address. * "custom" uses `browserCustomSearchUrl`, a template with `%s` for the query. @@ -525,6 +532,9 @@ export const ClientSettingsSchema = Schema.Struct({ followUpBehavior: Schema.Literals(["queue", "steer"]).pipe( Schema.withDecodingDefault(Effect.succeed("steer")), ), + sideThreadOpenTarget: SideThreadOpenTarget.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDE_THREAD_OPEN_TARGET)), + ), proactivePanelsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), showSkillsInSlashMenu: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), boringSidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), @@ -2101,6 +2111,7 @@ export const ClientSettingsPatch = Schema.Struct({ composerRichTextEnabled: Schema.optionalKey(Schema.Boolean), sendShortcut: Schema.optionalKey(Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"])), followUpBehavior: Schema.optionalKey(Schema.Literals(["queue", "steer"])), + sideThreadOpenTarget: Schema.optionalKey(SideThreadOpenTarget), proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean), showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean), boringSidebarEnabled: Schema.optionalKey(Schema.Boolean), From 271357040676ea578f134493169df4b27ee080f6 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:52:50 +0530 Subject: [PATCH 6/7] fix(desktop): update checks say why a build with a different saved track offers nothing (#38506) Co-authored-by: Claude Haiku 5.5 Co-authored-by: Julius Marminge --- apps/desktop/src/i18n/translations/de.json | 3 + apps/desktop/src/i18n/translations/en.json | 3 + apps/desktop/src/i18n/translations/es.json | 3 + apps/desktop/src/i18n/translations/fr.json | 3 + apps/desktop/src/i18n/translations/ja.json | 3 + apps/desktop/src/i18n/translations/ko.json | 3 + apps/desktop/src/i18n/translations/pt-BR.json | 3 + apps/desktop/src/i18n/translations/ru.json | 3 + apps/desktop/src/i18n/translations/sv.json | 3 + apps/desktop/src/i18n/translations/zh.json | 3 + .../src/updates/DesktopUpdates.test.ts | 76 +++++++++++++++++-- apps/desktop/src/updates/DesktopUpdates.ts | 33 +++++++- apps/desktop/src/updates/updateMachine.ts | 32 +++++--- .../src/window/DesktopApplicationMenu.ts | 19 ++++- apps/mobile/src/i18n/translations/de.json | 2 + apps/mobile/src/i18n/translations/en.json | 2 + apps/mobile/src/i18n/translations/es.json | 2 + apps/mobile/src/i18n/translations/fr.json | 2 + apps/mobile/src/i18n/translations/ja.json | 2 + apps/mobile/src/i18n/translations/ko.json | 2 + apps/mobile/src/i18n/translations/pt-BR.json | 2 + apps/mobile/src/i18n/translations/ru.json | 2 + apps/mobile/src/i18n/translations/sv.json | 2 + apps/mobile/src/i18n/translations/zh.json | 2 + .../desktopUpdate/DesktopAppUpdate.test.ts | 29 +++++++ .../src/desktopUpdate/DesktopAppUpdate.ts | 15 +++- .../web/src/components/desktopUpdate.logic.ts | 9 +++ apps/web/src/i18n/translations/de.json | 2 + apps/web/src/i18n/translations/en.json | 2 + apps/web/src/i18n/translations/es.json | 2 + apps/web/src/i18n/translations/fr.json | 2 + apps/web/src/i18n/translations/ja.json | 2 + apps/web/src/i18n/translations/ko.json | 2 + apps/web/src/i18n/translations/pt-BR.json | 2 + apps/web/src/i18n/translations/ru.json | 2 + apps/web/src/i18n/translations/sv.json | 2 + apps/web/src/i18n/translations/zh.json | 2 + .../src/connection/outdatedHostUpdate.ts | 8 +- .../client-runtime/src/state/server.test.ts | 45 ++++++++--- packages/client-runtime/src/state/server.ts | 28 ++++++- packages/contracts/src/ipc.ts | 3 + packages/contracts/src/server.ts | 7 ++ 42 files changed, 339 insertions(+), 35 deletions(-) diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json index 92f2ec88b3bdb..8e39e7585f60d 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Browservorschau", "49de6209699eb616": "Unbenannter Passkey", "b4a5bb1075d95154": "Passkey auswählen", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Du bist auf dem neuesten Stand!", "c6399b55619e2f67": "T3 Code {version} ist derzeit die neueste verfügbare Version.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Neu starten", "116a21f6cc215e5f": "Suche nach Updates fehlgeschlagen", "32c88cd9421abf33": "Es konnte nicht nach Updates gesucht werden.", + "9e5ada64a94c10de": "Dieser {build}-Build kann sich über den Kanal {saved} nicht selbst aktualisieren. Stelle den Update-Kanal wieder auf {build} um oder nutze Review neben Update-Kanal, um den Wechsel zu {saved} erneut zu versuchen.", "b37aca07d3c644d9": "Ein unbekannter Fehler ist aufgetreten. Bitte versuche es später erneut.", "c8c23435e780a60c": "Updates nicht verfügbar", "aecf7c98b81bef7a": "Automatische Updates sind derzeit nicht verfügbar.", diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 964d6a7ed12f7..9a07ef060cbc9 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Browser preview", "49de6209699eb616": "Unnamed passkey", "b4a5bb1075d95154": "Choose a passkey", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "You're up to date!", "c6399b55619e2f67": "T3 Code {version} is currently the newest version available.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Restart", "116a21f6cc215e5f": "Update check failed", "32c88cd9421abf33": "Could not check for updates.", + "9e5ada64a94c10de": "This {build} build can't update from the {saved} track on its own. Switch the update track back to {build}, or use Review beside Update track to retry the switch to {saved}.", "b37aca07d3c644d9": "An unknown error occurred. Please try again later.", "c8c23435e780a60c": "Updates unavailable", "aecf7c98b81bef7a": "Automatic updates are not available right now.", diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index c1a64c21e241d..f891e9eaf850b 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Vista previa del navegador", "49de6209699eb616": "Llave de acceso sin nombre", "b4a5bb1075d95154": "Elige una llave de acceso", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Estable", "1f12213f4d809e89": "¡Estás al día!", "c6399b55619e2f67": "T3 Code {version} es la versión más reciente disponible.", "b6e5b31255e011c5": "Aceptar", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Reiniciar", "116a21f6cc215e5f": "Error al buscar actualizaciones", "32c88cd9421abf33": "No se pudo buscar actualizaciones.", + "9e5ada64a94c10de": "Esta compilación {build} no puede actualizarse por sí sola desde el canal {saved}. Vuelve a poner el canal de actualizaciones en {build} o usa Revisar junto a Canal de actualizaciones para reintentar el cambio a {saved}.", "b37aca07d3c644d9": "Se produjo un error desconocido. Vuelve a intentarlo más tarde.", "c8c23435e780a60c": "Actualizaciones no disponibles", "aecf7c98b81bef7a": "Las actualizaciones automáticas no están disponibles ahora mismo.", diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 4a0376ba9c94a..0bb5a47518581 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Aperçu du navigateur", "49de6209699eb616": "Clé d’accès sans nom", "b4a5bb1075d95154": "Choisir une clé d’accès", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Vous êtes à jour !", "c6399b55619e2f67": "T3 Code {version} est actuellement la version la plus récente.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Redémarrer", "116a21f6cc215e5f": "Échec de la recherche de mises à jour", "32c88cd9421abf33": "Impossible de rechercher des mises à jour.", + "9e5ada64a94c10de": "Cette version {build} ne peut pas se mettre à jour seule depuis le canal {saved}. Remettez le canal de mise à jour sur {build}, ou utilisez Consulter à côté de Canal de mise à jour pour relancer le passage à {saved}.", "b37aca07d3c644d9": "Une erreur inconnue s’est produite. Veuillez réessayer plus tard.", "c8c23435e780a60c": "Mises à jour indisponibles", "aecf7c98b81bef7a": "Les mises à jour automatiques ne sont pas disponibles pour le moment.", diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index 4b5db0e253a42..df89efe466261 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "ブラウザープレビュー", "49de6209699eb616": "名前のないパスキー", "b4a5bb1075d95154": "パスキーを選択", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "安定版", "1f12213f4d809e89": "最新の状態です", "c6399b55619e2f67": "T3 Code {version} が現在利用できる最新バージョンです。", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "再起動", "116a21f6cc215e5f": "更新の確認に失敗しました", "32c88cd9421abf33": "更新を確認できませんでした。", + "9e5ada64a94c10de": "この {build} ビルドは {saved} トラックから単独では更新できません。更新トラックを {build} に戻すか、更新トラックの横にある「レビュー」を使って {saved} への切り替えを再試行してください。", "b37aca07d3c644d9": "不明なエラーが発生しました。しばらくしてからもう一度お試しください。", "c8c23435e780a60c": "更新を利用できません", "aecf7c98b81bef7a": "現在、自動更新は利用できません。", diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index ccebba3366e84..566724b9b91c1 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "브라우저 미리 보기", "49de6209699eb616": "이름 없는 패스키", "b4a5bb1075d95154": "패스키 선택", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "최신 버전입니다!", "c6399b55619e2f67": "T3 Code {version}이(가) 현재 사용 가능한 최신 버전입니다.", "b6e5b31255e011c5": "확인", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "다시 시작", "116a21f6cc215e5f": "업데이트 확인 실패", "32c88cd9421abf33": "업데이트를 확인할 수 없습니다.", + "9e5ada64a94c10de": "이 {build} 빌드는 {saved} 트랙에서 스스로 업데이트할 수 없습니다. 업데이트 트랙을 다시 {build}(으)로 바꾸거나, 업데이트 트랙 옆의 검토를 사용해 {saved}(으)로 전환을 다시 시도하세요.", "b37aca07d3c644d9": "알 수 없는 오류가 발생했습니다. 나중에 다시 시도하세요.", "c8c23435e780a60c": "업데이트를 사용할 수 없음", "aecf7c98b81bef7a": "지금은 자동 업데이트를 사용할 수 없습니다.", diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 11e80a2f667bb..67f4eefd1c9ec 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Pré-visualização do navegador", "49de6209699eb616": "Chave de acesso sem nome", "b4a5bb1075d95154": "Escolha uma chave de acesso", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Estável", "1f12213f4d809e89": "Você está atualizado!", "c6399b55619e2f67": "O T3 Code {version} é a versão mais recente disponível.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Reiniciar", "116a21f6cc215e5f": "Falha ao verificar atualizações", "32c88cd9421abf33": "Não foi possível verificar atualizações.", + "9e5ada64a94c10de": "Esta build {build} não consegue se atualizar sozinha pelo canal {saved}. Volte o canal de atualização para {build} ou use Revisar ao lado de Canal de atualização para tentar de novo a mudança para {saved}.", "b37aca07d3c644d9": "Ocorreu um erro desconhecido. Tente novamente mais tarde.", "c8c23435e780a60c": "Atualizações indisponíveis", "aecf7c98b81bef7a": "As atualizações automáticas não estão disponíveis no momento.", diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index cdcf02d0648dd..46364dfabe488 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Предпросмотр в браузере", "49de6209699eb616": "Безымянный ключ доступа", "b4a5bb1075d95154": "Выберите ключ доступа", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Стабильный", "1f12213f4d809e89": "У вас последняя версия!", "c6399b55619e2f67": "T3 Code {version} — новейшая доступная версия.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Перезапустить", "116a21f6cc215e5f": "Ошибка проверки обновлений", "32c88cd9421abf33": "Не удалось проверить обновления.", + "9e5ada64a94c10de": "Эта сборка {build} не может сама обновиться с канала «{saved}». Верните канал обновлений на «{build}» или нажмите «Ревью» рядом с «Канал обновлений», чтобы повторить переход на «{saved}».", "b37aca07d3c644d9": "Произошла неизвестная ошибка. Повторите попытку позже.", "c8c23435e780a60c": "Обновления недоступны", "aecf7c98b81bef7a": "Автоматические обновления сейчас недоступны.", diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index e2a204965fec2..67bcaf6a380aa 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Förhandsvisning i webbläsaren", "49de6209699eb616": "Namnlös lösenordsnyckel", "b4a5bb1075d95154": "Välj en lösenordsnyckel", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Du har den senaste versionen!", "c6399b55619e2f67": "T3 Code {version} är den senaste tillgängliga versionen.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Starta om", "116a21f6cc215e5f": "Sökningen efter uppdateringar misslyckades", "32c88cd9421abf33": "Kunde inte söka efter uppdateringar.", + "9e5ada64a94c10de": "Den här {build}-versionen kan inte uppdatera sig själv från spåret {saved}. Byt tillbaka uppdateringsspåret till {build}, eller använd Granska bredvid Uppdateringsspår för att försöka byta till {saved} igen.", "b37aca07d3c644d9": "Ett okänt fel inträffade. Försök igen senare.", "c8c23435e780a60c": "Uppdateringar är inte tillgängliga", "aecf7c98b81bef7a": "Automatiska uppdateringar är inte tillgängliga just nu.", diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index 6a89cd600c37a..72122de01df62 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "浏览器预览", "49de6209699eb616": "未命名通行密钥", "b4a5bb1075d95154": "选择通行密钥", + "61aa0109862ff7ca": "Nightly 版", + "f3430cac09a505a0": "稳定版", "1f12213f4d809e89": "已是最新版本!", "c6399b55619e2f67": "T3 Code {version} 已是最新版本。", "b6e5b31255e011c5": "确定", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "重启", "116a21f6cc215e5f": "检查更新失败", "32c88cd9421abf33": "无法检查更新。", + "9e5ada64a94c10de": "此 {build} 构建无法自行从 {saved} 通道更新。请将更新通道切回 {build},或使用“更新通道”旁的“查看”重新尝试切换到 {saved}。", "b37aca07d3c644d9": "发生未知错误,请稍后重试。", "c8c23435e780a60c": "更新不可用", "aecf7c98b81bef7a": "目前无法自动更新。", diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 33ed00a764738..535e1123d2911 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -79,6 +79,17 @@ const stableUpdateInfo = ( }; }; +// Subscribes before emitting, so the state the emit publishes is the one awaited, not a scheduler yield. +const nextPublishedState = (emit: () => void) => + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + const { changes } = yield* updates.subscribe; + const published = yield* Stream.runHead(changes).pipe(Effect.forkChild); + emit(); + yield* Fiber.join(published); + return yield* updates.getState; + }); + describe("DesktopUpdates", () => { it.effect("updates Linux .deb installs and leaves other non-AppImage installs off", () => Effect.gen(function* () { @@ -1191,16 +1202,49 @@ describe("DesktopUpdates", () => { const updates = yield* DesktopUpdates.DesktopUpdates; yield* updates.configure; yield* updates.check("startup"); - harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" }); - yield* flushCallbacks; - - assert.equal((yield* updates.getState).channel, "nightly"); - assert.isNull((yield* updates.getState).availableVersion); + const state = yield* nextPublishedState(() => + harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" }), + ); + assert.equal(state.channel, "nightly"); + assert.isNull(state.availableVersion); + assert.equal(state.status, "error"); + assert.equal(state.errorContext, "check"); + assert.isTrue(state.canRetry); + assert.deepEqual(state.trackMismatch, { buildChannel: "latest" }); assert.deepEqual(harness.checkAllowedDowngrade, [false]); }), ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("reports a track mismatch when the feed offers no release at all", () => { + const harness = makeHarness({ savedChannel: "nightly" }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("startup"); + const state = yield* nextPublishedState(() => harness.emit("update-not-available")); + assert.equal(state.status, "error"); + assert.equal(state.errorContext, "check"); + assert.isTrue(state.canRetry); + assert.deepEqual(state.trackMismatch, { buildChannel: "latest" }); + + // A later failure has its own reason, so the mismatch must not stay attached to it. + const failed = yield* nextPublishedState(() => + harness.emit("error", new Error("background updater failure")), + ); + assert.isUndefined(failed.trackMismatch); + + const mismatched = yield* nextPublishedState(() => harness.emit("update-not-available")); + assert.isDefined(mismatched.trackMismatch); + yield* updates.check("menu"); + assert.equal((yield* updates.getState).status, "checking"); + assert.isUndefined((yield* updates.getState).trackMismatch); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("never offers an older Nightly to a Nightly build's own checks", () => { const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1" }); @@ -1389,6 +1433,28 @@ describe("DesktopUpdates under a managed policy", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("does not name a blocked build track as the one to switch back to", () => { + const harness = makeHarness({ + appVersion: "1.2.4-nightly.20261027.1", + savedChannel: "latest", + policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("startup"); + const state = yield* nextPublishedState(() => harness.emit("update-not-available")); + + assert.equal(state.channel, "latest"); + assert.equal(state.status, "error"); + assert.equal(state.errorContext, "check"); + assert.isUndefined(state.trackMismatch); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("does not report the channel as the only block when updates are off anyway", () => { const harness = makeHarness({ appVersion: "1.2.3-nightly.20261028.1", diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 775a9ff6b04ff..7976503d9e761 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -368,6 +368,13 @@ function getAutoUpdateDisabledReason(args: { return null; } +const trackLabel = (channel: DesktopUpdateChannel) => + channel === "nightly" ? "Nightly" : "Stable"; + +// Clients localize `trackMismatch`; this English text serves older renderers and remote reports. +const trackMismatchMessage = (build: DesktopUpdateChannel, saved: DesktopUpdateChannel) => + `This ${trackLabel(build)} build can't update from the ${trackLabel(saved)} track on its own. Switch the update track back to ${trackLabel(build)}, or use Review beside Update track to retry the switch to ${trackLabel(saved)}.`; + function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean { return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64"; } @@ -496,6 +503,26 @@ export const make = Effect.gen(function* () { ) : Option.none(); + // Without a release floor, a build on another track than its saved one never offers anything. + // A track the policy blocks is never named as the one to switch to. + const noOfferState = (state: DesktopUpdateState, checkedAt: string) => + Effect.map(Ref.get(releaseFloorRef), (floor) => { + const buildChannel = desktopUpdateChannelOf(environment.appVersion); + if (Option.isSome(floor) || buildChannel === state.channel) { + return reduceDesktopUpdateStateOnNoUpdate(state, checkedAt); + } + const blocked = channelBlockedReason(buildChannel); + if (Option.isSome(blocked)) { + return reduceDesktopUpdateStateOnCheckFailure(state, blocked.value, checkedAt); + } + return reduceDesktopUpdateStateOnCheckFailure( + state, + trackMismatchMessage(buildChannel, state.channel), + checkedAt, + { buildChannel }, + ); + }); + const resolveStateDisabledReason = (channel: DesktopUpdateChannel) => resolveDisabledReason.pipe(Effect.map(Option.orElse(() => channelBlockedReason(channel)))); @@ -1070,7 +1097,7 @@ export const make = Effect.gen(function* () { channel: state.channel, }); const checkedAt = yield* currentIsoTimestamp; - yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt)); + yield* setState(yield* noOfferState(state, checkedAt)); yield* Ref.set(lastLoggedDownloadMilestoneRef, -1); return; } @@ -1117,7 +1144,7 @@ export const make = Effect.gen(function* () { const handleUpdateNotAvailable = Effect.gen(function* () { const checkedAt = yield* currentIsoTimestamp; const state = yield* Ref.get(updateStateRef); - yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt)); + yield* setState(yield* noOfferState(state, checkedAt)); yield* Ref.set(lastLoggedDownloadMilestoneRef, -1); yield* logUpdaterInfo("no updates available"); }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable")); @@ -1145,7 +1172,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(activeAction)) { const checkedAt = yield* currentIsoTimestamp; - yield* updateState((current) => ({ + yield* updateState(({ trackMismatch: _trackMismatch, ...current }) => ({ ...current, status: "error", message: error.message, diff --git a/apps/desktop/src/updates/updateMachine.ts b/apps/desktop/src/updates/updateMachine.ts index 4d3852446b189..80751315657c0 100644 --- a/apps/desktop/src/updates/updateMachine.ts +++ b/apps/desktop/src/updates/updateMachine.ts @@ -11,6 +11,14 @@ function nextStatusAfterDownloadFailure( return currentState.availableVersion ? "available" : "error"; } +// A mismatch describes only the check that found it. +function withoutTrackMismatch({ + trackMismatch: _trackMismatch, + ...state +}: DesktopUpdateState): DesktopUpdateState { + return state; +} + function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean { return currentState.availableVersion !== null; } @@ -46,7 +54,7 @@ export function reduceDesktopUpdateStateOnCheckStart( ): DesktopUpdateState { const hasDownloadedUpdate = state.downloadedVersion !== null; return { - ...state, + ...withoutTrackMismatch(state), status: "checking", checkedAt, releaseNotes: hasDownloadedUpdate ? state.releaseNotes : [], @@ -62,10 +70,11 @@ export function reduceDesktopUpdateStateOnCheckFailure( state: DesktopUpdateState, message: string, checkedAt: string, + trackMismatch?: DesktopUpdateState["trackMismatch"], ): DesktopUpdateState { if (state.downloadedVersion !== null) { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", message: null, checkedAt, @@ -76,13 +85,14 @@ export function reduceDesktopUpdateStateOnCheckFailure( } return { - ...state, + ...withoutTrackMismatch(state), status: "error", message, checkedAt, downloadPercent: null, errorContext: "check", canRetry: true, + ...(trackMismatch === undefined ? {} : { trackMismatch }), }; } @@ -96,7 +106,7 @@ export function reduceDesktopUpdateStateOnUpdateAvailable( const isDownloadedVersion = state.downloadedVersion === version; const preserveReleaseNotes = isDownloadedVersion && releaseNotes.length === 0; return { - ...state, + ...withoutTrackMismatch(state), status: isDownloadedVersion ? "downloaded" : "available", availableVersion: version, downloadedVersion: isDownloadedVersion ? version : null, @@ -116,7 +126,7 @@ export function reduceDesktopUpdateStateOnNoUpdate( ): DesktopUpdateState { if (state.downloadedVersion !== null) { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", availableVersion: state.downloadedVersion, downloadPercent: 100, @@ -128,7 +138,7 @@ export function reduceDesktopUpdateStateOnNoUpdate( } return { - ...state, + ...withoutTrackMismatch(state), status: "up-to-date", availableVersion: null, downloadedVersion: null, @@ -146,7 +156,7 @@ export function reduceDesktopUpdateStateOnDownloadStart( state: DesktopUpdateState, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloading", downloadPercent: 0, message: null, @@ -160,7 +170,7 @@ export function reduceDesktopUpdateStateOnDownloadFailure( message: string, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: nextStatusAfterDownloadFailure(state), message, downloadPercent: null, @@ -174,7 +184,7 @@ export function reduceDesktopUpdateStateOnDownloadProgress( percent: number, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloading", downloadPercent: percent, message: null, @@ -188,7 +198,7 @@ export function reduceDesktopUpdateStateOnDownloadComplete( version: string, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", availableVersion: version, downloadedVersion: version, @@ -204,7 +214,7 @@ export function reduceDesktopUpdateStateOnInstallFailure( message: string, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", message, errorContext: "install", diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 392208d5b54c9..543d8d245731b 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -4,6 +4,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import type { DesktopUpdateChannel } from "@t3tools/contracts"; import * as Electron from "electron"; import { msg } from "gt-i18n"; @@ -68,6 +69,11 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")( yield* desktopWindow.runMainContentsCommand(command); }); +const trackLabel = (channel: DesktopUpdateChannel) => + channel === "nightly" + ? m(msg("Nightly", { $context: "release track" })) + : m(msg("Stable", { $context: "release track" })); + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -134,7 +140,18 @@ const checkForUpdatesFromMenu = Effect.gen(function* () { type: "warning", title: m(msg("Update check failed")), message: m(msg("Could not check for updates.")), - detail: updateState.message ?? m(msg("An unknown error occurred. Please try again later.")), + detail: + updateState.trackMismatch !== undefined + ? m( + msg( + "This {build} build can't update from the {saved} track on its own. Switch the update track back to {build}, or use Review beside Update track to retry the switch to {saved}.", + ), + { + build: trackLabel(updateState.trackMismatch.buildChannel), + saved: trackLabel(updateState.channel), + }, + ) + : (updateState.message ?? m(msg("An unknown error occurred. Please try again later."))), buttons: [m(msg("OK"))], }); } diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 4d04ac029bf64..f5376272f166b 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "Das Update auf t3@{version} wurde zurückgerollt.", "31dc4da5813e0846": "Das Update auf t3@{version} ist fehlgeschlagen.", "b060872e18e91755": "Server-Update fehlgeschlagen.", + "77231250643f4943": "Dieser {build, select, nightly {Nightly} other {Stable}}-Build kann sich über den Kanal {saved, select, nightly {Nightly} other {Stable}} nicht selbst aktualisieren. Stelle den Update-Kanal wieder auf {build, select, nightly {Nightly} other {Stable}} um oder nutze Review neben Update-Kanal, um den Wechsel zu {saved, select, nightly {Nightly} other {Stable}} erneut zu versuchen.", + "43ed503038717b90": "Server-Update fehlgeschlagen:", "a8cb0a2b46270859": "Die Umgebungsdaten konnten nicht synchronisiert werden.", "4731d4616735186c": "{count, plural, one {{count} Subagent gestartet} other {{count} Subagenten gestartet}}", "885110d4e416d2cd": "{count, plural, one {{count} Subagent ausgeführt} other {{count} Subagenten ausgeführt}}", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index ac22e97d21be3..4e979ede57900 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "The t3@{version} update rolled-back.", "31dc4da5813e0846": "The t3@{version} update failed.", "b060872e18e91755": "Server update failed.", + "77231250643f4943": "This {build, select, nightly {Nightly} other {Stable}} build can't update from the {saved, select, nightly {Nightly} other {Stable}} track on its own. Switch the update track back to {build, select, nightly {Nightly} other {Stable}}, or use Review beside Update track to retry the switch to {saved, select, nightly {Nightly} other {Stable}}.", + "43ed503038717b90": "Server update failed:", "a8cb0a2b46270859": "Could not synchronize environment data.", "4731d4616735186c": "{count, plural, one {Kicked off {count} subagent} other {Kicked off {count} subagents}}", "885110d4e416d2cd": "{count, plural, one {Ran {count} subagent} other {Ran {count} subagents}}", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 046959950b3b0..167eccebe4341 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "La actualización a t3@{version} se revirtió.", "31dc4da5813e0846": "La actualización a t3@{version} falló.", "b060872e18e91755": "Falló la actualización del servidor.", + "77231250643f4943": "Esta compilación {build, select, nightly {Nightly} other {Estable}} no puede actualizarse por sí sola desde el canal {saved, select, nightly {Nightly} other {Estable}}. Vuelve a poner el canal de actualizaciones en {build, select, nightly {Nightly} other {Estable}} o usa Revisar junto a Canal de actualizaciones para reintentar el cambio a {saved, select, nightly {Nightly} other {Estable}}.", + "43ed503038717b90": "Falló la actualización del servidor:", "a8cb0a2b46270859": "No se pudieron sincronizar los datos del entorno.", "4731d4616735186c": "{count, plural, one {Se inició {count} subagente} other {Se iniciaron {count} subagentes}}", "885110d4e416d2cd": "{count, plural, one {Se ejecutó {count} subagente} other {Se ejecutaron {count} subagentes}}", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index c156610bd5c09..62ddd1e271583 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "La mise à jour t3@{version} a été annulée.", "31dc4da5813e0846": "La mise à jour t3@{version} a échoué.", "b060872e18e91755": "Échec de la mise à jour du serveur.", + "77231250643f4943": "Cette version {build, select, nightly {Nightly} other {Stable}} ne peut pas se mettre à jour seule depuis le canal {saved, select, nightly {Nightly} other {Stable}}. Remettez le canal de mise à jour sur {build, select, nightly {Nightly} other {Stable}}, ou utilisez Consulter à côté de Canal de mise à jour pour relancer le passage à {saved, select, nightly {Nightly} other {Stable}}.", + "43ed503038717b90": "Échec de la mise à jour du serveur :", "a8cb0a2b46270859": "Impossible de synchroniser les données de l’environnement.", "4731d4616735186c": "{count, plural, one {{count} sous-agent lancé} other {{count} sous-agents lancés}}", "885110d4e416d2cd": "{count, plural, one {{count} sous-agent exécuté} other {{count} sous-agents exécutés}}", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 019032f1eee88..21c9d1c07caeb 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "t3@{version} の更新はロールバックされました。", "31dc4da5813e0846": "t3@{version} の更新に失敗しました。", "b060872e18e91755": "サーバーの更新に失敗しました。", + "77231250643f4943": "この {build, select, nightly {Nightly} other {安定版}} ビルドは {saved, select, nightly {Nightly} other {安定版}} トラックから単独では更新できません。更新トラックを {build, select, nightly {Nightly} other {安定版}} に戻すか、更新トラックの横にある「レビュー」を使って {saved, select, nightly {Nightly} other {安定版}} への切り替えを再試行してください。", + "43ed503038717b90": "サーバーの更新に失敗しました:", "a8cb0a2b46270859": "環境のデータを同期できませんでした。", "4731d4616735186c": "{count, plural, other {{count} 個のサブエージェントを開始しました}}", "885110d4e416d2cd": "{count, plural, other {{count} 個のサブエージェントを実行しました}}", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index de7e21280597f..c20f81a58cc5e 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "t3@{version} 업데이트가 롤백되었습니다.", "31dc4da5813e0846": "t3@{version} 업데이트에 실패했습니다.", "b060872e18e91755": "서버 업데이트에 실패했습니다.", + "77231250643f4943": "이 {build, select, nightly {Nightly} other {Stable}} 빌드는 {saved, select, nightly {Nightly} other {Stable}} 트랙에서 스스로 업데이트할 수 없습니다. 업데이트 트랙을 다시 {build, select, nightly {Nightly} other {Stable}}(으)로 바꾸거나, 업데이트 트랙 옆의 검토를 사용해 {saved, select, nightly {Nightly} other {Stable}}(으)로 전환을 다시 시도하세요.", + "43ed503038717b90": "서버 업데이트에 실패했습니다:", "a8cb0a2b46270859": "환경 데이터를 동기화할 수 없습니다.", "4731d4616735186c": "{count, plural, other {서브에이전트 {count}개 시작함}}", "885110d4e416d2cd": "{count, plural, other {서브에이전트 {count}개 실행함}}", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 46a70448abf80..cf0d354e72348 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "A atualização t3@{version} foi revertida.", "31dc4da5813e0846": "A atualização t3@{version} falhou.", "b060872e18e91755": "Falha ao atualizar o servidor.", + "77231250643f4943": "Esta build {build, select, nightly {Nightly} other {Estável}} não consegue se atualizar sozinha pelo canal {saved, select, nightly {Nightly} other {Estável}}. Volte o canal de atualização para {build, select, nightly {Nightly} other {Estável}} ou use Revisar ao lado de Canal de atualização para tentar de novo a mudança para {saved, select, nightly {Nightly} other {Estável}}.", + "43ed503038717b90": "Falha ao atualizar o servidor:", "a8cb0a2b46270859": "Não foi possível sincronizar os dados do ambiente.", "4731d4616735186c": "{count, plural, one {{count} subagente iniciado} other {{count} subagentes iniciados}}", "885110d4e416d2cd": "{count, plural, one {{count} subagente executado} other {{count} subagentes executados}}", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 0632e3bf3d673..ffaca4ccd565f 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "Обновление t3@{version} откачено.", "31dc4da5813e0846": "Ошибка обновления t3@{version}.", "b060872e18e91755": "Не удалось обновить сервер.", + "77231250643f4943": "Эта сборка {build, select, nightly {Nightly} other {Стабильный}} не может сама обновиться с канала «{saved, select, nightly {Nightly} other {Стабильный}}». Верните канал обновлений на «{build, select, nightly {Nightly} other {Стабильный}}» или нажмите «Ревью» рядом с «Канал обновлений», чтобы повторить переход на «{saved, select, nightly {Nightly} other {Стабильный}}».", + "43ed503038717b90": "Не удалось обновить сервер:", "a8cb0a2b46270859": "Не удалось синхронизировать данные окружения.", "4731d4616735186c": "{count, plural, one {Запущен {count} субагент} few {Запущено {count} субагента} many {Запущено {count} субагентов} other {Запущено {count} субагента}}", "885110d4e416d2cd": "{count, plural, one {Отработал {count} субагент} few {Отработали {count} субагента} many {Отработали {count} субагентов} other {Отработали {count} субагента}}", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7d613fb7b3c9b..37900f9038e10 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "Uppdateringen till t3@{version} återställdes.", "31dc4da5813e0846": "Uppdateringen till t3@{version} misslyckades.", "b060872e18e91755": "Serveruppdateringen misslyckades.", + "77231250643f4943": "Den här {build, select, nightly {Nightly} other {Stable}}-versionen kan inte uppdatera sig själv från spåret {saved, select, nightly {Nightly} other {Stable}}. Byt tillbaka uppdateringsspåret till {build, select, nightly {Nightly} other {Stable}}, eller använd Granska bredvid Uppdateringsspår för att försöka byta till {saved, select, nightly {Nightly} other {Stable}} igen.", + "43ed503038717b90": "Serveruppdateringen misslyckades:", "a8cb0a2b46270859": "Kunde inte synkronisera miljöns data.", "4731d4616735186c": "{count, plural, one {Startade {count} subagent} other {Startade {count} subagenter}}", "885110d4e416d2cd": "{count, plural, one {Körde {count} subagent} other {Körde {count} subagenter}}", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index b560f0af3fbf0..882879f9c739e 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -732,6 +732,8 @@ "b50da99bbfd59a6d": "t3@{version} 更新已回滚。", "31dc4da5813e0846": "t3@{version} 更新失败。", "b060872e18e91755": "服务器更新失败。", + "77231250643f4943": "此 {build, select, nightly {Nightly 版} other {稳定版}} 构建无法自行从 {saved, select, nightly {Nightly 版} other {稳定版}} 通道更新。请将更新通道切回 {build, select, nightly {Nightly 版} other {稳定版}},或使用“更新通道”旁的“查看”重新尝试切换到 {saved, select, nightly {Nightly 版} other {稳定版}}。", + "43ed503038717b90": "服务器更新失败:", "a8cb0a2b46270859": "无法同步环境数据。", "4731d4616735186c": "{count, plural, other {已启动 {count} 个子智能体}}", "885110d4e416d2cd": "{count, plural, other {已运行 {count} 个子智能体}}", diff --git a/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts b/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts index b38dc6efb66d3..4d447ff7e85fa 100644 --- a/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts +++ b/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts @@ -204,6 +204,35 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("desktop app upda }), ); + it.effect.each([true, false])( + "carries the track mismatch only for its own failure (%s)", + (matchingReason) => + Effect.gen(function* () { + const mismatch = "This Stable build can't update from the Nightly track on its own."; + const reason = matchingReason ? mismatch : "The desktop update was cancelled."; + const { service } = yield* makeHarness({ + reports: (requestId) => [ + report( + requestId, + makeState({ + status: "error", + channel: "nightly", + message: mismatch, + errorContext: "check", + trackMismatch: { buildChannel: "latest" }, + }), + { outcome: "failed", reason }, + ), + ], + }); + const error = yield* service.run(() => Effect.void).pipe(Effect.flip); + expect(error.reason).toBe(reason); + expect(error.trackMismatch).toEqual( + matchingReason ? { buildChannel: "latest", savedChannel: "nightly" } : undefined, + ); + }), + ); + it.effect("fails when the desktop stops reporting before a terminal outcome", () => Effect.gen(function* () { const { service } = yield* makeHarness({ diff --git a/apps/server/src/desktopUpdate/DesktopAppUpdate.ts b/apps/server/src/desktopUpdate/DesktopAppUpdate.ts index 4963c09b2f6e5..ed1d3bba7f822 100644 --- a/apps/server/src/desktopUpdate/DesktopAppUpdate.ts +++ b/apps/server/src/desktopUpdate/DesktopAppUpdate.ts @@ -137,9 +137,18 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* ( `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`, ); } - return yield* failWith( - report.reason ?? report.state.message ?? "The desktop app update failed.", - ); + const reason = report.reason ?? report.state.message ?? "The desktop app update failed."; + const mismatch = report.state.trackMismatch; + if (mismatch !== undefined && reason === report.state.message) { + return yield* new ServerSelfUpdateError({ + reason, + trackMismatch: { + buildChannel: mismatch.buildChannel, + savedChannel: report.state.channel, + }, + }); + } + return yield* failWith(reason); }); const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")( diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.ts index b853c448a10bb..d3d4f618c8268 100644 --- a/apps/web/src/components/desktopUpdate.logic.ts +++ b/apps/web/src/components/desktopUpdate.logic.ts @@ -1,3 +1,4 @@ +import { desktopTrackMismatchText } from "@t3tools/client-runtime/state/server"; import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts"; import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; import { msg } from "gt-react"; @@ -159,6 +160,14 @@ export function getDesktopUpdateButtonTooltip( }), ); } + if (state.trackMismatch !== undefined) { + return resolve( + desktopTrackMismatchText({ + buildChannel: state.trackMismatch.buildChannel, + savedChannel: state.channel, + }), + ); + } return state.message ?? resolve(msg("Update failed")); } // The updater discards every release of the other track, so "up to date" would be false here. diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index f49ef838a02e0..20f1962571b12 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "Das Update auf t3@{version} wurde zurückgerollt.", "31dc4da5813e0846": "Das Update auf t3@{version} ist fehlgeschlagen.", "b060872e18e91755": "Server-Update fehlgeschlagen.", + "77231250643f4943": "Dieser {build, select, nightly {Nightly} other {Stable}}-Build kann sich über den Kanal {saved, select, nightly {Nightly} other {Stable}} nicht selbst aktualisieren. Stelle den Update-Kanal wieder auf {build, select, nightly {Nightly} other {Stable}} um oder nutze Review neben Update-Kanal, um den Wechsel zu {saved, select, nightly {Nightly} other {Stable}} erneut zu versuchen.", + "43ed503038717b90": "Server-Update fehlgeschlagen:", "a8cb0a2b46270859": "Die Umgebungsdaten konnten nicht synchronisiert werden.", "4731d4616735186c": "{count, plural, one {{count} Subagent gestartet} other {{count} Subagenten gestartet}}", "885110d4e416d2cd": "{count, plural, one {{count} Subagent ausgeführt} other {{count} Subagenten ausgeführt}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index ba8a96f2b96ae..ce59dc61ea67c 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "The t3@{version} update rolled-back.", "31dc4da5813e0846": "The t3@{version} update failed.", "b060872e18e91755": "Server update failed.", + "77231250643f4943": "This {build, select, nightly {Nightly} other {Stable}} build can't update from the {saved, select, nightly {Nightly} other {Stable}} track on its own. Switch the update track back to {build, select, nightly {Nightly} other {Stable}}, or use Review beside Update track to retry the switch to {saved, select, nightly {Nightly} other {Stable}}.", + "43ed503038717b90": "Server update failed:", "a8cb0a2b46270859": "Could not synchronize environment data.", "4731d4616735186c": "{count, plural, one {Kicked off {count} subagent} other {Kicked off {count} subagents}}", "885110d4e416d2cd": "{count, plural, one {Ran {count} subagent} other {Ran {count} subagents}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 2dc62e4340467..93c1737d59187 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "La actualización a t3@{version} se revirtió.", "31dc4da5813e0846": "La actualización a t3@{version} falló.", "b060872e18e91755": "Falló la actualización del servidor.", + "77231250643f4943": "Esta compilación {build, select, nightly {Nightly} other {Estable}} no puede actualizarse por sí sola desde el canal {saved, select, nightly {Nightly} other {Estable}}. Vuelve a poner el canal de actualizaciones en {build, select, nightly {Nightly} other {Estable}} o usa Revisar junto a Canal de actualizaciones para reintentar el cambio a {saved, select, nightly {Nightly} other {Estable}}.", + "43ed503038717b90": "Falló la actualización del servidor:", "a8cb0a2b46270859": "No se pudieron sincronizar los datos del entorno.", "4731d4616735186c": "{count, plural, one {Se inició {count} subagente} other {Se iniciaron {count} subagentes}}", "885110d4e416d2cd": "{count, plural, one {Se ejecutó {count} subagente} other {Se ejecutaron {count} subagentes}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 5b6f8fe3684fe..75c5a81e3af72 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "La mise à jour t3@{version} a été annulée.", "31dc4da5813e0846": "La mise à jour t3@{version} a échoué.", "b060872e18e91755": "Échec de la mise à jour du serveur.", + "77231250643f4943": "Cette version {build, select, nightly {Nightly} other {Stable}} ne peut pas se mettre à jour seule depuis le canal {saved, select, nightly {Nightly} other {Stable}}. Remettez le canal de mise à jour sur {build, select, nightly {Nightly} other {Stable}}, ou utilisez Consulter à côté de Canal de mise à jour pour relancer le passage à {saved, select, nightly {Nightly} other {Stable}}.", + "43ed503038717b90": "Échec de la mise à jour du serveur :", "a8cb0a2b46270859": "Impossible de synchroniser les données de l’environnement.", "4731d4616735186c": "{count, plural, one {{count} sous-agent lancé} other {{count} sous-agents lancés}}", "885110d4e416d2cd": "{count, plural, one {{count} sous-agent exécuté} other {{count} sous-agents exécutés}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 925d388aaac83..2b29b15b06cec 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "t3@{version} の更新はロールバックされました。", "31dc4da5813e0846": "t3@{version} の更新に失敗しました。", "b060872e18e91755": "サーバーの更新に失敗しました。", + "77231250643f4943": "この {build, select, nightly {Nightly} other {安定版}} ビルドは {saved, select, nightly {Nightly} other {安定版}} トラックから単独では更新できません。更新トラックを {build, select, nightly {Nightly} other {安定版}} に戻すか、更新トラックの横にある「レビュー」を使って {saved, select, nightly {Nightly} other {安定版}} への切り替えを再試行してください。", + "43ed503038717b90": "サーバーの更新に失敗しました:", "a8cb0a2b46270859": "環境のデータを同期できませんでした。", "4731d4616735186c": "{count, plural, other {{count} 個のサブエージェントを開始しました}}", "885110d4e416d2cd": "{count, plural, other {{count} 個のサブエージェントを実行しました}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index f3db2a16565c7..6995e81d19f37 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "t3@{version} 업데이트가 롤백되었습니다.", "31dc4da5813e0846": "t3@{version} 업데이트에 실패했습니다.", "b060872e18e91755": "서버 업데이트에 실패했습니다.", + "77231250643f4943": "이 {build, select, nightly {Nightly} other {Stable}} 빌드는 {saved, select, nightly {Nightly} other {Stable}} 트랙에서 스스로 업데이트할 수 없습니다. 업데이트 트랙을 다시 {build, select, nightly {Nightly} other {Stable}}(으)로 바꾸거나, 업데이트 트랙 옆의 검토를 사용해 {saved, select, nightly {Nightly} other {Stable}}(으)로 전환을 다시 시도하세요.", + "43ed503038717b90": "서버 업데이트에 실패했습니다:", "a8cb0a2b46270859": "환경 데이터를 동기화할 수 없습니다.", "4731d4616735186c": "{count, plural, other {서브에이전트 {count}개 시작함}}", "885110d4e416d2cd": "{count, plural, other {서브에이전트 {count}개 실행함}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 13dbeaf291427..fada341a7a9b0 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "A atualização t3@{version} foi revertida.", "31dc4da5813e0846": "A atualização t3@{version} falhou.", "b060872e18e91755": "Falha ao atualizar o servidor.", + "77231250643f4943": "Esta build {build, select, nightly {Nightly} other {Estável}} não consegue se atualizar sozinha pelo canal {saved, select, nightly {Nightly} other {Estável}}. Volte o canal de atualização para {build, select, nightly {Nightly} other {Estável}} ou use Revisar ao lado de Canal de atualização para tentar de novo a mudança para {saved, select, nightly {Nightly} other {Estável}}.", + "43ed503038717b90": "Falha ao atualizar o servidor:", "a8cb0a2b46270859": "Não foi possível sincronizar os dados do ambiente.", "4731d4616735186c": "{count, plural, one {{count} subagente iniciado} other {{count} subagentes iniciados}}", "885110d4e416d2cd": "{count, plural, one {{count} subagente executado} other {{count} subagentes executados}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index fa60799c89a78..42f112f26d25b 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "Обновление t3@{version} откачено.", "31dc4da5813e0846": "Ошибка обновления t3@{version}.", "b060872e18e91755": "Не удалось обновить сервер.", + "77231250643f4943": "Эта сборка {build, select, nightly {Nightly} other {Стабильный}} не может сама обновиться с канала «{saved, select, nightly {Nightly} other {Стабильный}}». Верните канал обновлений на «{build, select, nightly {Nightly} other {Стабильный}}» или нажмите «Ревью» рядом с «Канал обновлений», чтобы повторить переход на «{saved, select, nightly {Nightly} other {Стабильный}}».", + "43ed503038717b90": "Не удалось обновить сервер:", "a8cb0a2b46270859": "Не удалось синхронизировать данные окружения.", "4731d4616735186c": "{count, plural, one {Запущен {count} субагент} few {Запущено {count} субагента} many {Запущено {count} субагентов} other {Запущено {count} субагента}}", "885110d4e416d2cd": "{count, plural, one {Отработал {count} субагент} few {Отработали {count} субагента} many {Отработали {count} субагентов} other {Отработали {count} субагента}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 7cb5b4f31ead7..f5d040f3bb0d3 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "Uppdateringen till t3@{version} återställdes.", "31dc4da5813e0846": "Uppdateringen till t3@{version} misslyckades.", "b060872e18e91755": "Serveruppdateringen misslyckades.", + "77231250643f4943": "Den här {build, select, nightly {Nightly} other {Stable}}-versionen kan inte uppdatera sig själv från spåret {saved, select, nightly {Nightly} other {Stable}}. Byt tillbaka uppdateringsspåret till {build, select, nightly {Nightly} other {Stable}}, eller använd Granska bredvid Uppdateringsspår för att försöka byta till {saved, select, nightly {Nightly} other {Stable}} igen.", + "43ed503038717b90": "Serveruppdateringen misslyckades:", "a8cb0a2b46270859": "Kunde inte synkronisera miljöns data.", "4731d4616735186c": "{count, plural, one {Startade {count} subagent} other {Startade {count} subagenter}}", "885110d4e416d2cd": "{count, plural, one {Körde {count} subagent} other {Körde {count} subagenter}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 264cdc880110f..0d3e8e2489295 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -733,6 +733,8 @@ "b50da99bbfd59a6d": "t3@{version} 更新已回滚。", "31dc4da5813e0846": "t3@{version} 更新失败。", "b060872e18e91755": "服务器更新失败。", + "77231250643f4943": "此 {build, select, nightly {Nightly 版} other {稳定版}} 构建无法自行从 {saved, select, nightly {Nightly 版} other {稳定版}} 通道更新。请将更新通道切回 {build, select, nightly {Nightly 版} other {稳定版}},或使用“更新通道”旁的“查看”重新尝试切换到 {saved, select, nightly {Nightly 版} other {稳定版}}。", + "43ed503038717b90": "服务器更新失败:", "a8cb0a2b46270859": "无法同步环境数据。", "4731d4616735186c": "{count, plural, other {已启动 {count} 个子智能体}}", "885110d4e416d2cd": "{count, plural, other {已运行 {count} 个子智能体}}", diff --git a/packages/client-runtime/src/connection/outdatedHostUpdate.ts b/packages/client-runtime/src/connection/outdatedHostUpdate.ts index 442a54b928ada..0af68e0edc892 100644 --- a/packages/client-runtime/src/connection/outdatedHostUpdate.ts +++ b/packages/client-runtime/src/connection/outdatedHostUpdate.ts @@ -24,7 +24,11 @@ import * as Socket from "effect/socket/Socket"; import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts"; import { makeWsRpcProtocolClient, PING_TIMEOUT } from "../rpc/protocol.ts"; -import { isLegacyUpdateHandoffLoss, resolveServerUpdateProgressResult } from "../state/server.ts"; +import { + isLegacyUpdateHandoffLoss, + localizeServerSelfUpdateError, + resolveServerUpdateProgressResult, +} from "../state/server.ts"; import * as RelayEnvironmentDiscovery from "../relay/discovery.ts"; import * as ConnectionResolver from "./resolver.ts"; import * as EnvironmentRegistry from "./registry.ts"; @@ -206,7 +210,7 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd } return updateResult; }), - ); + ).pipe(Effect.mapError(localizeServerSelfUpdateError)); yield* onStage("resuming"); const pollUrls = [ diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index 1778f91ebc764..782e5fc62a75e 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -66,12 +66,14 @@ import { resolveServerUpdateProgressResult, serverUpdateStateForProgressEvent, serverUpdateStateAtom, + serverUpdateFailureText, serverUpdateStateForServerVersion, validateServerUpdateReadyEvent, waitForNextEnvironmentReconnect, waitForDesktopUpdateTarget, runDesktopCommitWithReconnectObserver, } from "./server.ts"; +import { errorDisplayMessage, errorI18nMessage } from "../errors/translatable.ts"; import { runAtomCommand } from "./runtime.ts"; import { applyServerConfigProjection } from "./serverConfigProjection.ts"; @@ -239,14 +241,21 @@ describe("accepted server update recovery", () => { { loss: "interrupt", resumes: true }, { loss: "socket", resumes: true }, { loss: "server_error", resumes: false }, + { loss: "track_mismatch", method: "desktop-managed", resumes: false }, + { loss: "track_mismatch", method: "desktop-managed", unary: true, resumes: false }, { loss: "no_progress", resumes: false }, { loss: "cancel", resumes: false }, { loss: "socket", method: "respawn", resumes: true }, { loss: "socket", method: "desktop-managed", resumes: false }, - ] as const)("handles $loss with $method and recovery=$resumes", (scenario) => + ] as const)("handles $loss with $method, unary=$unary and recovery=$resumes", (scenario) => Effect.gen(function* () { const { loss, resumes } = scenario; const method = "method" in scenario ? scenario.method : "boot-service"; + const trackMismatch = new ServerSelfUpdateError({ + reason: + "This Stable build can't update from the Nightly track on its own. Switch the update track back to Stable, or use Review beside Update track to retry the switch to Nightly.", + trackMismatch: { buildChannel: "latest", savedChannel: "nightly" }, + }); const observing = yield* Deferred.make(); const cancelFiber = yield* Deferred.make>(); const oldReadyObserved = yield* Deferred.make(); @@ -257,7 +266,10 @@ describe("accepted server update recovery", () => { environment: { ...CONFIG.environment, serverVersion: "0.0.30", - capabilities: { serverSelfUpdate: method, serverSelfUpdateProgress: true }, + capabilities: { + serverSelfUpdate: method, + serverSelfUpdateProgress: !("unary" in scenario), + }, }, } as ServerConfig; const ready = (serverVersion: string) => @@ -283,6 +295,7 @@ describe("accepted server update recovery", () => { ), ) : Stream.make(ready("0.0.30")).pipe(Stream.concat(Stream.never)), + [WS_METHODS.serverUpdateServer]: () => Effect.fail(trackMismatch), [WS_METHODS.serverUpdateServerWithProgress]: () => Stream.unwrap( Effect.sync(() => { @@ -306,9 +319,11 @@ describe("accepted server update recovery", () => { ? new ServerSelfUpdateError({ reason: "Archive verification failed.", }) - : new RpcClientError.RpcClientError({ - reason: new Socket.SocketCloseError({ code: 1006 }), - }), + : loss === "track_mismatch" + ? trackMismatch + : new RpcClientError.RpcClientError({ + reason: new Socket.SocketCloseError({ code: 1006 }), + }), ), ), ), @@ -377,10 +392,22 @@ describe("accepted server update recovery", () => { ); if (!resumes) { expect(first).toBe("settled"); - expect(AsyncResult.isFailure(yield* Effect.promise(() => pending))).toBe(true); - expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toMatchObject({ - status: "failed", - }); + const failure = yield* Effect.promise(() => pending); + expect(AsyncResult.isFailure(failure)).toBe(true); + const failed = registry.get(serverUpdateStateAtom(TARGET.environmentId)); + expect(failed).toMatchObject({ status: "failed" }); + if ( + loss === "track_mismatch" && + AsyncResult.isFailure(failure) && + failed.status === "failed" + ) { + const cause = Cause.squash(failure.cause); + const marked = errorI18nMessage(cause); + expect(marked).toHaveLength(2); + expect(failed.i18nMessage).toEqual(marked); + expect(errorDisplayMessage(cause)).toBe(trackMismatch.message); + expect(serverUpdateFailureText(failed)).toBe(trackMismatch.message); + } return; } expect(first).toBe("observing"); diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 8cf0be6f31705..3179f0c149e4b 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -4,8 +4,10 @@ import { markedTextEnglish, resolveMarkedText, thrownErrorMessage, + withI18nMessage, } from "../errors/translatable.ts"; import { + type DesktopUpdateChannel, type EnvironmentId, type ProviderInstanceId, type ServerConfig, @@ -13,6 +15,7 @@ import { type ServerLifecycleWelcomePayload, type ServerLifecycleStreamReadyEvent, type ServerProviderWorkspaceSnapshot, + ServerSelfUpdateError, type ServerSelfUpdateProgressEvent, type ServerSelfUpdateResult, shouldRecommendDatabaseCompaction, @@ -388,6 +391,29 @@ export function serverUpdateFailure(error: unknown): { : { message: serverUpdateFailureMessage(error), i18nMessage }; } +/** Marked text for a desktop app whose build track differs from its saved update track. */ +export function desktopTrackMismatchText(mismatch: { + readonly buildChannel: DesktopUpdateChannel; + readonly savedChannel: DesktopUpdateChannel; +}): string { + return msg( + "This {build, select, nightly {Nightly} other {Stable}} build can't update from the {saved, select, nightly {Nightly} other {Stable}} track on its own. Switch the update track back to {build, select, nightly {Nightly} other {Stable}}, or use Review beside Update track to retry the switch to {saved, select, nightly {Nightly} other {Stable}}.", + { build: mismatch.buildChannel, saved: mismatch.savedChannel }, + ); +} + +const isServerSelfUpdateError = Schema.is(ServerSelfUpdateError); + +/** Gives a host's track mismatch marked text; older hosts send only the English `reason`. */ +export function localizeServerSelfUpdateError(error: E): E { + if (!isServerSelfUpdateError(error) || error.trackMismatch === undefined) return error; + return withI18nMessage( + error, + msg("Server update failed:"), + desktopTrackMismatchText(error.trackMismatch), + ); +} + export function serverUpdateFailureText( state: Extract, resolve: MFunctionType = mFallback, @@ -1218,7 +1244,7 @@ export function createServerEnvironmentAtoms( targetVersion, }); return updateResult; - }), + }).pipe(Effect.mapError(localizeServerSelfUpdateError)), ); // A track switch's desktop host already on its track's newest build only saved the diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 77a523c03608f..dc0e70f7dad92 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -292,6 +292,8 @@ export interface DesktopUpdateState { notAppliedVersion?: string; /** Off only because a managed policy rules out this channel; switching channels turns it on. */ channelBlockedByPolicy?: true; + /** The check failed only because this build's track differs from the saved `channel`. */ + trackMismatch?: { readonly buildChannel: DesktopUpdateChannel }; } export interface DesktopUpdateReleaseNote { @@ -336,6 +338,7 @@ export const DesktopUpdateStateSchema = Schema.Struct({ canRetry: Schema.Boolean, notAppliedVersion: Schema.optionalKey(Schema.String), channelBlockedByPolicy: Schema.optionalKey(Schema.Literal(true)), + trackMismatch: Schema.optionalKey(Schema.Struct({ buildChannel: DesktopUpdateChannelSchema })), }); export const DesktopCliCommandStateSchema = Schema.Struct({ diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index f074b8f6a3e46..afd870ef97cc7 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -1070,6 +1070,13 @@ export class ServerSelfUpdateError extends Schema.TaggedError Date: Sat, 21 Nov 2026 01:56:50 +0530 Subject: [PATCH 7/7] fix(desktop): a phone can watch an agent's hidden browser tab while Windows is locked (#39198) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/preview/Manager.test.ts | 24 +++++++++++++++++++++--- apps/desktop/src/preview/Manager.ts | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 2091ff3c7f8f2..2a01977302594 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -2415,10 +2415,18 @@ describe("PreviewManager", () => { Effect.gen(function* () { const host = yield* DesktopBrowserHost.DesktopBrowserHost; const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; + const windowThrottling = vi.fn<(enabled: boolean) => void>(); + const mainWebContents = Object.assign(makeTestHostWebContents(), { + setBackgroundThrottling: windowThrottling, + }); const contents = Object.assign( - makeTestPreviewWebContents(async () => { - throw new Error("unused"); - }, 42), + makeTestPreviewWebContents( + async () => { + throw new Error("unused"); + }, + 42, + mainWebContents, + ), { isDevToolsOpened: () => false, getUserAgent: () => "Electron", @@ -2431,6 +2439,11 @@ describe("PreviewManager", () => { ) as unknown as typeof contents.debugger.sendCommand; fromId.mockReturnValue(contents); const manager = yield* PreviewManager.PreviewManager; + yield* manager.setMainWindow({ + isDestroyed: () => false, + once: vi.fn(), + webContents: mainWebContents, + } as never); const capturing = yield* Queue.unbounded(); yield* manager.subscribeStateChanges((_tabId, state) => Queue.offer(capturing, state.capturing).pipe(Effect.asVoid), @@ -2463,9 +2476,14 @@ describe("PreviewManager", () => { }), ); expect(yield* Queue.take(capturing)).toBe(true); + // A locked or covered window paints a guest it had hidden only while unthrottled. + expect(windowThrottling.mock.calls).toEqual([[false]]); + expect(contents.setBackgroundThrottling.mock.calls).toEqual([[false]]); yield* manager.setCaptureDrawn("tab_1", true); screenshot.resolve({ data: "" }); expect(yield* Queue.take(capturing)).toBe(false); + expect(windowThrottling.mock.calls).toEqual([[false], [true]]); + expect(contents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); }).pipe(Effect.provide(managerLayer())), ); diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 1f28826bcc196..fbf70e12fd375 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -3623,6 +3623,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function { discard: true }, ); }); + // A hidden or locked window draws no frames, so a guest it hid stays unpainted until unthrottled. + const serverCaptureLeases = new Map(); const updateServerTabCapturing = Effect.fn("PreviewManager.updateServerTabCapturing")( function* (painting: { readonly key: { readonly threadId: string; readonly tabId: string }; @@ -3633,6 +3635,25 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function candidate.serverTab?.threadId === painting.key.threadId && candidate.serverTab.tabId === painting.key.tabId, ); + const key = `${painting.key.threadId}\u0000${painting.key.tabId}`; + const held = serverCaptureLeases.get(key); + if (!painting.active && held) { + serverCaptureLeases.delete(key); + yield* stopFrameCapture(held.tabId, held.lease); + } else if (painting.active && !held && tab) { + const lease = Symbol("server-capture"); + yield* startFrameCapture(tab.tabId, lease).pipe( + Effect.andThen( + Effect.sync(() => serverCaptureLeases.set(key, { tabId: tab.tabId, lease })), + ), + Effect.catch((error) => + Effect.logWarning("Failed to unthrottle a server tab for its capture.", { + tabId: tab.tabId, + error, + }), + ), + ); + } if (tab && tab.capturing !== painting.active) { yield* update(tab.tabId, { capturing: painting.active }); }