From 994186e4c5e0ec5a3505bc3842b06c8ebf1b7246 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:19:04 -0800 Subject: [PATCH 01/17] feat(server): read a linked environment's thread for a client over the link Co-Authored-By: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.test.ts | 53 +++++ .../src/observability/RpcInstrumentation.ts | 1 + apps/server/src/peer/PeerForwarding.test.ts | 206 +++++++++++++++++- apps/server/src/peer/PeerThreadReader.ts | 150 +++++++++++++ apps/server/src/server.ts | 5 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 8 + .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/peerLink.ts | 66 +++++- packages/contracts/src/rpc.ts | 11 + 10 files changed, 498 insertions(+), 6 deletions(-) create mode 100644 apps/server/src/peer/PeerThreadReader.ts diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 1d38610692965..624e353712cb8 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -6,6 +6,7 @@ import { AuthSettingsWriteScope, AuthAccessWriteScope, DEFAULT_SERVER_SETTINGS, + EnvironmentId, ProviderDriverKind, ProviderInstanceId, ProjectId, @@ -201,6 +202,58 @@ it.effect("allows issue reads but requires a source-control grant before comment }).pipe(Effect.scoped), ); +it.effect("reads a linked environment's thread only for a client that may read threads here", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.peerLinksReadThread + > => tag !== WS_METHODS.peerLinksReadThread, + ), + ); + const read: string[] = []; + const handlers = group.toLayerHandler(WS_METHODS.peerLinksReadThread, ({ threadId }) => + Effect.sync(() => { + read.push(threadId); + return { + label: "Box", + thread: { threadId, title: "There", status: "idle" as const, model: "gpt-5" }, + items: [], + earlierPosition: null, + hasMore: false, + }; + }), + ); + const input = { + environmentId: EnvironmentId.make("environment-box"), + threadId: ThreadId.make("thread:box"), + }; + // Managing links and writing settings here say nothing about reading threads. + const outsider = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.merge( + handlers, + RpcAuthorization.layer([AuthAccessWriteScope, AuthSettingsWriteScope]), + ), + ), + ); + expect(yield* outsider[WS_METHODS.peerLinksReadThread](input).pipe(Effect.flip)).toMatchObject({ + _tag: "EnvironmentAuthorizationError", + requiredPermission: AuthOrchestrationReadScope, + }); + expect(read).toEqual([]); + + const reader = yield* RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))), + ); + expect((yield* reader[WS_METHODS.peerLinksReadThread](input)).label).toBe("Box"); + expect(read).toEqual([input.threadId]); + }).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/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a2b698657afcb..40405c2fb2a09 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -69,6 +69,7 @@ const RPC_AGGREGATES = { [WS_METHODS.peerLinksLink]: "peerLinks", [WS_METHODS.peerLinksUnlink]: "peerLinks", [WS_METHODS.peerLinksAnswerRequest]: "peerLinks", + [WS_METHODS.peerLinksReadThread]: "peerLinks", [WS_METHODS.serverGetSettings]: "server", [WS_METHODS.serverUpdateSettings]: "server", [WS_METHODS.serverSearchAcpRegistry]: "server", diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index a70c0d25792b8..3c4bf71c4fdb3 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -4,6 +4,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { EnvironmentId, + MessageId, + OrchestratorMcpThreadSendResult, type OrchestrationV2Run, type OrchestrationV2ThreadShell, type SourceControlCloneRepositoryInput, @@ -11,9 +13,11 @@ import { ProviderInstanceId, RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; 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"; @@ -43,6 +47,8 @@ import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts"; import * as PeerForwarding from "./PeerForwarding.ts"; import * as PeerLinks from "./PeerLinks.ts"; import * as PeerLinkRequests from "./PeerLinkRequests.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; +import * as PeerThreadReader from "./PeerThreadReader.ts"; import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts"; const laptop = descriptorOf("environment-laptop", "Laptop"); @@ -73,6 +79,53 @@ const nothingSeen: Seen = { /** The box user's own thread, which no link started. */ const usersThread = ThreadId.make("thread:box-users-own"); +/** A long idle thread of the box user's, whose transcript a client reads over the link. */ +const transcriptThread = ThreadId.make("thread:box-transcript"); +const TRANSCRIPT_ITEMS = 120; +/** Enough text that a page fills its byte budget well before its item limit. */ +const transcriptText = (position: number) => `reply ${position} ${"x".repeat(2_000)}`; + +const transcriptPage: ThreadManagement.ThreadManagementService["Service"]["getTimelinePage"] = ( + threadId, + options, +) => { + const matching = Array.from({ length: TRANSCRIPT_ITEMS }, (_, position) => position).filter( + (position) => + position > (options.afterPosition ?? -1) && + position < (options.beforePosition ?? Number.POSITIVE_INFINITY), + ); + const page = + options.beforePosition === undefined + ? matching.slice(0, options.limit) + : matching.slice(-options.limit); + return Effect.succeed({ + items: page.map((position) => { + const id = TurnItemId.make(`item:${position}`); + return { + position, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: id, + item: { + id, + threadId, + runId: boxRun, + status: "completed" as const, + title: null, + updatedAt: DateTime.makeUnsafe(0), + type: "assistant_message" as const, + messageId: MessageId.make(`message:${position}`), + text: transcriptText(position), + streaming: false, + } as never, + }; + }), + totalItems: TRANSCRIPT_ITEMS, + hasMore: page.length > 0 && page.at(-1)! < matching.at(-1)!, + hasEarlier: page.length > 0 && page[0]! > matching[0]!, + }); +}; + /** * B's threads: one `auto` thread in `boxProject` that the laptop's link * started, whose run finishes on the third wait, and the box user's own. @@ -86,14 +139,34 @@ const boxThreads = (seen: Ref.Ref, linkSession: Ref.Ref) => { const users = { ...liveThreadShell(usersThread, { runtimeMode: "auto" }), projectId: boxProject }; const run = (status: OrchestrationV2Run["status"]) => ({ id: boxRun, status }) as unknown as OrchestrationV2Run; + const transcript = { + ...liveThreadShell(transcriptThread, { runtimeMode: "auto", activeRunId: null }), + projectId: boxProject, + title: "Long transcript", + status: "idle" as const, + }; const shellOf = (threadId: ThreadId): Effect.Effect => - threadId === boxThread ? linked : Effect.succeed(threadId === usersThread ? users : null); + threadId === boxThread + ? linked + : Effect.succeed( + threadId === usersThread ? users : threadId === transcriptThread ? transcript : null, + ); const projectionOf = (threadId: ThreadId) => shellOf(threadId).pipe( - Effect.map((thread) => ({ thread, runs: [run("running")], runtimeRequests: [] }) as never), + Effect.map( + (thread) => + ({ + thread, + runs: threadId === transcriptThread ? [] : [run("running")], + runtimeRequests: [], + providerTurns: [], + }) as never, + ), ); return Layer.mock(ThreadManagement.ThreadManagementService)({ getThreadShell: shellOf, + getTimelinePage: transcriptPage, + getRunCount: () => Effect.succeed(0), getProjectThreadRecords: (input) => projectionOf(input.threadId), getThreadRecords: (threadId) => projectionOf(threadId), listProjectThreads: () => linked.pipe(Effect.map((shell) => [shell] as never)), @@ -369,7 +442,18 @@ const makeLaptop = Effect.gen(function* () { ), Effect.provideService(McpSchema.McpServerClient, mcpClient), ); - return { links: Context.get(linking, PeerLinks.PeerLinks), call }; + const reader = yield* PeerThreadReader.layer.pipe( + Layer.provide(Layer.succeedContext(linking)), + Layer.build, + ); + return { + links: Context.get(linking, PeerLinks.PeerLinks), + settings: Context.get(linking, ServerSettings.ServerSettingsService), + peers: Context.get(linking, PeerMcpClient.PeerMcpClient), + /** What a client connected to the laptop reads the box's threads through. */ + reader: Context.get(reader, PeerThreadReader.PeerThreadReader), + call, + }; }); const failureOf = (result: McpSchema.CallToolResult) => { @@ -744,3 +828,119 @@ it.effect("refuses a launch there above the link's access, naming the link", () }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + +it.effect("reads a linked environment's thread for a client in bounded pages, and only reads", () => + Effect.scoped( + Effect.gen(function* () { + const seen = yield* Ref.make(nothingSeen); + const linkSession = yield* Ref.make(""); + const b = yield* serveBox(seen, linkSession); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "full-access"); + yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId); + const read = (cursor: { beforePosition?: number; afterPosition?: number } = {}) => + a.reader.read({ environmentId: box.environmentId, threadId: transcriptThread, ...cursor }); + + // No cursor reads the end of the thread, not its start. + const newest = yield* read(); + expect(newest).toMatchObject({ + label: "Box", + thread: { threadId: transcriptThread, title: "Long transcript", status: "idle" }, + hasMore: false, + }); + expect(newest.items.at(-1)).toMatchObject({ + position: TRANSCRIPT_ITEMS - 1, + type: "assistant_message", + text: transcriptText(TRANSCRIPT_ITEMS - 1), + }); + + // Walking back visits every item once, each page within the item and byte bounds. + const pages = [newest]; + while (pages[0]!.earlierPosition !== null) { + pages.unshift(yield* read({ beforePosition: pages[0]!.earlierPosition })); + } + expect(pages.flatMap((page) => page.items.map((item) => item.position))).toEqual( + Array.from({ length: TRANSCRIPT_ITEMS }, (_, position) => position), + ); + expect(pages.length).toBeGreaterThan(TRANSCRIPT_ITEMS / 50); + for (const page of pages) { + expect(page.items.length).toBeGreaterThan(0); + expect(page.items.length).toBeLessThanOrEqual(50); + expect(Buffer.byteLength(JSON.stringify(page), "utf8")).toBeLessThanOrEqual(30_000); + } + + // A refresh reads only what follows the cursor. + const refreshed = yield* read({ afterPosition: TRANSCRIPT_ITEMS - 3 }); + expect(refreshed.items.map((item) => item.position)).toEqual([ + TRANSCRIPT_ITEMS - 2, + TRANSCRIPT_ITEMS - 1, + ]); + expect((yield* read({ afterPosition: TRANSCRIPT_ITEMS - 1 })).items).toEqual([]); + + // The link has full access, yet the modes a client's read carries let nothing be written. + const written = yield* a.peers + .call({ + environmentId: box.environmentId, + tool: "t3_thread_send", + arguments: { threadId: boxThread, message: "Carry on there." }, + limits: PeerThreadReader.CLIENT_READ_LIMITS, + success: OrchestratorMcpThreadSendResult, + }) + .pipe(Effect.flip); + expect(written.code).toBe("runtime_mode_escalation_denied"); + expect((yield* Ref.get(seen)).sends).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("tells a client why a linked environment's thread cannot be read", () => + Effect.scoped( + Effect.gen(function* () { + const seen = yield* Ref.make(nothingSeen); + const linkSession = yield* Ref.make(""); + const b = yield* serveBox(seen, linkSession); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "auto"); + const session = (yield* b.linkedSessions)[0]!.sessionId; + yield* Ref.set(linkSession, session); + const reasonOf = (environmentId: EnvironmentId, threadId: ThreadId) => + a.reader.read({ environmentId, threadId }).pipe( + Effect.flip, + Effect.map(({ reason, label }) => ({ reason, label })), + ); + + expect(yield* reasonOf(box.environmentId, ThreadId.make("thread:box-gone"))).toEqual({ + reason: "thread_not_found", + label: "Box", + }); + + yield* Ref.set(b.bearers, []); + expect( + yield* reasonOf(EnvironmentId.make("environment-elsewhere"), transcriptThread), + ).toEqual({ reason: "unknown_link", label: null }); + + yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false }); + expect(yield* reasonOf(box.environmentId, transcriptThread)).toEqual({ + reason: "disabled", + label: null, + }); + yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: true }); + // Neither refusal asked the box anything. + expect(yield* Ref.get(b.bearers)).toEqual([]); + + yield* b.auth.revokeSession(session); + expect(yield* reasonOf(box.environmentId, transcriptThread)).toEqual({ + reason: "rejected", + label: "Box", + }); + + yield* Ref.set(b.bearers, []); + yield* TestClock.adjust(Duration.days(31)); + expect(yield* reasonOf(box.environmentId, transcriptThread)).toEqual({ + reason: "expired", + label: "Box", + }); + expect(yield* Ref.get(b.bearers)).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/peer/PeerThreadReader.ts b/apps/server/src/peer/PeerThreadReader.ts new file mode 100644 index 0000000000000..07ca86f0237da --- /dev/null +++ b/apps/server/src/peer/PeerThreadReader.ts @@ -0,0 +1,150 @@ +import { + type OrchestratorMcpFailure, + OrchestratorMcpThreadReadResult, + type PeerLinkThreadPage, + PeerLinkThreadReadError, + type PeerLinkThreadReadInput, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; + +/** + * A client has no agent modes to pass on, so its read carries the narrowest ones. The linked + * environment holds every call to those, and this service only ever calls its read tool. + */ +export const CLIENT_READ_LIMITS: PeerMcpClient.PeerCallLimits = { + runtimeMode: "approval-required", + interactionMode: "plan", +}; + +const PAGE_ITEMS = 50; +const ITEM_MAX_CHARS = 20_000; +/** A linked caller's cursorless read starts at the thread's first item, so the newest page asks from the end. */ +const NEWEST = Number.MAX_SAFE_INTEGER; + +/** + * Reads a linked environment's threads for a client of this environment, over the link this + * environment already holds. `PeerForwarding` is the agent's path; a client has no thread or + * modes of its own, so this one checks only the link and reads. + */ +export class PeerThreadReader extends Context.Service< + PeerThreadReader, + { + /** One bounded page of the thread's transcript, with the thread's current status. */ + readonly read: ( + input: PeerLinkThreadReadInput, + ) => Effect.Effect; + } +>()("t3/peer/PeerThreadReader") {} + +const reasonOf = (failure: OrchestratorMcpFailure): PeerLinkThreadReadError["reason"] => + failure.code === "thread_not_found" + ? "thread_not_found" + : failure.code === "capability_denied" || failure.code === "invalid_request" + ? "rejected" + : "unreachable"; + +const make = Effect.gen(function* () { + const links = yield* PeerLinks.PeerLinks; + const peers = yield* PeerMcpClient.PeerMcpClient; + + const read: PeerThreadReader["Service"]["read"] = Effect.fn("PeerThreadReader.read")( + function* (input) { + if (!(yield* links.enabled)) { + return yield* new PeerLinkThreadReadError({ + reason: "disabled", + label: null, + message: PeerLinks.LINKED_ENVIRONMENTS_OFF, + }); + } + const link = yield* links.get(input.environmentId).pipe( + Effect.mapError( + (error) => + new PeerLinkThreadReadError({ + reason: "unreachable", + label: null, + message: error.message, + }), + ), + ); + if (Option.isNone(link)) { + return yield* new PeerLinkThreadReadError({ + reason: "unknown_link", + label: null, + message: "This environment is no longer linked to the one this thread is on.", + }); + } + const { label, expiresAt } = link.value; + if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) { + return yield* new PeerLinkThreadReadError({ + reason: "expired", + label, + message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`, + }); + } + const backwards = input.afterPosition === undefined; + const page = yield* peers + .call({ + environmentId: input.environmentId, + tool: "t3_thread_read", + arguments: { + threadId: input.threadId, + view: "activity", + limit: PAGE_ITEMS, + maxCharsPerItem: ITEM_MAX_CHARS, + runLimit: 1, + ...(backwards + ? { beforePosition: input.beforePosition ?? NEWEST } + : { + afterPosition: input.afterPosition, + ...(input.beforePosition === undefined + ? {} + : { beforePosition: input.beforePosition }), + }), + }, + limits: CLIENT_READ_LIMITS, + success: OrchestratorMcpThreadReadResult, + }) + .pipe( + Effect.mapError( + (failure) => + new PeerLinkThreadReadError({ + reason: reasonOf(failure), + label, + message: failure.message, + }), + ), + ); + // A version that only reads forward ignores `beforePosition` and answers from the start. + if (backwards && page.earlierPosition === undefined) { + return yield* new PeerLinkThreadReadError({ + reason: "incompatible", + label, + message: `${label} runs a T3 Code version that cannot page a thread from its end. Update it to read its threads from here.`, + }); + } + return { + label, + thread: { + threadId: page.thread.threadId, + title: page.thread.title, + status: page.thread.status, + model: page.thread.model, + }, + items: page.items, + earlierPosition: page.earlierPosition ?? null, + hasMore: page.hasMore, + }; + }, + ); + + return PeerThreadReader.of({ read }); +}); + +export const layer = Layer.effect(PeerThreadReader, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ab3bbeb1d186a..f98995eeb91a6 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -94,6 +94,7 @@ import * as RemoteDelegation from "./peer/RemoteDelegation.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PeerMcpClient from "./peer/PeerMcpClient.ts"; +import * as PeerThreadReader from "./peer/PeerThreadReader.ts"; import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as DeviceService from "./device/DeviceService.ts"; @@ -890,9 +891,9 @@ const layerMakeRoutes = Layer.mergeAll( ), ), Layer.provide(PreviewBrowser.layer), - // Links to other environments, shared by Settings (WebSocket) and agents (/mcp). + // Links to other environments, shared by clients (WebSocket) and agents (/mcp). Layer.provide( - PeerForwarding.layer.pipe( + Layer.merge(PeerForwarding.layer, PeerThreadReader.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 26456c0da320d..17d95b1b0c8c4 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -99,6 +99,7 @@ import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as RpcAuthorization from "./auth/RpcAuthorization.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; +import * as PeerThreadReader from "./peer/PeerThreadReader.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as PreviewManager from "./preview/Manager.ts"; @@ -845,6 +846,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(PairingGrantStore.PairingGrantStore)({}), Layer.mock(PeerLinks.PeerLinks)({}), Layer.mock(PeerLinkRequests.PeerLinkRequests)({}), + Layer.mock(PeerThreadReader.PeerThreadReader)({}), 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 9408127f5a2b3..f0e76e7a5b5f8 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -8,6 +8,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; +import * as PeerThreadReader from "./peer/PeerThreadReader.ts"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; @@ -1558,6 +1559,7 @@ export const layerWsRpc = ( const secretResolver = yield* SecretResolver.SecretResolver; const peerLinks = yield* PeerLinks.PeerLinks; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; + const peerThreadReader = yield* PeerThreadReader.PeerThreadReader; const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; @@ -2704,6 +2706,10 @@ export const layerWsRpc = ( [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), + [WS_METHODS.peerLinksReadThread]: (input) => + Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( + Effect.andThen(peerThreadReader.read(input)), + ), [WS_METHODS.peerLinksAnswerRequest]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(peerLinkRequests.answer(input)), @@ -3615,6 +3621,7 @@ export const layer = Layer.unwrap( const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const peerLinks = yield* PeerLinks.PeerLinks; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; + const peerThreadReader = yield* PeerThreadReader.PeerThreadReader; const sql = yield* SqlClient.SqlClient; return HttpRouter.add( "GET", @@ -3715,6 +3722,7 @@ export const layer = Layer.unwrap( ), Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)), Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)), + Layer.provide(Layer.succeed(PeerThreadReader.PeerThreadReader, peerThreadReader)), Layer.provide( SourceControlDiscovery.layer.pipe( Layer.provide( diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 0b6164871a0ad..2bdaaba5bb2e5 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -86,6 +86,8 @@ 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, + // Reads a linked environment's thread as this one's own are read. + [WS_METHODS.peerLinksReadThread]: AuthOrchestrationReadScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index f8cf83c1fdbdd..949f57bc8c392 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -1,7 +1,17 @@ import * as Schema from "effect/Schema"; import { AuthMcpClientAccess } from "./auth.ts"; -import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts"; +import { + EnvironmentId, + NonNegativeInt, + ThreadId, + TrimmedNonEmptyString, + TurnItemId, +} from "./baseSchemas.ts"; +import { + OrchestratorMcpThreadStatus, + OrchestratorMcpThreadTimelineItem, +} from "./orchestratorMcp.ts"; /** * A link from this environment to another one (the peer). This environment @@ -73,6 +83,60 @@ export class PeerLinkError extends Schema.TaggedError()("PeerLink cause: Schema.optionalKey(Schema.Defect()), }) {} +/** + * A page of a linked environment's thread, read for a client of this environment over the link. + * No cursor reads the newest page; `beforePosition` pages back and `afterPosition` reads what + * came after, which is also how an open view refreshes. + */ +export const PeerLinkThreadReadInput = Schema.Struct({ + /** The linked environment the thread lives in. */ + environmentId: EnvironmentId, + threadId: ThreadId, + beforePosition: Schema.optionalKey(NonNegativeInt), + afterPosition: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(-1))), +}); +export type PeerLinkThreadReadInput = typeof PeerLinkThreadReadInput.Type; + +export const PeerLinkThreadPage = Schema.Struct({ + /** What this environment calls the linked one. */ + label: Schema.String, + thread: Schema.Struct({ + threadId: ThreadId, + title: Schema.String, + status: OrchestratorMcpThreadStatus, + model: Schema.String, + }), + /** Oldest first. Each page is bounded in items and in bytes. */ + items: Schema.Array(OrchestratorMcpThreadTimelineItem), + /** Pass as `beforePosition` for the page before this one; null at the thread's start. */ + earlierPosition: Schema.NullOr(NonNegativeInt), + /** More items follow this page already, so the next read need not wait. */ + hasMore: Schema.Boolean, +}); +export type PeerLinkThreadPage = typeof PeerLinkThreadPage.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 cannot page a thread backwards. */ + "incompatible", + ]), + /** What this environment calls the linked one, when it still has the link. */ + label: Schema.NullOr(Schema.String), + message: Schema.String, + }, +) {} + /** * 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..fc9e13982456a 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -25,6 +25,9 @@ import { PeerLinkRequestAnswerInput, PeerLinkRequestError, PeerLinkSummary, + PeerLinkThreadPage, + PeerLinkThreadReadError, + PeerLinkThreadReadInput, } from "./peerLink.ts"; import { ChatGptReconnectProfileInput, @@ -549,6 +552,7 @@ export const WS_METHODS = { peerLinksLink: "peerLinks.link", peerLinksUnlink: "peerLinks.unlink", peerLinksAnswerRequest: "peerLinks.answerRequest", + peerLinksReadThread: "peerLinks.readThread", serverGetSettings: "server.getSettings", serverUpdateSettings: "server.updateSettings", serverDiscoverSourceControl: "server.discoverSourceControl", @@ -902,6 +906,12 @@ const WsPeerLinksUnlinkRpc = Rpc.make(WS_METHODS.peerLinksUnlink, { error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), }); +const WsPeerLinksReadThreadRpc = Rpc.make(WS_METHODS.peerLinksReadThread, { + payload: PeerLinkThreadReadInput, + success: PeerLinkThreadPage, + error: Schema.Union([PeerLinkThreadReadError, EnvironmentAuthorizationError]), +}); + const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, { payload: PeerLinkRequestAnswerInput, error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]), @@ -2305,6 +2315,7 @@ export const WsRpcGroup = RpcGroup.make( WsPeerLinksLinkRpc, WsPeerLinksUnlinkRpc, WsPeerLinksAnswerRequestRpc, + WsPeerLinksReadThreadRpc, WsServerDiscoverSourceControlRpc, WsServerCheckSecretSourceRpc, WsServerSearchAcpRegistryRpc, From 53b676e8285c01f6f80ab9f98f7f655475325b08 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:40:32 -0800 Subject: [PATCH 02/17] feat: read a linked environment's threads from the client A remote subagent row or a thread link to a linked machine opens a read-only transcript, read by the connected environment over its link. Web and mobile share the paging and polling session; it reads only while the view is open. Co-Authored-By: Claude Fable 5.2 --- apps/mobile/src/Stack.tsx | 5 + .../features/threads/LinkedThreadSheet.tsx | 248 ++++++++++++ .../features/threads/ThreadAgentsSheet.tsx | 38 +- .../threads/thread-subagent-group.tsx | 29 +- .../threads/threadAgentsPresentation.ts | 31 +- apps/mobile/src/i18n/translations/de.json | 41 +- apps/mobile/src/i18n/translations/en.json | 41 +- apps/mobile/src/i18n/translations/es.json | 41 +- apps/mobile/src/i18n/translations/fr.json | 41 +- apps/mobile/src/i18n/translations/ja.json | 41 +- apps/mobile/src/i18n/translations/ko.json | 41 +- apps/mobile/src/i18n/translations/pt-BR.json | 41 +- apps/mobile/src/i18n/translations/ru.json | 41 +- apps/mobile/src/i18n/translations/sv.json | 41 +- apps/mobile/src/i18n/translations/zh.json | 41 +- apps/mobile/src/state/linkedThread.ts | 41 ++ .../src/components/chat/LinkedThreadSheet.tsx | 183 +++++++++ .../chat/MarkdownThreadLink.browser.test.tsx | 31 ++ .../components/chat/MarkdownThreadLink.tsx | 44 ++ ...hreadRelationshipsControl.browser.test.tsx | 6 +- .../chat/ThreadRelationshipsControl.tsx | 33 +- .../src/components/chat/V2LifecycleRow.tsx | 19 +- apps/web/src/i18n/translations/de.json | 81 +++- apps/web/src/i18n/translations/en.json | 83 +++- apps/web/src/i18n/translations/es.json | 83 +++- apps/web/src/i18n/translations/fr.json | 83 +++- apps/web/src/i18n/translations/ja.json | 84 +++- apps/web/src/i18n/translations/ko.json | 82 +++- apps/web/src/i18n/translations/pt-BR.json | 81 +++- apps/web/src/i18n/translations/ru.json | 81 +++- apps/web/src/i18n/translations/sv.json | 83 +++- apps/web/src/i18n/translations/zh.json | 83 +++- apps/web/src/routes/__root.tsx | 2 + apps/web/src/state/linkedThreadView.ts | 100 +++++ docs/user/remote-access.md | 15 + packages/client-runtime/package.json | 4 + .../client-runtime/src/linkedThread.test.ts | 353 ++++++++++++++++ packages/client-runtime/src/linkedThread.ts | 381 ++++++++++++++++++ .../src/state/commandPermissions.test.ts | 31 ++ .../client-runtime/src/state/peerLinks.ts | 5 + 40 files changed, 2507 insertions(+), 326 deletions(-) create mode 100644 apps/mobile/src/features/threads/LinkedThreadSheet.tsx create mode 100644 apps/mobile/src/state/linkedThread.ts create mode 100644 apps/web/src/components/chat/LinkedThreadSheet.tsx 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 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/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx new file mode 100644 index 0000000000000..e772a1c3e4c50 --- /dev/null +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -0,0 +1,248 @@ +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { + isLinkedThreadWorking, + linkedThreadFailure, + type LinkedThreadFailure, + type LinkedThreadItemPresentation, + type LinkedThreadTarget, + presentLinkedThreadItem, +} from "@t3tools/client-runtime/linked-thread"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { T, useGT, useMessages } from "gt-react-native"; +import { useRef, useState } from "react"; +import type * as React from "react"; +import { 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 { useLinkedThreadSession } from "../../state/linkedThread"; +import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; + +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 TruncatedNote() { + return ( + + Long text, cut short here. + + ); +} + +function ActivityRow(props: { + readonly item: Extract; +}) { + const { item } = props; + const [open, setOpen] = useState(false); + const summary = ( + + {item.summary} + + ); + if (item.body === null) return summary; + return ( + setOpen(!open)} + className="active:opacity-70" + > + {summary} + {open ? ( + + + {item.body} + + {item.truncated ? : null} + + ) : null} + + ); +} + +function LinkedThreadItem(props: { readonly item: LinkedThreadItemPresentation }) { + const { item } = props; + const styles = useMarkdownPreviewStyles(); + if (item.kind === "activity") return ; + return item.kind === "user" ? ( + + + {item.text} + + {item.truncated ? : null} + + ) : ( + + + {item.truncated ? : null} + + ); +} + +function FailureCard(props: { + readonly failure: LinkedThreadFailure; + readonly stale: boolean; + readonly onRetry: () => void; +}) { + const gt = useGT(); + return ( + + {props.failure.title} + + {props.failure.detail} + {props.stale ? ` ${gt("Showing what was read before.")}` : ""} + + {props.failure.retryable ? ( + + + + ) : null; + return ( + <> + + + {transcript?.thread.title || target.title || gt("Thread on {label}", { label })} + + + + + + Read-only · on {label} via {via} + + {transcript !== null && isLinkedThreadWorking(transcript) ? ( + + · Working + + ) : null} + + + {/* A "Connect to interact" action belongs here once this client can pair with the linked environment. */} + + {/* Reversed, so the view opens at the newest item and stays there as items arrive. */} +
+
+ {transcript === null ? ( + failure === null ? ( +
+ + + Reading from {label}… + +
+ ) : ( + + {failure.title} + {failure.detail} + {retry} + + ) + ) : ( + <> + {transcript.earlierPosition !== null ? ( + + ) : null} + {transcript.items.length === 0 ? ( +

+ Nothing in this thread yet. +

+ ) : null} + {transcript.items.map((item) => { + const presented = presentLinkedThreadItem(item, m); + return presented === null ? null : ( + + ); + })} + {failure === null ? null : ( + + {failure.title} + + {failure.detail} Showing what was read before. + + {retry} + + )} + + )} +
+
+ + ); +} + +/** + * A linked environment's thread, read through the environment this client is connected to. The + * client never connects to the linked one, so the view only reads. + */ +export function LinkedThreadSheet() { + const [target, setTarget] = useAtom(linkedThreadViewAtom); + return ( + { + if (!open) setTarget(null); + }} + > + + {target === null ? null : ( + + )} + + + ); +} diff --git a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx index 6febe0ff8b343..adda7cca95068 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx @@ -10,6 +10,8 @@ import { MarkdownThreadLink } from "./MarkdownThreadLink"; const state = vi.hoisted(() => ({ reply: null as unknown, remote: null as unknown, + linked: new Map(), + openedLinked: [] as Array, })); vi.mock(import("../../state/entities"), () => ({ useThreadShell: ((ref: { environmentId: string } | null) => @@ -27,6 +29,15 @@ vi.mock(import("../../state/environments"), () => ({ { environmentId: EnvironmentId.make("remote"), label: "Remote" }, ], })); +vi.mock(import("../../state/peerLinks"), () => ({ + useLinkedEnvironments: ((environmentId: string | null) => + environmentId === null ? new Map() : state.linked) as never, +})); +vi.mock(import("../../state/linkedThreadView"), () => ({ + useOpenLinkedThread: () => (target) => { + state.openedLinked.push(target); + }, +})); vi.mock(import("../ProjectFavicon"), () => ({ ProjectFavicon: () => ( @@ -46,6 +57,8 @@ function setup() { AsyncResult.AsyncResult, string> >(AsyncResult.initial()); state.reply = reply; + state.linked = new Map(); + state.openedLinked = []; state.remote = { environmentId: EnvironmentId.make("remote"), id: ThreadId.make("older-thread"), @@ -156,3 +169,21 @@ 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("opens a thread on a machine only this environment links to as a read through it", async () => { + const { registry } = setup(); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + state.linked = new Map([["linked-vm", "fs-17"]]); + const environmentId = EnvironmentId.make("environment"); + const link = { environmentId: EnvironmentId.make("linked-vm"), threadId: ThreadId.make("there") }; + await using screen = await render( + + + , + ); + await screen.getByRole("button", { name: "Thread, Thread on fs-17" }).click(); + expect(state.openedLinked).toEqual([ + { viaEnvironmentId: environmentId, ...link, label: "fs-17", title: null }, + ]); + expect(screen.router?.state.location.pathname).toBe("/"); +}); diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 1a0df30fe0518..917d36f7bddd1 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 { useGT, useMessages } from "gt-react"; +import { MessagesSquareIcon } from "lucide-react"; import { formatHostedThreadLink, guessThreadLinkRef, @@ -11,10 +12,14 @@ import { unknownThreadLinkLabel } from "@t3tools/shared/threadLinksCopy"; import { configuredHostedAppUrl } from "../../hostedPairing"; import { useThreadRefs, useThreadShell } from "../../state/entities"; import { useEnvironmentIdentities } from "../../state/environments"; +import { useOpenLinkedThread } from "../../state/linkedThreadView"; +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: { @@ -58,6 +63,45 @@ export function MarkdownThreadLink(props: { : null; const remote = useThreadShell(remoteRef); const resolved = target ?? (remoteRef && remote ? { ref: remoteRef, metadata: remote } : null); + // A thread on a machine this client cannot reach still reads through the one that links to it. + const linkedLabel = useLinkedEnvironments(reachable ? null : props.environmentId).get( + writtenRef.environmentId, + ); + const openLinked = useOpenLinkedThread(); + if (resolved === null && linkedLabel !== undefined) { + const title = props.label ?? gt("Thread on {label}", { label: linkedLabel }); + return ( + + + openLinked({ + viaEnvironmentId: props.environmentId, + ...writtenRef, + label: linkedLabel, + title: props.label, + }) + } + /> + } + 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/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 1a0fb5bd406f8..2d8e67ed294ed 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -45,6 +45,9 @@ vi.mock(import("../../state/environments"), () => ({ useEnvironment: (() => null) as never, useEnvironmentProviders: (() => new Map()) as never, })); +vi.mock(import("../../state/peerLinks"), () => ({ + peerLinkEnvironment: { readThread: {} } as never, +})); vi.mock(import("../../lib/archivedThreadsState"), () => ({ useArchivedThreadSnapshots: (() => ({ snapshots: [{ environmentId: "environment", snapshot: { threads: state.archivedThreads } }], @@ -330,8 +333,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..e7fcb0c560d2a 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -62,6 +62,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 +280,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 environment whose thread delegated the task, which holds the link. */ + readonly viaEnvironmentId: EnvironmentId; 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 +299,14 @@ function RemoteSubagentRow(props: { title: props.agent.title ?? gt("Subagent"), isSubagent: true, }); + const opener = useLinkedThreadOpener(props.viaEnvironmentId, remoteChild, title); return (
  • { - if (environment === null) return; - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams( - scopeThreadRef(remoteChild.environmentId, remoteChild.threadId), - ), - }); - }} - /> + } > @@ -1086,6 +1072,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.environmentId, 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/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 22f9bcf953f2b..e65afae756622 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -82,6 +82,29 @@ "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", + "6ab96e26bda35288": "Denkt nach", + "67733c48eaaec73a": "Tarif", + "75aaf70eabf15f4b": "Dateisuche", + "ac511f991a3c1fab": "Websuche", + "5e30649065b60d94": "Genehmigungsanfrage", + "5c8772e727c04218": "Frage", + "a06eb47a82969918": "Subagent", + "646de37e0bec85f8": "Tool-Aufruf", + "885ae08a2160a158": "Kontext komprimiert", + "afc8fb892e52f932": "Fehler", "f71597ae3afaef44": "{first} und {second}", "4047174839a16714": "{first} und {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "Komprimieren des Kontexts gestoppt", "2605da0149cd15f1": "Kontext wird komprimiert", "39a82db18ca50c21": "Kontext komprimiert: {before} → {after} Tokens", - "885ae08a2160a158": "Kontext komprimiert", "3ab6b281a0991766": "{count, plural, =1 {Verknüpfte Pull Requests geprüft} other {Verknüpfte Pull Requests {count}-mal geprüft}}", "857e92a89b6b6257": "{count, plural, one {{count} Datei gelesen} other {{count} Dateien gelesen}}", "466ac7fcdb97bb76": "{count, plural, one {{count} Datei geändert} other {{count} Dateien geändert}}", @@ -1913,7 +1935,6 @@ "cf34b1bdf8179c16": "Lokal", "d85877d9ef77c50c": "Änderungen", "b816058fba61e4d6": "Runde {count}", - "646de37e0bec85f8": "Tool-Aufruf", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Letzte Runde", "e6ae3a0fbf3eb49e": "Für diese Auswahl sind keine Diff-Dateiinhalte verfügbar.", @@ -3575,6 +3596,36 @@ " verknüpft. Der Agent kann diese Verknüpfung so verwenden; ändere den Zugriff unter Einstellungen → Umgebungen." ], "000b0df227182d39": "Andere Adresse…", + "009e2ca841fdc1ef": "diese Umgebung", + "1944f04b75ddf26d": "Thread auf {label}", + "c8e6ea4d6313e912": "Langer Text, hier gekürzt.", + "59fb6d9ab29a1513": [ + "Schreibgeschützt · auf ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " über ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "Arbeitet", + "d0bda35aeec66684": [ + "Wird von ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " gelesen …" + ], + "50fb8b2ca3db6cad": "Frühere laden", + "048b8a737af895ac": "Noch nichts in diesem Thread.", + "c3e8cd9bf44e2f43": "Angezeigt wird, was zuvor gelesen wurde.", "eb6e0584cf4a2a1d": "Sprache: {language}", "d76c606a3c519b78": "Zeilenumbruch deaktivieren", "2b683498cee8c8a7": "Zeilen umbrechen", @@ -3602,6 +3653,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?", @@ -3649,9 +3701,7 @@ "9bbecec926c3b695": "Wiederholen", "4fd8927b7afc2a92": "Nachricht kopieren", "6f8651e48261911a": "Gedanke", - "ac511f991a3c1fab": "Websuche", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} weitere} other {{path} +{count} weitere}}", - "6ab96e26bda35288": "Denkt nach", "4d4981a1c5bd9728": "Befehl läuft", "a078225c5f197cd2": "Befehl fehlgeschlagen", "37ab148aaa486051": "Befehl abgelehnt", @@ -3750,7 +3800,6 @@ "afe27891aab8cf37": "{label}: Nicht bereit.", "2f77cc3105ddd7f8": "Anbieter", "3b205a1c17c06fbd": "Favoriten", - "a06eb47a82969918": "Subagent", "d567966a45ff32be": "Arbeit der Subagenten", "4740c38b2edd194d": "Nur lesen. Diese Subagenten können keine Nachrichten annehmen.", "5a0125dd9241cdec": "Wird geladen…", @@ -4024,6 +4073,15 @@ } ], "e58a1d884fa1d8f2": "Thread-Details", + "43c5fbd02c6f330a": "Weniger anzeigen", + "de45b075b016cb14": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " weitere anzeigen" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} Kommentar} other {{count} Kommentare}}", "42f634397f3960aa": "In Thread-Details anzeigen", @@ -4063,15 +4121,6 @@ ], "159ddd0d146a0f22": "Beobachtet: Der Agent wird geweckt, wenn Checks fertig sind, jemand kommentiert oder der Branch Konflikte hat. Klicke zum Beenden.", "1cbc8b5db51b4c77": "Mergen", - "43c5fbd02c6f330a": "Weniger anzeigen", - "de45b075b016cb14": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " weitere anzeigen" - ], "a3d040c4ef4fc6e9": "Über dem Tempo", "b16fdf56b16d99c9": "Im Tempo", "90f977e97ae8b6c6": "Unter dem Tempo", @@ -4086,6 +4135,7 @@ "66be4fb43249bbd2": "{used} von {max} Tokens", "ee3ae58c8b38a425": "{left} % übrig", "ebb26f93fb83a71b": "{label}: {left} % übrig", + "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "728c6cc1431e76c8": "Wird in {duration} zurückgesetzt · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Die Zwischenablage-API ist beim Kopieren der Admin-Anfrage nicht verfügbar.", @@ -4138,7 +4188,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", @@ -10932,7 +10981,6 @@ "af4c158f5758af59": "Bedienelemente der Seitenleiste", "cddde869ea4ceb29": "Auswahl in der Seitenleiste", "735a61ef214f6836": "Terminal-Hintergrund", - "afc8fb892e52f932": "Fehler", "16ad4c65b7cde1bb": "„{label}“ hat keine helle Palette. Erstelle ein Design mit demselben Namen, um eine hinzuzufügen.", "0ec05a92bf5537a2": "„{label}“ hat keine dunkle Palette. Erstelle ein Design mit demselben Namen, um eine hinzuzufügen.", "a9cfdfa41271d7d4": "„{label}“ hat bereits eine helle Palette.", @@ -11860,7 +11908,6 @@ "0bd938825ffcf992": "+{percent} % des Kontingents", "09c0e00d7fb55402": "Reset-Guthaben wird verwendet…", "4df3ff1be768a7ab": "{name}: {remaining} % übrig", - "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", "a16b48709357a5a7": "Nutzung verwalten", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 442486e2decb0..89bb2ca9eb438 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -82,6 +82,29 @@ "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}", + "6ab96e26bda35288": "Thinking", + "67733c48eaaec73a": "Plan", + "75aaf70eabf15f4b": "File search", + "ac511f991a3c1fab": "Web search", + "5e30649065b60d94": "Approval request", + "5c8772e727c04218": "Question", + "a06eb47a82969918": "Subagent", + "646de37e0bec85f8": "Tool call", + "885ae08a2160a158": "Context compacted", + "afc8fb892e52f932": "Error", "f71597ae3afaef44": "{first} and {second}", "4047174839a16714": "{first}, and {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "Context compaction stopped", "2605da0149cd15f1": "Compacting context", "39a82db18ca50c21": "Context compacted {before} → {after} tokens", - "885ae08a2160a158": "Context compacted", "3ab6b281a0991766": "{count, plural, =1 {Checked linked pull requests} other {Checked linked pull requests {count} times}}", "857e92a89b6b6257": "{count, plural, one {Read {count} file} other {Read {count} files}}", "466ac7fcdb97bb76": "{count, plural, one {Changed {count} file} other {Changed {count} files}}", @@ -1914,7 +1936,6 @@ "cf34b1bdf8179c16": "Uncommitted", "d85877d9ef77c50c": "Changes", "b816058fba61e4d6": "Turn {count}", - "646de37e0bec85f8": "Tool call", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Latest turn", "e6ae3a0fbf3eb49e": "Diff file contents are unavailable for this selection.", @@ -3574,6 +3595,36 @@ ". The agent can use that link as it is; change its access in Settings → Environments." ], "000b0df227182d39": "Another address…", + "009e2ca841fdc1ef": "this environment", + "1944f04b75ddf26d": "Thread on {label}", + "c8e6ea4d6313e912": "Long text, cut short here.", + "59fb6d9ab29a1513": [ + "Read-only · on ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " via ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "Working", + "d0bda35aeec66684": [ + "Reading from ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "Load earlier", + "048b8a737af895ac": "Nothing in this thread yet.", + "c3e8cd9bf44e2f43": "Showing what was read before.", "eb6e0584cf4a2a1d": "Language: {language}", "d76c606a3c519b78": "Disable line wrap", "2b683498cee8c8a7": "Wrap lines", @@ -3601,6 +3652,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}?", @@ -3648,9 +3700,7 @@ "9bbecec926c3b695": "Retry", "4fd8927b7afc2a92": "Copy message", "6f8651e48261911a": "Thought", - "ac511f991a3c1fab": "Web search", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} more} other {{path} +{count} more}}", - "6ab96e26bda35288": "Thinking", "4d4981a1c5bd9728": "Running command", "a078225c5f197cd2": "Failed command", "37ab148aaa486051": "Declined command", @@ -3749,7 +3799,6 @@ "afe27891aab8cf37": "{label}: Not ready.", "2f77cc3105ddd7f8": "Providers", "3b205a1c17c06fbd": "Favorites", - "a06eb47a82969918": "Subagent", "d567966a45ff32be": "Subagent work", "4740c38b2edd194d": "Read only. These subagents cannot take messages.", "5a0125dd9241cdec": "Loading…", @@ -4022,6 +4071,16 @@ } ], "e58a1d884fa1d8f2": "Thread details", + "43c5fbd02c6f330a": "Show less", + "de45b075b016cb14": [ + "Show ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " more" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comment} other {{count} comments}}", "42f634397f3960aa": "Show in thread details", @@ -4061,16 +4120,6 @@ ], "159ddd0d146a0f22": "Watching: the agent wakes when checks finish, someone comments, or the branch conflicts. Click to stop.", "1cbc8b5db51b4c77": "Merge", - "43c5fbd02c6f330a": "Show less", - "de45b075b016cb14": [ - "Show ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " more" - ], "a3d040c4ef4fc6e9": "Ahead of pace", "b16fdf56b16d99c9": "On pace", "90f977e97ae8b6c6": "Under pace", @@ -4085,6 +4134,7 @@ "66be4fb43249bbd2": "{used} of {max} tokens", "ee3ae58c8b38a425": "{left}% left", "ebb26f93fb83a71b": "{label}: {left}% left", + "1b16346722b65812": "{timeLeft}% of the window left", "728c6cc1431e76c8": "Resets in {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Clipboard API is unavailable while copying admin request.", @@ -4137,7 +4187,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", @@ -10942,7 +10991,6 @@ "af4c158f5758af59": "Sidebar controls", "cddde869ea4ceb29": "Sidebar selection", "735a61ef214f6836": "Terminal background", - "afc8fb892e52f932": "Error", "16ad4c65b7cde1bb": "“{label}” has no light palette. Create a theme with the same name to add one.", "0ec05a92bf5537a2": "“{label}” has no dark palette. Create a theme with the same name to add one.", "a9cfdfa41271d7d4": "“{label}” already has a light palette.", @@ -11868,7 +11916,6 @@ "0bd938825ffcf992": "+{percent}% of pool", "09c0e00d7fb55402": "Using reset credit…", "4df3ff1be768a7ab": "{name}: {remaining}% left", - "1b16346722b65812": "{timeLeft}% of the window left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", "a16b48709357a5a7": "Manage usage", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 87c7e9a861a93..991fae1b8e6d5 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -82,6 +82,29 @@ "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}", + "6ab96e26bda35288": "Pensando", + "67733c48eaaec73a": "Plan", + "75aaf70eabf15f4b": "Búsqueda de archivos", + "ac511f991a3c1fab": "Búsqueda web", + "5e30649065b60d94": "Solicitud de aprobación", + "5c8772e727c04218": "Pregunta", + "a06eb47a82969918": "Subagente", + "646de37e0bec85f8": "Llamada a herramienta", + "885ae08a2160a158": "Contexto compactado", + "afc8fb892e52f932": "Error", "f71597ae3afaef44": "{first} y {second}", "4047174839a16714": "{first} y {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "Se detuvo la compactación del contexto", "2605da0149cd15f1": "Compactando el contexto", "39a82db18ca50c21": "Contexto compactado de {before} → {after} tokens", - "885ae08a2160a158": "Contexto compactado", "3ab6b281a0991766": "{count, plural, =1 {Se comprobaron las pull requests vinculadas} other {Se comprobaron las pull requests vinculadas {count} veces}}", "857e92a89b6b6257": "{count, plural, one {Se leyó {count} archivo} other {Se leyeron {count} archivos}}", "466ac7fcdb97bb76": "{count, plural, one {Se cambió {count} archivo} other {Se cambiaron {count} archivos}}", @@ -1914,7 +1936,6 @@ "cf34b1bdf8179c16": "Sin commit", "d85877d9ef77c50c": "Cambios", "b816058fba61e4d6": "Turno {count}", - "646de37e0bec85f8": "Llamada a herramienta", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Último turno", "e6ae3a0fbf3eb49e": "El contenido de los archivos del diff no está disponible para esta selección.", @@ -3574,6 +3595,36 @@ ". El agente puede usar ese vínculo tal cual; cambia su acceso en Ajustes → Entornos." ], "000b0df227182d39": "Otra dirección…", + "009e2ca841fdc1ef": "este entorno", + "1944f04b75ddf26d": "Hilo en {label}", + "c8e6ea4d6313e912": "Texto largo, recortado aquí.", + "59fb6d9ab29a1513": [ + "Solo lectura · en ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " a través de ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "Trabajando", + "d0bda35aeec66684": [ + "Leyendo desde ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "Cargar anteriores", + "048b8a737af895ac": "Aún no hay nada en este hilo.", + "c3e8cd9bf44e2f43": "Se muestra lo que se leyó antes.", "eb6e0584cf4a2a1d": "Lenguaje: {language}", "d76c606a3c519b78": "Desactivar ajuste de línea", "2b683498cee8c8a7": "Ajustar líneas", @@ -3601,6 +3652,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}?", @@ -3646,9 +3698,7 @@ "9bbecec926c3b695": "Reintentar", "4fd8927b7afc2a92": "Copiar mensaje", "6f8651e48261911a": "Razonamiento", - "ac511f991a3c1fab": "Búsqueda web", "07e65dba2b16d3f7": "{count, plural, one {{path} y {count} más} other {{path} y {count} más}}", - "6ab96e26bda35288": "Pensando", "4d4981a1c5bd9728": "Ejecutando comando", "a078225c5f197cd2": "Comando fallido", "37ab148aaa486051": "Comando rechazado", @@ -3747,7 +3797,6 @@ "afe27891aab8cf37": "{label}: no está listo.", "2f77cc3105ddd7f8": "Proveedores", "3b205a1c17c06fbd": "Favoritos", - "a06eb47a82969918": "Subagente", "d567966a45ff32be": "Trabajo del subagente", "4740c38b2edd194d": "Solo lectura. Estos subagentes no pueden recibir mensajes.", "5a0125dd9241cdec": "Cargando…", @@ -4020,6 +4069,16 @@ } ], "e58a1d884fa1d8f2": "Detalles del hilo", + "43c5fbd02c6f330a": "Mostrar menos", + "de45b075b016cb14": [ + "Mostrar ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " más" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comentario} other {{count} comentarios}}", "42f634397f3960aa": "Mostrar en los detalles del hilo", @@ -4059,16 +4118,6 @@ ], "159ddd0d146a0f22": "Siguiendo: el agente se activa cuando terminan las comprobaciones, alguien comenta o la rama tiene conflictos. Haz clic para dejar de seguir.", "1cbc8b5db51b4c77": "Fusionar", - "43c5fbd02c6f330a": "Mostrar menos", - "de45b075b016cb14": [ - "Mostrar ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " más" - ], "a3d040c4ef4fc6e9": "Por encima del ritmo", "b16fdf56b16d99c9": "Al ritmo", "90f977e97ae8b6c6": "Por debajo del ritmo", @@ -4083,6 +4132,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left} % restante", "ebb26f93fb83a71b": "{label}: {left} % restante", + "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "728c6cc1431e76c8": "Se restablece en {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "La API del portapapeles no está disponible al copiar la solicitud de administrador.", @@ -4135,7 +4185,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ó", @@ -10927,7 +10976,6 @@ "af4c158f5758af59": "Controles de la barra lateral", "cddde869ea4ceb29": "Selección de la barra lateral", "735a61ef214f6836": "Fondo de la terminal", - "afc8fb892e52f932": "Error", "16ad4c65b7cde1bb": "«{label}» no tiene paleta clara. Crea un tema con el mismo nombre para añadir una.", "0ec05a92bf5537a2": "«{label}» no tiene paleta oscura. Crea un tema con el mismo nombre para añadir una.", "a9cfdfa41271d7d4": "«{label}» ya tiene una paleta clara.", @@ -11853,7 +11901,6 @@ "0bd938825ffcf992": "+{percent}% del total", "09c0e00d7fb55402": "Usando el crédito de restablecimiento…", "4df3ff1be768a7ab": "{name}: queda un {remaining}%", - "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", "a16b48709357a5a7": "Gestionar uso", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a3a16e772103e..2d19651e0f370 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -82,6 +82,29 @@ "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}", + "6ab96e26bda35288": "Réflexion", + "67733c48eaaec73a": "Forfait", + "75aaf70eabf15f4b": "Recherche de fichiers", + "ac511f991a3c1fab": "Recherche web", + "5e30649065b60d94": "Demande d’approbation", + "5c8772e727c04218": "Question", + "a06eb47a82969918": "Sous-agent", + "646de37e0bec85f8": "Appel d’outil", + "885ae08a2160a158": "Contexte compacté", + "afc8fb892e52f932": "Erreur", "f71597ae3afaef44": "{first} et {second}", "4047174839a16714": "{first} et {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "Compactage du contexte arrêté", "2605da0149cd15f1": "Compactage du contexte", "39a82db18ca50c21": "Contexte compacté de {before} → {after} tokens", - "885ae08a2160a158": "Contexte compacté", "3ab6b281a0991766": "{count, plural, =1 {Pull requests associées vérifiées} other {Pull requests associées vérifiées {count} fois}}", "857e92a89b6b6257": "{count, plural, one {{count} fichier lu} other {{count} fichiers lus}}", "466ac7fcdb97bb76": "{count, plural, one {{count} fichier modifié} other {{count} fichiers modifiés}}", @@ -1914,7 +1936,6 @@ "cf34b1bdf8179c16": "Locales", "d85877d9ef77c50c": "Modifications", "b816058fba61e4d6": "Tour {count}", - "646de37e0bec85f8": "Appel d’outil", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Dernier tour", "e6ae3a0fbf3eb49e": "Le contenu des fichiers du diff n’est pas disponible pour cette sélection.", @@ -3574,6 +3595,36 @@ ". L’agent peut utiliser cette association telle quelle ; modifiez son accès dans Paramètres → Environnements." ], "000b0df227182d39": "Autre adresse…", + "009e2ca841fdc1ef": "cet environnement", + "1944f04b75ddf26d": "Fil sur {label}", + "c8e6ea4d6313e912": "Texte long, coupé ici.", + "59fb6d9ab29a1513": [ + "Lecture seule · sur ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " via ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "En cours", + "d0bda35aeec66684": [ + "Lecture depuis ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "Charger les précédents", + "048b8a737af895ac": "Rien dans ce fil pour l’instant.", + "c3e8cd9bf44e2f43": "Affichage de ce qui a été lu auparavant.", "eb6e0584cf4a2a1d": "Langage : {language}", "d76c606a3c519b78": "Désactiver le retour à la ligne", "2b683498cee8c8a7": "Retour à la ligne", @@ -3601,6 +3652,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} ?", @@ -3647,9 +3699,7 @@ "9bbecec926c3b695": "Réessayer", "4fd8927b7afc2a92": "Copier le message", "6f8651e48261911a": "Réflexion", - "ac511f991a3c1fab": "Recherche web", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} autre} other {{path} +{count} autres}}", - "6ab96e26bda35288": "Réflexion", "4d4981a1c5bd9728": "Exécution de la commande", "a078225c5f197cd2": "Commande en échec", "37ab148aaa486051": "Commande refusée", @@ -3748,7 +3798,6 @@ "afe27891aab8cf37": "{label} : pas prêt.", "2f77cc3105ddd7f8": "Fournisseurs", "3b205a1c17c06fbd": "Favoris", - "a06eb47a82969918": "Sous-agent", "d567966a45ff32be": "Travail des sous-agents", "4740c38b2edd194d": "Lecture seule. Ces sous-agents ne peuvent pas recevoir de messages.", "5a0125dd9241cdec": "Chargement…", @@ -4021,6 +4070,16 @@ } ], "e58a1d884fa1d8f2": "Détails du fil", + "43c5fbd02c6f330a": "Afficher moins", + "de45b075b016cb14": [ + "Afficher ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " de plus" + ], "02d9667ff2c8e0b8": "Ticket {key} : {title}", "4276743ee60a3c62": "{count, plural, one {{count} commentaire} other {{count} commentaires}}", "42f634397f3960aa": "Afficher dans les détails du fil", @@ -4060,16 +4119,6 @@ ], "159ddd0d146a0f22": "Surveillance : l’agent se réveille quand les checks se terminent, que quelqu’un commente ou que la branche entre en conflit. Cliquez pour arrêter.", "1cbc8b5db51b4c77": "Fusionner", - "43c5fbd02c6f330a": "Afficher moins", - "de45b075b016cb14": [ - "Afficher ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " de plus" - ], "a3d040c4ef4fc6e9": "En avance sur le rythme", "b16fdf56b16d99c9": "Dans le rythme", "90f977e97ae8b6c6": "En dessous du rythme", @@ -4084,6 +4133,7 @@ "66be4fb43249bbd2": "{used} tokens sur {max}", "ee3ae58c8b38a425": "{left} % restant", "ebb26f93fb83a71b": "{label} : {left} % restant", + "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "728c6cc1431e76c8": "Réinitialisation dans {duration} · {time}", "e16b0b9b490c8bc7": "{label} : {value}", "ba67d0a9ff5dabf0": "L’API Presse-papiers n’est pas disponible pour copier la demande à l’administrateur.", @@ -4136,7 +4186,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é", @@ -10932,7 +10981,6 @@ "af4c158f5758af59": "Contrôles de la barre latérale", "cddde869ea4ceb29": "Sélection de la barre latérale", "735a61ef214f6836": "Arrière-plan du terminal", - "afc8fb892e52f932": "Erreur", "16ad4c65b7cde1bb": "« {label} » n’a pas de palette claire. Créez un thème du même nom pour en ajouter une.", "0ec05a92bf5537a2": "« {label} » n’a pas de palette sombre. Créez un thème du même nom pour en ajouter une.", "a9cfdfa41271d7d4": "« {label} » a déjà une palette claire.", @@ -11858,7 +11906,6 @@ "0bd938825ffcf992": "+{percent} % du quota", "09c0e00d7fb55402": "Utilisation du crédit de réinitialisation…", "4df3ff1be768a7ab": "{name} : {remaining} % restant", - "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", "a16b48709357a5a7": "Gérer l’utilisation", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 8459e9cf87854..4a42c46fe183e 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -82,6 +82,29 @@ "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} に応答していません", + "6ab96e26bda35288": "思考中", + "67733c48eaaec73a": "プラン", + "75aaf70eabf15f4b": "ファイル検索", + "ac511f991a3c1fab": "Web 検索", + "5e30649065b60d94": "承認リクエスト", + "5c8772e727c04218": "質問", + "a06eb47a82969918": "サブエージェント", + "646de37e0bec85f8": "ツール呼び出し", + "885ae08a2160a158": "コンテキストを圧縮しました", + "afc8fb892e52f932": "エラー", "f71597ae3afaef44": "{first} と {second}", "4047174839a16714": "{first}、{last}", "65ca7867c176afbf": "{first}、{rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "コンテキストの圧縮を停止しました", "2605da0149cd15f1": "コンテキストを圧縮しています", "39a82db18ca50c21": "コンテキストを圧縮しました ({before} → {after} トークン)", - "885ae08a2160a158": "コンテキストを圧縮しました", "3ab6b281a0991766": "{count, plural, =1 {リンクされたプルリクエストを確認しました} other {リンクされたプルリクエストを {count} 回確認しました}}", "857e92a89b6b6257": "{count, plural, other {{count} 個のファイルを読み取りました}}", "466ac7fcdb97bb76": "{count, plural, other {{count} 個のファイルを変更しました}}", @@ -1912,7 +1934,6 @@ "cf34b1bdf8179c16": "未コミット", "d85877d9ef77c50c": "変更", "b816058fba61e4d6": "ターン {count}", - "646de37e0bec85f8": "ツール呼び出し", "975c7fec8175f596": "コミット", "9614272348cc04cf": "最新のターン", "e6ae3a0fbf3eb49e": "この選択では差分ファイルの内容を利用できません。", @@ -3569,6 +3590,37 @@ " にリンクされています。エージェントはそのリンクをそのまま使用できます。アクセス権は [設定] → [環境] で変更してください。" ], "000b0df227182d39": "別のアドレス…", + "009e2ca841fdc1ef": "この環境", + "1944f04b75ddf26d": "{label} のスレッド", + "c8e6ea4d6313e912": "長いテキストのため、ここで省略されています。", + "59fb6d9ab29a1513": [ + "読み取り専用 · ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "(", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + }, + " 経由)" + ], + "ff1728d6a7065373": "作業中", + "d0bda35aeec66684": [ + "読み取り中: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "以前のものを読み込む", + "048b8a737af895ac": "このスレッドにはまだ何もありません。", + "c3e8cd9bf44e2f43": "以前に読み取った内容を表示しています。", "eb6e0584cf4a2a1d": "言語: {language}", "d76c606a3c519b78": "行の折り返しを無効にする", "2b683498cee8c8a7": "行を折り返す", @@ -3596,6 +3648,7 @@ "6d329f7d3a50c7e7": "表をコピー", "6c71d251d9917587": "Markdown としてコピー", "d510b122f84051a0": "CSV としてコピー", + "2912e4ac3697686b": "{label} のスレッドを読む", "ced684880c2e1961": "{server} に {tool} の実行を許可しますか?", "b66fa23b5647b62d": "{server} からこのメッセージを送信しますか?", "bae7f74153fa8a05": "{server} からの {names} を保存しますか?", @@ -3640,9 +3693,7 @@ "9bbecec926c3b695": "再試行", "4fd8927b7afc2a92": "メッセージをコピー", "6f8651e48261911a": "思考", - "ac511f991a3c1fab": "Web 検索", "07e65dba2b16d3f7": "{count, plural, other {{path} と他 {count} 件}}", - "6ab96e26bda35288": "思考中", "4d4981a1c5bd9728": "コマンドを実行中", "a078225c5f197cd2": "失敗したコマンド", "37ab148aaa486051": "拒否されたコマンド", @@ -3741,7 +3792,6 @@ "afe27891aab8cf37": "{label}: 準備ができていません。", "2f77cc3105ddd7f8": "プロバイダー", "3b205a1c17c06fbd": "お気に入り", - "a06eb47a82969918": "サブエージェント", "d567966a45ff32be": "サブエージェントの作業", "4740c38b2edd194d": "読み取り専用です。これらのサブエージェントはメッセージを受け付けません。", "5a0125dd9241cdec": "読み込んでいます…", @@ -4011,6 +4061,16 @@ } ], "e58a1d884fa1d8f2": "スレッドの詳細", + "43c5fbd02c6f330a": "表示を減らす", + "de45b075b016cb14": [ + "さらに ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 件を表示" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, other {{count} 件のコメント}}", "42f634397f3960aa": "スレッドの詳細に表示", @@ -4050,16 +4110,6 @@ ], "159ddd0d146a0f22": "監視中: チェックの完了、コメントの追加、ブランチの競合が発生するとエージェントが起動します。クリックすると停止します。", "1cbc8b5db51b4c77": "マージ", - "43c5fbd02c6f330a": "表示を減らす", - "de45b075b016cb14": [ - "さらに ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 件を表示" - ], "a3d040c4ef4fc6e9": "ペースより速い", "b16fdf56b16d99c9": "ペースどおり", "90f977e97ae8b6c6": "ペースより遅い", @@ -4074,6 +4124,7 @@ "66be4fb43249bbd2": "{used} / {max} トークン", "ee3ae58c8b38a425": "残り {left}%", "ebb26f93fb83a71b": "{label}: 残り {left}%", + "1b16346722b65812": "期間の残り {timeLeft}%", "728c6cc1431e76c8": "{duration} 後にリセット · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "管理者へのリクエストをコピーする際にクリップボード API を利用できませんでした。", @@ -4126,7 +4177,6 @@ "309b160785f6c473": "このチャットでフォークを開く", "6676cd4b8299663f": "このチャットで親スレッドを開く", "63e8c7a0ef0513b5": "関連するスレッド", - "68060b380fe53942": "{label} で実行されています。そこでスレッドを開くには接続してください。", "9996d9dac573001a": "{label} で開く", "15a601a94893277f": "親スレッドを開けませんでした", "5eb43f554a5b7a58": "親スレッドは削除されました", @@ -10882,7 +10932,6 @@ "af4c158f5758af59": "サイドバーのコントロール", "cddde869ea4ceb29": "サイドバーの選択", "735a61ef214f6836": "ターミナルの背景", - "afc8fb892e52f932": "エラー", "16ad4c65b7cde1bb": "「{label}」にはライトのパレットがありません。追加するには同じ名前のテーマを作成してください。", "0ec05a92bf5537a2": "「{label}」にはダークのパレットがありません。追加するには同じ名前のテーマを作成してください。", "a9cfdfa41271d7d4": "「{label}」にはすでにライトのパレットがあります。", @@ -11808,7 +11857,6 @@ "0bd938825ffcf992": "プールの +{percent}%", "09c0e00d7fb55402": "リセットクレジットを使用しています…", "4df3ff1be768a7ab": "{name}: 残り {remaining}%", - "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "使用量を管理", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c523c5dc7b1fc..4edcfe0e2bfe1 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -82,6 +82,29 @@ "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}에 응답하지 않습니다", + "6ab96e26bda35288": "생각 중", + "67733c48eaaec73a": "계획", + "75aaf70eabf15f4b": "파일 검색", + "ac511f991a3c1fab": "웹 검색", + "5e30649065b60d94": "승인 요청", + "5c8772e727c04218": "질문", + "a06eb47a82969918": "서브에이전트", + "646de37e0bec85f8": "도구 호출", + "885ae08a2160a158": "컨텍스트 압축됨", + "afc8fb892e52f932": "오류", "f71597ae3afaef44": "{first} 및 {second}", "4047174839a16714": "{first} 및 {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "컨텍스트 압축 중지됨", "2605da0149cd15f1": "컨텍스트 압축 중", "39a82db18ca50c21": "컨텍스트 압축됨: 토큰 {before} → {after}", - "885ae08a2160a158": "컨텍스트 압축됨", "3ab6b281a0991766": "{count, plural, =1 {연결된 풀 리퀘스트 확인함} other {연결된 풀 리퀘스트 {count}번 확인함}}", "857e92a89b6b6257": "{count, plural, other {파일 {count}개 읽음}}", "466ac7fcdb97bb76": "{count, plural, other {파일 {count}개 변경함}}", @@ -1914,7 +1936,6 @@ "cf34b1bdf8179c16": "커밋되지 않음", "d85877d9ef77c50c": "변경 사항", "b816058fba61e4d6": "턴 {count}", - "646de37e0bec85f8": "도구 호출", "975c7fec8175f596": "커밋", "9614272348cc04cf": "최근 턴", "e6ae3a0fbf3eb49e": "이 선택 항목의 변경된 파일 내용을 사용할 수 없습니다.", @@ -3569,6 +3590,37 @@ "에 연결되어 있습니다. 에이전트는 이 연결을 그대로 사용할 수 있으며, 액세스는 설정 → 환경에서 변경하세요." ], "000b0df227182d39": "다른 주소…", + "009e2ca841fdc1ef": "이 환경", + "1944f04b75ddf26d": "{label}의 스레드", + "c8e6ea4d6313e912": "긴 텍스트라 여기에서 잘렸습니다.", + "59fb6d9ab29a1513": [ + "읽기 전용 · ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " (", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + }, + " 경유)" + ], + "ff1728d6a7065373": "작업 중", + "d0bda35aeec66684": [ + "읽는 중: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "이전 항목 불러오기", + "048b8a737af895ac": "이 스레드에는 아직 아무것도 없습니다.", + "c3e8cd9bf44e2f43": "이전에 읽은 내용을 표시하고 있습니다.", "eb6e0584cf4a2a1d": "언어: {language}", "d76c606a3c519b78": "줄 바꿈 끄기", "2b683498cee8c8a7": "줄 바꿈", @@ -3596,6 +3648,7 @@ "6d329f7d3a50c7e7": "표 복사", "6c71d251d9917587": "Markdown으로 복사", "d510b122f84051a0": "CSV로 복사", + "2912e4ac3697686b": "{label}의 스레드 읽기", "ced684880c2e1961": "{server}이(가) {tool}을(를) 실행하도록 허용할까요?", "b66fa23b5647b62d": "{server}에서 이 메시지를 보낼까요?", "bae7f74153fa8a05": "{server}에서 {names}을(를) 저장할까요?", @@ -3640,9 +3693,7 @@ "9bbecec926c3b695": "다시 시도", "4fd8927b7afc2a92": "메시지 복사", "6f8651e48261911a": "생각", - "ac511f991a3c1fab": "웹 검색", "07e65dba2b16d3f7": "{count, plural, other {{path} 외 {count}개}}", - "6ab96e26bda35288": "생각 중", "4d4981a1c5bd9728": "명령 실행 중", "a078225c5f197cd2": "명령 실패", "37ab148aaa486051": "명령 거부됨", @@ -3739,7 +3790,6 @@ "afe27891aab8cf37": "{label}: 준비되지 않음.", "2f77cc3105ddd7f8": "제공자", "3b205a1c17c06fbd": "즐겨찾기", - "a06eb47a82969918": "서브에이전트", "d567966a45ff32be": "서브에이전트 작업", "4740c38b2edd194d": "읽기 전용입니다. 이 서브에이전트는 메시지를 받을 수 없습니다.", "5a0125dd9241cdec": "불러오는 중…", @@ -4009,6 +4059,15 @@ } ], "e58a1d884fa1d8f2": "스레드 세부 정보", + "43c5fbd02c6f330a": "간략히 보기", + "de45b075b016cb14": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "개 더 보기" + ], "02d9667ff2c8e0b8": "이슈 {key}: {title}", "4276743ee60a3c62": "{count, plural, other {댓글 {count}개}}", "42f634397f3960aa": "스레드 세부 정보에 표시", @@ -4048,15 +4107,6 @@ ], "159ddd0d146a0f22": "지켜보는 중: 검사가 끝나거나, 누군가 댓글을 달거나, 브랜치가 충돌하면 에이전트가 깨어납니다. 클릭하여 중지하세요.", "1cbc8b5db51b4c77": "병합", - "43c5fbd02c6f330a": "간략히 보기", - "de45b075b016cb14": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - "개 더 보기" - ], "a3d040c4ef4fc6e9": "예상보다 빠름", "b16fdf56b16d99c9": "예상대로", "90f977e97ae8b6c6": "예상보다 느림", @@ -4071,6 +4121,7 @@ "66be4fb43249bbd2": "토큰 {max}개 중 {used}개", "ee3ae58c8b38a425": "{left}% 남음", "ebb26f93fb83a71b": "{label}: {left}% 남음", + "1b16346722b65812": "기간 {timeLeft}% 남음", "728c6cc1431e76c8": "{duration} 후 초기화 · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "관리자 요청을 복사하는 중 클립보드 API를 사용할 수 없습니다.", @@ -4123,7 +4174,6 @@ "309b160785f6c473": "이 채팅에서 포크 열기", "6676cd4b8299663f": "이 채팅에서 상위 스레드 열기", "63e8c7a0ef0513b5": "관련 스레드", - "68060b380fe53942": "{label}에서 실행됩니다. 그곳에서 스레드를 열려면 연결하세요.", "9996d9dac573001a": "{label}에서 열기", "15a601a94893277f": "상위 스레드를 열 수 없습니다", "5eb43f554a5b7a58": "상위 스레드가 삭제되었습니다", @@ -10879,7 +10929,6 @@ "af4c158f5758af59": "사이드바 컨트롤", "cddde869ea4ceb29": "사이드바 선택 항목", "735a61ef214f6836": "터미널 배경", - "afc8fb892e52f932": "오류", "16ad4c65b7cde1bb": "“{label}”에는 밝은 팔레트가 없습니다. 추가하려면 같은 이름으로 테마를 만드세요.", "0ec05a92bf5537a2": "“{label}”에는 어두운 팔레트가 없습니다. 추가하려면 같은 이름으로 테마를 만드세요.", "a9cfdfa41271d7d4": "“{label}”에는 이미 밝은 팔레트가 있습니다.", @@ -11805,7 +11854,6 @@ "0bd938825ffcf992": "풀의 +{percent}%", "09c0e00d7fb55402": "초기화 크레딧 사용 중…", "4df3ff1be768a7ab": "{name}: {remaining}% 남음", - "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", "a16b48709357a5a7": "사용량 관리", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index bd34cd96c3d8b..fe38078d4b8bc 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -82,6 +82,29 @@ "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}", + "6ab96e26bda35288": "Pensando", + "67733c48eaaec73a": "Plano", + "75aaf70eabf15f4b": "Pesquisa de arquivos", + "ac511f991a3c1fab": "Pesquisa na web", + "5e30649065b60d94": "Solicitação de aprovação", + "5c8772e727c04218": "Pergunta", + "a06eb47a82969918": "Subagente", + "646de37e0bec85f8": "Chamada de ferramenta", + "885ae08a2160a158": "Contexto compactado", + "afc8fb892e52f932": "Erro", "f71597ae3afaef44": "{first} e {second}", "4047174839a16714": "{first} e {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "Compactação do contexto interrompida", "2605da0149cd15f1": "Compactando o contexto", "39a82db18ca50c21": "Contexto compactado de {before} → {after} tokens", - "885ae08a2160a158": "Contexto compactado", "3ab6b281a0991766": "{count, plural, =1 {Verificou os pull requests vinculados} other {Verificou os pull requests vinculados {count} vezes}}", "857e92a89b6b6257": "{count, plural, one {Leu {count} arquivo} other {Leu {count} arquivos}}", "466ac7fcdb97bb76": "{count, plural, one {Alterou {count} arquivo} other {Alterou {count} arquivos}}", @@ -1914,7 +1936,6 @@ "cf34b1bdf8179c16": "Sem commit", "d85877d9ef77c50c": "Alterações", "b816058fba61e4d6": "Turno {count}", - "646de37e0bec85f8": "Chamada de ferramenta", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Último turno", "e6ae3a0fbf3eb49e": "O conteúdo dos arquivos do diff não está disponível para esta seleção.", @@ -3574,6 +3595,36 @@ ". O agente pode usar esse vínculo como está; altere o acesso em Configurações → Ambientes." ], "000b0df227182d39": "Outro endereço…", + "009e2ca841fdc1ef": "este ambiente", + "1944f04b75ddf26d": "Thread em {label}", + "c8e6ea4d6313e912": "Texto longo, cortado aqui.", + "59fb6d9ab29a1513": [ + "Somente leitura · em ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " via ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "Trabalhando", + "d0bda35aeec66684": [ + "Lendo de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "Carregar anteriores", + "048b8a737af895ac": "Ainda não há nada nesta thread.", + "c3e8cd9bf44e2f43": "Mostrando o que foi lido antes.", "eb6e0584cf4a2a1d": "Linguagem: {language}", "d76c606a3c519b78": "Desativar quebra de linha", "2b683498cee8c8a7": "Quebrar linhas", @@ -3601,6 +3652,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}?", @@ -3647,9 +3699,7 @@ "9bbecec926c3b695": "Tentar novamente", "4fd8927b7afc2a92": "Copiar mensagem", "6f8651e48261911a": "Raciocínio", - "ac511f991a3c1fab": "Pesquisa na web", "07e65dba2b16d3f7": "{count, plural, one {{path} e mais {count}} other {{path} e mais {count}}}", - "6ab96e26bda35288": "Pensando", "4d4981a1c5bd9728": "Executando comando", "a078225c5f197cd2": "Comando com falha", "37ab148aaa486051": "Comando recusado", @@ -3748,7 +3798,6 @@ "afe27891aab8cf37": "{label}: não está pronto.", "2f77cc3105ddd7f8": "Provedores", "3b205a1c17c06fbd": "Favoritos", - "a06eb47a82969918": "Subagente", "d567966a45ff32be": "Trabalho de subagentes", "4740c38b2edd194d": "Somente leitura. Estes subagentes não aceitam mensagens.", "5a0125dd9241cdec": "Carregando…", @@ -4021,6 +4070,15 @@ } ], "e58a1d884fa1d8f2": "Detalhes da thread", + "43c5fbd02c6f330a": "Mostrar menos", + "de45b075b016cb14": [ + "Mostrar mais ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comentário} other {{count} comentários}}", "42f634397f3960aa": "Mostrar nos detalhes da thread", @@ -4060,15 +4118,6 @@ ], "159ddd0d146a0f22": "Acompanhando: o agente é ativado quando as verificações terminam, alguém comenta ou o branch entra em conflito. Clique para parar.", "1cbc8b5db51b4c77": "Mesclar", - "43c5fbd02c6f330a": "Mostrar menos", - "de45b075b016cb14": [ - "Mostrar mais ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "a3d040c4ef4fc6e9": "Acima do ritmo", "b16fdf56b16d99c9": "No ritmo", "90f977e97ae8b6c6": "Abaixo do ritmo", @@ -4083,6 +4132,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left}% restante", "ebb26f93fb83a71b": "{label}: {left}% restante", + "1b16346722b65812": "{timeLeft}% da janela restante", "728c6cc1431e76c8": "Renova em {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "A API da área de transferência não está disponível ao copiar o pedido para o administrador.", @@ -4135,7 +4185,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", @@ -10931,7 +10980,6 @@ "af4c158f5758af59": "Controles da barra lateral", "cddde869ea4ceb29": "Seleção da barra lateral", "735a61ef214f6836": "Fundo do terminal", - "afc8fb892e52f932": "Erro", "16ad4c65b7cde1bb": "“{label}” não tem paleta clara. Crie um tema com o mesmo nome para adicionar uma.", "0ec05a92bf5537a2": "“{label}” não tem paleta escura. Crie um tema com o mesmo nome para adicionar uma.", "a9cfdfa41271d7d4": "“{label}” já tem uma paleta clara.", @@ -11857,7 +11905,6 @@ "0bd938825ffcf992": "+{percent}% do total", "09c0e00d7fb55402": "Usando crédito de redefinição…", "4df3ff1be768a7ab": "{name}: {remaining}% restante", - "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", "a16b48709357a5a7": "Gerenciar uso", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4242d78d5f3c5..2c9cdd2feaf85 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -82,6 +82,29 @@ "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}", + "6ab96e26bda35288": "Думает", + "67733c48eaaec73a": "План", + "75aaf70eabf15f4b": "Поиск файлов", + "ac511f991a3c1fab": "Поиск в интернете", + "5e30649065b60d94": "Запрос подтверждения", + "5c8772e727c04218": "Вопрос", + "a06eb47a82969918": "Субагент", + "646de37e0bec85f8": "Вызов инструмента", + "885ae08a2160a158": "Контекст сжат", + "afc8fb892e52f932": "Ошибка", "f71597ae3afaef44": "{first} и {second}", "4047174839a16714": "{first} и {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "Сжатие контекста остановлено", "2605da0149cd15f1": "Сжатие контекста", "39a82db18ca50c21": "Контекст сжат: {before} → {after} токенов", - "885ae08a2160a158": "Контекст сжат", "3ab6b281a0991766": "{count, plural, =1 {Проверены привязанные пул-реквесты} one {Привязанные пул-реквесты проверены {count} раз} few {Привязанные пул-реквесты проверены {count} раза} many {Привязанные пул-реквесты проверены {count} раз} other {Привязанные пул-реквесты проверены {count} раза}}", "857e92a89b6b6257": "{count, plural, one {Прочитан {count} файл} few {Прочитано {count} файла} many {Прочитано {count} файлов} other {Прочитано {count} файла}}", "466ac7fcdb97bb76": "{count, plural, one {Изменён {count} файл} few {Изменено {count} файла} many {Изменено {count} файлов} other {Изменено {count} файла}}", @@ -1914,7 +1936,6 @@ "cf34b1bdf8179c16": "Без коммита", "d85877d9ef77c50c": "Изменения", "b816058fba61e4d6": "Ход {count}", - "646de37e0bec85f8": "Вызов инструмента", "975c7fec8175f596": "Коммит", "9614272348cc04cf": "Последний ход", "e6ae3a0fbf3eb49e": "Содержимое файлов диффа недоступно для этого выбора.", @@ -3574,6 +3595,36 @@ ". Агент может использовать эту привязку как есть; изменить её доступ можно в «Настройки → Окружения»." ], "000b0df227182d39": "Другой адрес…", + "009e2ca841fdc1ef": "это окружение", + "1944f04b75ddf26d": "Тред на {label}", + "c8e6ea4d6313e912": "Длинный текст, здесь обрезан.", + "59fb6d9ab29a1513": [ + "Только чтение · на ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " через ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "Работает", + "d0bda35aeec66684": [ + "Чтение с ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "Загрузить более ранние", + "048b8a737af895ac": "В этом треде пока ничего нет.", + "c3e8cd9bf44e2f43": "Показано то, что было прочитано раньше.", "eb6e0584cf4a2a1d": "Язык: {language}", "d76c606a3c519b78": "Отключить перенос строк", "2b683498cee8c8a7": "Переносить строки", @@ -3601,6 +3652,7 @@ "6d329f7d3a50c7e7": "Копировать таблицу", "6c71d251d9917587": "Копировать как Markdown", "d510b122f84051a0": "Копировать как CSV", + "2912e4ac3697686b": "Читать тред на {label}", "ced684880c2e1961": "Разрешить {server} запустить {tool}?", "b66fa23b5647b62d": "Отправить это сообщение от {server}?", "bae7f74153fa8a05": "Сохранить {names} от {server}?", @@ -3647,9 +3699,7 @@ "9bbecec926c3b695": "Повторить", "4fd8927b7afc2a92": "Копировать сообщение", "6f8651e48261911a": "Размышление", - "ac511f991a3c1fab": "Поиск в интернете", "07e65dba2b16d3f7": "{count, plural, one {{path} и ещё {count}} few {{path} и ещё {count}} many {{path} и ещё {count}} other {{path} и ещё {count}}}", - "6ab96e26bda35288": "Думает", "4d4981a1c5bd9728": "Выполняется команда", "a078225c5f197cd2": "Команда с ошибкой", "37ab148aaa486051": "Команда отклонена", @@ -3748,7 +3798,6 @@ "afe27891aab8cf37": "{label}: не готов.", "2f77cc3105ddd7f8": "Провайдеры", "3b205a1c17c06fbd": "Избранное", - "a06eb47a82969918": "Субагент", "d567966a45ff32be": "Работа субагентов", "4740c38b2edd194d": "Только чтение. Этим субагентам нельзя отправлять сообщения.", "5a0125dd9241cdec": "Загрузка…", @@ -4021,6 +4070,15 @@ } ], "e58a1d884fa1d8f2": "Сведения о треде", + "43c5fbd02c6f330a": "Показать меньше", + "de45b075b016cb14": [ + "Показать ещё ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} комментарий} few {{count} комментария} many {{count} комментариев} other {{count} комментария}}", "42f634397f3960aa": "Показывать в сведениях о треде", @@ -4060,15 +4118,6 @@ ], "159ddd0d146a0f22": "Отслеживается: агент проснётся, когда завершатся проверки, кто-то оставит комментарий или в ветке появится конфликт. Нажмите, чтобы прекратить.", "1cbc8b5db51b4c77": "Слить", - "43c5fbd02c6f330a": "Показать меньше", - "de45b075b016cb14": [ - "Показать ещё ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "a3d040c4ef4fc6e9": "Быстрее темпа", "b16fdf56b16d99c9": "В темпе", "90f977e97ae8b6c6": "Медленнее темпа", @@ -4083,6 +4132,7 @@ "66be4fb43249bbd2": "{used} из {max} токенов", "ee3ae58c8b38a425": "Осталось {left}%", "ebb26f93fb83a71b": "{label}: осталось {left}%", + "1b16346722b65812": "От окна осталось {timeLeft}%", "728c6cc1431e76c8": "Сброс через {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "API буфера обмена недоступен при копировании запроса администратору.", @@ -4135,7 +4185,6 @@ "309b160785f6c473": "Открыть ответвление в этом чате", "6676cd4b8299663f": "Открыть родительский тред в этом чате", "63e8c7a0ef0513b5": "Связанные треды", - "68060b380fe53942": "Работает на {label}. Подключитесь к нему, чтобы открыть тред там.", "9996d9dac573001a": "Открыть на {label}", "15a601a94893277f": "Не удалось открыть родительский тред", "5eb43f554a5b7a58": "Родительский тред удалён", @@ -10932,7 +10981,6 @@ "af4c158f5758af59": "Элементы боковой панели", "cddde869ea4ceb29": "Выделение на боковой панели", "735a61ef214f6836": "Фон терминала", - "afc8fb892e52f932": "Ошибка", "16ad4c65b7cde1bb": "У «{label}» нет светлой палитры. Чтобы добавить её, создайте тему с тем же названием.", "0ec05a92bf5537a2": "У «{label}» нет тёмной палитры. Чтобы добавить её, создайте тему с тем же названием.", "a9cfdfa41271d7d4": "У «{label}» уже есть светлая палитра.", @@ -11858,7 +11906,6 @@ "0bd938825ffcf992": "+{percent}% пула", "09c0e00d7fb55402": "Использование кредита на сброс…", "4df3ff1be768a7ab": "{name}: осталось {remaining}%", - "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", "a16b48709357a5a7": "Управление использованием", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d3d7bec015020..06363ce596933 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -82,6 +82,29 @@ "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}", + "6ab96e26bda35288": "Tänker", + "67733c48eaaec73a": "Abonnemang", + "75aaf70eabf15f4b": "Filsökning", + "ac511f991a3c1fab": "Webbsökning", + "5e30649065b60d94": "Begäran om godkännande", + "5c8772e727c04218": "Fråga", + "a06eb47a82969918": "Subagent", + "646de37e0bec85f8": "Verktygsanrop", + "885ae08a2160a158": "Kontexten komprimerades", + "afc8fb892e52f932": "Fel", "f71597ae3afaef44": "{first} och {second}", "4047174839a16714": "{first} och {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "Kontextkomprimeringen stoppades", "2605da0149cd15f1": "Komprimerar kontext", "39a82db18ca50c21": "Kontexten komprimerades {before} → {after} token", - "885ae08a2160a158": "Kontexten komprimerades", "3ab6b281a0991766": "{count, plural, =1 {Kontrollerade länkade pull requests} other {Kontrollerade länkade pull requests {count} gånger}}", "857e92a89b6b6257": "{count, plural, one {Läste {count} fil} other {Läste {count} filer}}", "466ac7fcdb97bb76": "{count, plural, one {Ändrade {count} fil} other {Ändrade {count} filer}}", @@ -1914,7 +1936,6 @@ "cf34b1bdf8179c16": "Ej committat", "d85877d9ef77c50c": "Ändringar", "b816058fba61e4d6": "Omgång {count}", - "646de37e0bec85f8": "Verktygsanrop", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Senaste omgången", "e6ae3a0fbf3eb49e": "Diffens filinnehåll är inte tillgängligt för den här markeringen.", @@ -3574,6 +3595,36 @@ ". Agenten kan använda den länken som den är; ändra dess åtkomst under Inställningar → Miljöer." ], "000b0df227182d39": "En annan adress…", + "009e2ca841fdc1ef": "den här miljön", + "1944f04b75ddf26d": "Tråd på {label}", + "c8e6ea4d6313e912": "Lång text, avkortad här.", + "59fb6d9ab29a1513": [ + "Skrivskyddad · på ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " via ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "Arbetar", + "d0bda35aeec66684": [ + "Läser från ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "…" + ], + "50fb8b2ca3db6cad": "Läs in tidigare", + "048b8a737af895ac": "Inget i den här tråden ännu.", + "c3e8cd9bf44e2f43": "Visar det som lästes tidigare.", "eb6e0584cf4a2a1d": "Språk: {language}", "d76c606a3c519b78": "Inaktivera radbrytning", "2b683498cee8c8a7": "Bryt rader", @@ -3601,6 +3652,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}?", @@ -3647,9 +3699,7 @@ "9bbecec926c3b695": "Försök igen", "4fd8927b7afc2a92": "Kopiera meddelande", "6f8651e48261911a": "Tanke", - "ac511f991a3c1fab": "Webbsökning", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} till} other {{path} +{count} till}}", - "6ab96e26bda35288": "Tänker", "4d4981a1c5bd9728": "Kör kommando", "a078225c5f197cd2": "Misslyckat kommando", "37ab148aaa486051": "Avböjt kommando", @@ -3748,7 +3798,6 @@ "afe27891aab8cf37": "{label}: Inte redo.", "2f77cc3105ddd7f8": "Leverantörer", "3b205a1c17c06fbd": "Favoriter", - "a06eb47a82969918": "Subagent", "d567966a45ff32be": "Subagentarbete", "4740c38b2edd194d": "Endast läsning. De här subagenterna kan inte ta emot meddelanden.", "5a0125dd9241cdec": "Läser in…", @@ -4021,6 +4070,16 @@ } ], "e58a1d884fa1d8f2": "Tråddetaljer", + "43c5fbd02c6f330a": "Visa mindre", + "de45b075b016cb14": [ + "Visa ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " till" + ], "02d9667ff2c8e0b8": "Ärende {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} kommentar} other {{count} kommentarer}}", "42f634397f3960aa": "Visa i tråddetaljer", @@ -4060,16 +4119,6 @@ ], "159ddd0d146a0f22": "Bevakar: agenten vaknar när kontrollerna är klara, någon kommenterar eller grenen får konflikter. Klicka för att sluta.", "1cbc8b5db51b4c77": "Merga", - "43c5fbd02c6f330a": "Visa mindre", - "de45b075b016cb14": [ - "Visa ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " till" - ], "a3d040c4ef4fc6e9": "Före takten", "b16fdf56b16d99c9": "I takt", "90f977e97ae8b6c6": "Under takten", @@ -4084,6 +4133,7 @@ "66be4fb43249bbd2": "{used} av {max} token", "ee3ae58c8b38a425": "{left} % kvar", "ebb26f93fb83a71b": "{label}: {left} % kvar", + "1b16346722b65812": "{timeLeft} % av fönstret kvar", "728c6cc1431e76c8": "Återställs om {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Urklipps-API:t är inte tillgängligt vid kopiering av administratörsbegäran.", @@ -4136,7 +4186,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", @@ -10940,7 +10989,6 @@ "af4c158f5758af59": "Sidofältets kontroller", "cddde869ea4ceb29": "Sidofältets markering", "735a61ef214f6836": "Terminalens bakgrund", - "afc8fb892e52f932": "Fel", "16ad4c65b7cde1bb": "”{label}” har ingen ljus palett. Skapa ett tema med samma namn för att lägga till en.", "0ec05a92bf5537a2": "”{label}” har ingen mörk palett. Skapa ett tema med samma namn för att lägga till en.", "a9cfdfa41271d7d4": "”{label}” har redan en ljus palett.", @@ -11866,7 +11914,6 @@ "0bd938825ffcf992": "+{percent} % av poolen", "09c0e00d7fb55402": "Använder återställningskredit…", "4df3ff1be768a7ab": "{name}: {remaining} % kvar", - "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", "a16b48709357a5a7": "Hantera användning", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5923adef292f5..1d904362e9f30 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -82,6 +82,29 @@ "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}", + "6ab96e26bda35288": "正在思考", + "67733c48eaaec73a": "计划", + "75aaf70eabf15f4b": "文件搜索", + "ac511f991a3c1fab": "网络搜索", + "5e30649065b60d94": "审批请求", + "5c8772e727c04218": "问题", + "a06eb47a82969918": "子智能体", + "646de37e0bec85f8": "工具调用", + "885ae08a2160a158": "上下文已压缩", + "afc8fb892e52f932": "错误", "f71597ae3afaef44": "{first} 和 {second}", "4047174839a16714": "{first} 和 {last}", "65ca7867c176afbf": "{first}、{rest}", @@ -857,7 +880,6 @@ "3277065a791a0e06": "上下文压缩已停止", "2605da0149cd15f1": "正在压缩上下文", "39a82db18ca50c21": "上下文已压缩:{before} → {after} token", - "885ae08a2160a158": "上下文已压缩", "3ab6b281a0991766": "{count, plural, =1 {已检查关联的 pull request } other {已检查关联的 pull request {count} 次}}", "857e92a89b6b6257": "{count, plural, other {已读取 {count} 个文件}}", "466ac7fcdb97bb76": "{count, plural, other {已更改 {count} 个文件}}", @@ -1916,7 +1938,6 @@ "cf34b1bdf8179c16": "未提交的更改", "d85877d9ef77c50c": "改动", "b816058fba61e4d6": "第 {count} 轮", - "646de37e0bec85f8": "工具调用", "975c7fec8175f596": "提交", "9614272348cc04cf": "最近一轮", "e6ae3a0fbf3eb49e": "此选择没有可用的差异文件内容。", @@ -3579,6 +3600,36 @@ "。智能体可以直接使用该关联;请在“设置 → 环境”中更改其访问权限。" ], "000b0df227182d39": "其他地址…", + "009e2ca841fdc1ef": "此环境", + "1944f04b75ddf26d": "{label} 上的会话", + "c8e6ea4d6313e912": "文本较长,此处已截断。", + "59fb6d9ab29a1513": [ + "只读 · 位于 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ",经由 ", + { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + ], + "ff1728d6a7065373": "运行中", + "d0bda35aeec66684": [ + "正在从 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 读取…" + ], + "50fb8b2ca3db6cad": "加载更早的内容", + "048b8a737af895ac": "此会话中还没有内容。", + "c3e8cd9bf44e2f43": "正在显示之前读取的内容。", "eb6e0584cf4a2a1d": "语言:{language}", "d76c606a3c519b78": "取消自动换行", "2b683498cee8c8a7": "自动换行", @@ -3606,6 +3657,7 @@ "6d329f7d3a50c7e7": "复制表格", "6c71d251d9917587": "复制为 Markdown", "d510b122f84051a0": "复制为 CSV", + "2912e4ac3697686b": "读取 {label} 上的会话", "ced684880c2e1961": "允许 {server} 运行 {tool} 吗?", "b66fa23b5647b62d": "要发送这条来自 {server} 的消息吗?", "bae7f74153fa8a05": "要保存来自 {server} 的 {names} 吗?", @@ -3651,9 +3703,7 @@ "9bbecec926c3b695": "重试", "4fd8927b7afc2a92": "复制消息", "6f8651e48261911a": "已思考", - "ac511f991a3c1fab": "网络搜索", "07e65dba2b16d3f7": "{count, plural, other {{path},另有 {count} 个}}", - "6ab96e26bda35288": "正在思考", "4d4981a1c5bd9728": "正在运行命令", "a078225c5f197cd2": "命令失败", "37ab148aaa486051": "已拒绝命令", @@ -3752,7 +3802,6 @@ "afe27891aab8cf37": "{label}:未就绪。", "2f77cc3105ddd7f8": "智能体提供方", "3b205a1c17c06fbd": "收藏", - "a06eb47a82969918": "子智能体", "d567966a45ff32be": "子智能体工作", "4740c38b2edd194d": "只读。这些子智能体无法接收消息。", "5a0125dd9241cdec": "加载中…", @@ -4026,6 +4075,16 @@ } ], "e58a1d884fa1d8f2": "会话详情", + "43c5fbd02c6f330a": "收起", + "de45b075b016cb14": [ + "再显示 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 个" + ], "02d9667ff2c8e0b8": "issue {key}:{title}", "4276743ee60a3c62": "{count, plural, other {{count} 条评论}}", "42f634397f3960aa": "在会话详情中显示", @@ -4066,16 +4125,6 @@ ], "159ddd0d146a0f22": "关注中:检查完成、有人评论或分支出现冲突时,智能体会被唤醒。点击停止关注。", "1cbc8b5db51b4c77": "合并", - "43c5fbd02c6f330a": "收起", - "de45b075b016cb14": [ - "再显示 ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 个" - ], "a3d040c4ef4fc6e9": "用量消耗偏快", "b16fdf56b16d99c9": "用量消耗适中", "90f977e97ae8b6c6": "用量消耗偏慢", @@ -4090,6 +4139,7 @@ "66be4fb43249bbd2": "{used} / {max} token", "ee3ae58c8b38a425": "剩余 {left}%", "ebb26f93fb83a71b": "{label}:剩余 {left}%", + "1b16346722b65812": "窗口剩余 {timeLeft}%", "728c6cc1431e76c8": "{duration} 后重置 · {time}", "e16b0b9b490c8bc7": "{label}:{value}", "ba67d0a9ff5dabf0": "复制管理员请求时剪贴板 API 不可用。", @@ -4142,7 +4192,6 @@ "309b160785f6c473": "在此对话中打开分叉", "6676cd4b8299663f": "在此对话中打开父会话", "63e8c7a0ef0513b5": "相关会话", - "68060b380fe53942": "运行于 {label}。连接到它以在那里打开会话。", "9996d9dac573001a": "在 {label} 上打开", "15a601a94893277f": "无法打开父会话", "5eb43f554a5b7a58": "父会话已被删除", @@ -10953,7 +11002,6 @@ "af4c158f5758af59": "侧边栏控件", "cddde869ea4ceb29": "侧边栏选中项", "735a61ef214f6836": "终端背景", - "afc8fb892e52f932": "错误", "16ad4c65b7cde1bb": "“{label}”没有浅色调色板。创建同名主题即可添加。", "0ec05a92bf5537a2": "“{label}”没有深色调色板。创建同名主题即可添加。", "a9cfdfa41271d7d4": "“{label}”已有浅色调色板。", @@ -11883,7 +11931,6 @@ "0bd938825ffcf992": "+{percent}%(按共享池总额度计算)", "09c0e00d7fb55402": "正在使用重置额度…", "4df3ff1be768a7ab": "{name}:剩余 {remaining}%", - "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "管理用量", diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 3cbef77306c8e..6a78b0f957a6a 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -17,6 +17,7 @@ import { useEffect, useEffectEvent, useRef, useState } from "react"; import { APP_DISPLAY_NAME, APP_VERSION } from "../branding"; import { AppSidebarLayout } from "../components/AppSidebarLayout"; import { CommandPalette } from "../components/CommandPalette"; +import { LinkedThreadSheet } from "../components/chat/LinkedThreadSheet"; import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog"; import { GuestShareDialogHost } from "../components/chat/GuestShareControls"; import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog"; @@ -205,6 +206,7 @@ function RootRouteBranch() { + {import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null} ); diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts new file mode 100644 index 0000000000000..bf27c529622d9 --- /dev/null +++ b/apps/web/src/state/linkedThreadView.ts @@ -0,0 +1,100 @@ +import { useAtomSet } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + createLinkedThreadSession, + type LinkedThreadOpen, + type LinkedThreadTarget, + resolveLinkedThreadOpen, +} from "@t3tools/client-runtime/linked-thread"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { Atom } from "effect/reactivity"; +import { useState, useSyncExternalStore } from "react"; + +import { getDocumentActivity } from "../lib/documentActivity"; +import { buildThreadRouteParams } from "../threadRoutes"; +import { useEnvironment } from "./environments"; +import { peerLinkEnvironment } from "./peerLinks"; +import { useAtomCommand } from "./use-atom-command"; + +/** The linked environment's thread the read-only view shows, or none. */ +export const linkedThreadViewAtom = Atom.make(null).pipe( + Atom.withLabel("linked-thread-view"), +); + +/** Opens a linked environment's thread in the read-only view. */ +export function useOpenLinkedThread(): (target: LinkedThreadTarget) => void { + return useAtomSet(linkedThreadViewAtom); +} + +/** + * How a click opens a thread that a thread in `viaEnvironmentId` says is on a linked environment: + * in place when this client is connected there itself, else read-only through the link. + */ +export function useLinkedThreadOpener( + viaEnvironmentId: EnvironmentId, + thread: + | { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly label: string; + } + | undefined, + title: string | null, +): { readonly mode: LinkedThreadOpen; readonly open: () => void } | null { + const navigate = useNavigate(); + const openLinked = useOpenLinkedThread(); + const own = useEnvironment(thread?.environmentId ?? null); + if (thread === undefined) return null; + const mode = resolveLinkedThreadOpen({ + environmentId: thread.environmentId, + viaEnvironmentId, + own: own === null ? undefined : { connected: own.connection.phase === "connected" }, + linked: true, + }); + return { + mode, + open: () => { + if (mode === "linked") { + openLinked({ viaEnvironmentId, ...thread, label: own?.label ?? thread.label, title }); + return; + } + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.threadId)), + }); + }, + }; +} + +/** + * The transcript of `target`, read through the environment that links to it. Reads start when the + * calling view mounts and stop when it unmounts; key the view by its target. + */ +export function useLinkedThreadSession(target: LinkedThreadTarget) { + const read = useAtomCommand(peerLinkEnvironment.readThread, { + reportFailure: false, + reportDefect: false, + }); + const [session] = useState(() => + createLinkedThreadSession({ + read: async (cursor) => { + const result = await read({ + environmentId: target.viaEnvironmentId, + input: { environmentId: target.environmentId, threadId: target.threadId, ...cursor }, + }); + return result._tag === "Success" + ? { ok: true, page: result.value } + : { ok: false, error: squashAtomCommandFailure(result) }; + }, + schedule: (run, delayMs) => { + const timer = setTimeout(run, delayMs); + return () => clearTimeout(timer); + }, + isActive: () => getDocumentActivity().visible, + }), + ); + const state = useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot); + return { state, session }; +} diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 8a8e87fe0ba57..953ae0d2c41b2 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -435,6 +435,21 @@ 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 its transcript opens read-only, fetched by the machine you are +connected to over its link. It follows the thread while it runs. + +- The view is marked **Read-only** with both machines' names. To reply, approve + or stop the thread, connect this app to that machine. +- 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 003abc03ac65f..fb50a1b8e9f31 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -107,6 +107,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" diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts new file mode 100644 index 0000000000000..c33862372bf0a --- /dev/null +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -0,0 +1,353 @@ +import { EnvironmentId, type PeerLinkThreadPage, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + createLinkedThreadSession, + type LinkedThreadCursor, + type LinkedThreadReadResult, + presentLinkedThreadItem, + LINKED_THREAD_ACTIVE_POLL_MS, + LINKED_THREAD_IDLE_POLL_MS, + linkedThreadFailure, + linkedThreadPollDelayMs, + linkedThreadRefreshCursor, + mergeLinkedThreadPage, + resolveLinkedThreadOpen, +} from "./linkedThread.ts"; + +const nucbox = EnvironmentId.make("environment-nucbox"); +const vm = EnvironmentId.make("environment-vm"); +const threadId = ThreadId.make("thread:vm"); + +const item = ( + position: number, + text: string, + status: PeerLinkThreadPage["items"][number]["status"] = "completed", +): PeerLinkThreadPage["items"][number] => ({ + position, + visibility: "local", + sourceThreadId: threadId, + itemId: TurnItemId.make(`item:${position}`), + runId: null, + messageId: null, + createdBy: null, + creationSource: null, + type: "assistant_message", + status, + title: null, + text, + textTruncated: false, + updatedAt: "2026-11-19T00:00:00.000Z", +}); + +const page = ( + items: PeerLinkThreadPage["items"], + overrides: Partial = {}, +): PeerLinkThreadPage => ({ + label: "VM", + thread: { threadId, title: "Fix the build", status: "running", model: "gpt-5" }, + items, + earlierPosition: null, + hasMore: false, + ...overrides, +}); + +describe("resolveLinkedThreadOpen", () => { + const open = (own: { connected: boolean } | undefined, linked: boolean) => + resolveLinkedThreadOpen({ environmentId: vm, viaEnvironmentId: nucbox, own, linked }); + + it("keeps the client's own connection when it has one", () => { + expect(open({ connected: true }, true)).toBe("direct"); + }); + + it("reads through the link when the client is not connected to that environment", () => { + expect(open(undefined, true)).toBe("linked"); + expect(open({ connected: false }, true)).toBe("linked"); + }); + + it("falls back to what the client can do alone when nothing links there", () => { + expect(open({ connected: false }, false)).toBe("direct"); + expect(open(undefined, false)).toBe("unavailable"); + }); + + it("never routes an environment's own thread through a link", () => { + expect( + resolveLinkedThreadOpen({ + environmentId: nucbox, + viaEnvironmentId: nucbox, + own: undefined, + linked: true, + }), + ).toBe("direct"); + }); +}); + +describe("mergeLinkedThreadPage", () => { + const newest = page([item(10, "ten"), item(11, "eleven", "running")], { earlierPosition: 10 }); + + it("moves the start back with an earlier page and keeps the forward state", () => { + const merged = mergeLinkedThreadPage( + newest, + page([item(8, "eight"), item(9, "nine")], { earlierPosition: null, hasMore: true }), + "earlier", + ); + expect(merged.items.map((entry) => entry.position)).toEqual([8, 9, 10, 11]); + expect(merged.earlierPosition).toBeNull(); + expect(merged.hasMore).toBe(false); + }); + + it("replaces a re-read item and appends what followed, without moving the start", () => { + const merged = mergeLinkedThreadPage( + newest, + page([item(11, "eleven, finished"), item(12, "twelve")], { + earlierPosition: 11, + thread: { threadId, title: "Fix the build", status: "completed", model: "gpt-5" }, + }), + "later", + ); + expect(merged.items.map((entry) => entry.text)).toEqual(["ten", "eleven, finished", "twelve"]); + expect(merged.earlierPosition).toBe(10); + expect(merged.thread.status).toBe("completed"); + }); +}); + +describe("linkedThreadRefreshCursor", () => { + it("reads after the last item once everything shown has settled", () => { + expect(linkedThreadRefreshCursor(page([item(4, "a"), item(5, "b")]))).toBe(5); + expect(linkedThreadRefreshCursor(page([]))).toBe(-1); + }); + + it("re-reads from an item that is still being written", () => { + expect( + linkedThreadRefreshCursor(page([item(4, "a"), item(5, "b", "running"), item(6, "c")])), + ).toBe(4); + }); + + it("continues from the last item while a page left more behind it", () => { + expect( + linkedThreadRefreshCursor(page([item(4, "a", "running"), item(5, "b")], { hasMore: true })), + ).toBe(5); + }); + + it("stops re-reading an item that stays unsettled once it is far behind", () => { + const items = [ + item(0, "stuck", "waiting"), + ...Array.from({ length: 30 }, (_, i) => item(i + 1, "x")), + ]; + expect(linkedThreadRefreshCursor(page(items))).toBe(30); + }); +}); + +describe("linkedThreadPollDelayMs", () => { + it("reads again at once while catching up, soon while working, and rarely when idle", () => { + expect(linkedThreadPollDelayMs(page([], { hasMore: true }))).toBe(0); + expect(linkedThreadPollDelayMs(page([]))).toBe(LINKED_THREAD_ACTIVE_POLL_MS); + expect( + linkedThreadPollDelayMs( + page([], { thread: { threadId, title: "Done", status: "idle", model: "gpt-5" } }), + ), + ).toBe(LINKED_THREAD_IDLE_POLL_MS); + }); +}); + +describe("linkedThreadFailure", () => { + const names = { via: "nucbox", label: "VM" }; + const failure = (reason: string, label: string | null = "fs-17") => + linkedThreadFailure( + { _tag: "PeerLinkThreadReadError", reason, label, message: "From the server." }, + names, + ); + + it("names the environment that has to change, and only retries what can recover", () => { + expect(failure("disabled", null)).toMatchObject({ + title: "Linked environments is off on nucbox", + retryable: false, + }); + expect(failure("expired")).toMatchObject({ + title: "The link from nucbox to fs-17 expired", + retryable: false, + }); + expect(failure("thread_not_found")).toMatchObject({ + title: "This thread is no longer on fs-17", + retryable: false, + }); + expect(failure("incompatible")).toEqual({ + title: "fs-17 needs an update", + detail: "From the server.", + retryable: false, + }); + expect(failure("unreachable")).toEqual({ + title: "fs-17 is not answering nucbox", + detail: "From the server.", + retryable: true, + }); + }); + + it("falls back to the client's name for the linked environment, and explains an old host", () => { + expect(failure("unknown_link", null).title).toBe("nucbox is no longer linked to VM"); + expect(linkedThreadFailure(new Error(""), names)).toMatchObject({ + title: "Could not read this thread through nucbox", + detail: "nucbox may need an update before it can read linked threads.", + retryable: true, + }); + }); +}); + +describe("presentLinkedThreadItem", () => { + const present = ( + type: string, + text: string | null, + extra: Partial> = {}, + ) => presentLinkedThreadItem({ ...item(0, ""), type, text, ...extra }); + + it("shows messages in full and tool work as a row that opens", () => { + expect(present("user_message", "Fix it")).toMatchObject({ kind: "user", text: "Fix it" }); + expect(present("command_execution", "$ vp test\n3 passed")).toEqual({ + kind: "activity", + summary: "$ vp test", + body: "3 passed", + failed: false, + truncated: false, + }); + expect(present("dynamic_tool", "{}", { title: "t3_thread_read" })).toMatchObject({ + summary: "Tool call · t3_thread_read", + body: "{}", + }); + expect(present("error", "Rate limited")).toMatchObject({ summary: "Error", failed: true }); + expect(present("system_notice", "Session restarted")).toMatchObject({ + summary: "Session restarted", + body: null, + }); + }); + + it("hides items with nothing to read", () => { + expect(present("checkpoint", "[]")).toBeNull(); + expect(present("assistant_message", " ")).toBeNull(); + expect(present("system_notice", null)).toBeNull(); + }); +}); + +describe("createLinkedThreadSession", () => { + /** Reads answer when the test says so, and timers run when the test runs them. */ + const harness = (active = { current: true }) => { + const reads: Array<{ + readonly cursor: LinkedThreadCursor; + readonly answer: (result: LinkedThreadReadResult) => Promise; + }> = []; + const timers: Array<{ readonly run: () => void; readonly delayMs: number; live: boolean }> = []; + const session = createLinkedThreadSession({ + read: (cursor) => + new Promise((resolve) => { + reads.push({ + cursor, + answer: async (result) => { + resolve(result); + await Promise.resolve(); + }, + }); + }), + schedule: (run, delayMs) => { + const timer = { run, delayMs, live: true }; + timers.push(timer); + return () => { + timer.live = false; + }; + }, + isActive: () => active.current, + }); + const pending = () => timers.filter((timer) => timer.live); + const fire = () => { + const timer = pending()[0]!; + timer.live = false; + timer.run(); + }; + return { session, reads, pending, fire }; + }; + + it("reads the newest page on open, then follows the thread at its pace", async () => { + const { session, reads, pending, fire } = harness(); + session.subscribe(() => {}); + expect(reads.map((read) => read.cursor)).toEqual([{}]); + await reads[0]!.answer({ + ok: true, + page: page([item(4, "a"), item(5, "b", "running")], { earlierPosition: 4 }), + }); + expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_ACTIVE_POLL_MS]); + + fire(); + expect(reads[1]!.cursor).toEqual({ afterPosition: 4 }); + await reads[1]!.answer({ + ok: true, + page: page([item(5, "b, done")], { + thread: { threadId, title: "Fix the build", status: "completed", model: "gpt-5" }, + }), + }); + expect(session.getSnapshot().transcript?.items.map((entry) => entry.text)).toEqual([ + "a", + "b, done", + ]); + expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_IDLE_POLL_MS]); + }); + + it("pages back without losing what a refresh brought in meanwhile", async () => { + const { session, reads, fire } = harness(); + session.subscribe(() => {}); + await reads[0]!.answer({ ok: true, page: page([item(5, "five")], { earlierPosition: 5 }) }); + fire(); + void session.loadEarlier(); + expect(reads.slice(1).map((read) => read.cursor)).toEqual([ + { afterPosition: 5 }, + { beforePosition: 5 }, + ]); + expect(session.getSnapshot().loadingEarlier).toBe(true); + await reads[2]!.answer({ ok: true, page: page([item(4, "four")]) }); + await reads[1]!.answer({ ok: true, page: page([item(6, "six")]) }); + expect(session.getSnapshot()).toMatchObject({ loadingEarlier: false, error: null }); + expect(session.getSnapshot().transcript?.items.map((entry) => entry.position)).toEqual([ + 4, 5, 6, + ]); + expect(session.getSnapshot().transcript?.earlierPosition).toBeNull(); + }); + + it("stops asking once the view closes or the read cannot recover", async () => { + const closing = harness(); + const close = closing.session.subscribe(() => {}); + await closing.reads[0]!.answer({ ok: true, page: page([item(1, "one")]) }); + close(); + expect(closing.pending()).toEqual([]); + + const late = harness(); + const closeLate = late.session.subscribe(() => {}); + closeLate(); + await late.reads[0]!.answer({ ok: true, page: page([item(1, "one")]) }); + expect(late.session.getSnapshot().transcript).toBeNull(); + expect(late.pending()).toEqual([]); + + const expired = harness(); + expired.session.subscribe(() => {}); + const error = { _tag: "PeerLinkThreadReadError", reason: "expired", label: "VM", message: "" }; + await expired.reads[0]!.answer({ ok: false, error }); + expect(expired.session.getSnapshot().error).toBe(error); + expect(expired.pending()).toEqual([]); + }); + + it("keeps trying an environment that is out of reach, and waits while nobody is looking", async () => { + const active = { current: true }; + const { session, reads, pending, fire } = harness(active); + session.subscribe(() => {}); + await reads[0]!.answer({ + ok: false, + error: { _tag: "PeerLinkThreadReadError", reason: "unreachable", label: "VM", message: "" }, + }); + expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_IDLE_POLL_MS]); + + active.current = false; + fire(); + expect(reads).toHaveLength(1); + active.current = true; + fire(); + expect(reads).toHaveLength(2); + await reads[1]!.answer({ ok: true, page: page([item(1, "one")]) }); + expect(session.getSnapshot()).toMatchObject({ error: null }); + }); +}); diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts new file mode 100644 index 0000000000000..9fc42b3b1c12c --- /dev/null +++ b/packages/client-runtime/src/linkedThread.ts @@ -0,0 +1,381 @@ +import type { EnvironmentId, PeerLinkThreadPage, ThreadId } from "@t3tools/contracts"; +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; + +/** 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"; + +type Page = Pick; + +/** What a linked thread view holds: the pages read so far, as one run of items, oldest first. */ +export type LinkedThreadTranscript = Page; + +/** + * Adds a page to what is shown. An earlier page moves the start back; a later one replaces the + * items it re-reads, which is how an item still being written gets its new text. Every page + * carries the thread's current title and status. + */ +export function mergeLinkedThreadPage( + current: LinkedThreadTranscript | null, + page: Page, + direction: "earlier" | "later", +): LinkedThreadTranscript { + if (current === null) return page; + const byPosition = new Map(current.items.map((item) => [item.position, item])); + for (const item of page.items) byPosition.set(item.position, item); + return { + label: page.label, + thread: page.thread, + items: [...byPosition.values()].sort((left, right) => left.position - right.position), + earlierPosition: direction === "earlier" ? page.earlierPosition : current.earlierPosition, + hasMore: direction === "later" ? page.hasMore : current.hasMore, + }; +} + +const UNSETTLED_ITEM_STATUSES = new Set(["pending", "running", "waiting"]); +/** How far back a refresh re-reads for items still changing, so a stuck one cannot grow it. */ +const REFRESH_WINDOW = 20; + +/** + * The `afterPosition` of the next forward read. While a page left more behind it, that continues + * from the last item. Otherwise it re-reads from the oldest recent item still in progress, since + * its text and status change in place. + */ +export function linkedThreadRefreshCursor(transcript: LinkedThreadTranscript): number { + const last = transcript.items.at(-1)?.position ?? -1; + if (transcript.hasMore) return last; + const unsettled = transcript.items + .slice(-REFRESH_WINDOW) + .find((item) => UNSETTLED_ITEM_STATUSES.has(item.status)); + return unsettled === undefined ? last : unsettled.position - 1; +} + +const ACTIVE_THREAD_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]); + +export const LINKED_THREAD_ACTIVE_POLL_MS = 2_500; +export const LINKED_THREAD_IDLE_POLL_MS = 15_000; + +/** How long an open view waits before its next read: none while catching up, short while the thread works. */ +export function linkedThreadPollDelayMs(transcript: LinkedThreadTranscript): number { + if (transcript.hasMore) return 0; + return ACTIVE_THREAD_STATUSES.has(transcript.thread.status) + ? LINKED_THREAD_ACTIVE_POLL_MS + : LINKED_THREAD_IDLE_POLL_MS; +} + +/** Whether a failed read can succeed later with nothing changed: the linked environment was only out of reach. */ +function isLinkedThreadFailureRetryable(error: unknown): boolean { + if (!hasStringField(error, "_tag") || error._tag !== "PeerLinkThreadReadError") return true; + return 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 = isLinkedThreadFailureRetryable(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, + }; + } +} + +type Item = PeerLinkThreadPage["items"][number]; + +export type LinkedThreadItemPresentation = + | { readonly kind: "user" | "assistant"; readonly text: string; readonly truncated: boolean } + | { + readonly kind: "activity"; + readonly summary: string; + /** What the row opens to show; null when the summary says it all. */ + readonly body: string | null; + readonly failed: boolean; + readonly truncated: boolean; + }; + +const ACTIVITY_LABELS = { + reasoning: msg("Thinking"), + todo_list: msg("Plan"), + file_search: msg("File search"), + web_search: msg("Web search"), + approval_request: msg("Approval request"), + user_input_request: msg("Question"), + subagent: msg("Subagent"), + dynamic_tool: msg("Tool call"), + compaction: msg("Context compacted"), + error: msg("Error"), +} as const; + +const firstLine = (text: string) => { + const end = text.indexOf("\n"); + return end === -1 + ? { head: text, rest: null } + : { head: text.slice(0, end), rest: text.slice(end + 1) }; +}; + +/** + * How a transcript item reads in a linked thread view: messages in full, everything else as a + * one-line row that opens. `null` hides items that say nothing to a reader, such as checkpoints. + */ +export function presentLinkedThreadItem( + item: Pick, + resolve: MFunctionType = mFallback, +): LinkedThreadItemPresentation | null { + const text = item.text ?? ""; + const truncated = item.textTruncated; + if (item.type === "checkpoint") return null; + if (item.type === "user_message") return { kind: "user", text, truncated }; + if (item.type === "assistant_message" || item.type === "proposed_plan") { + return text.trim() === "" ? null : { kind: "assistant", text, truncated }; + } + const failed = item.status === "failed" || item.type === "error"; + if (item.type === "command_execution" || item.type === "file_change") { + const { head, rest } = firstLine(text); + return { kind: "activity", summary: head, body: rest, failed, truncated }; + } + const label = Object.hasOwn(ACTIVITY_LABELS, item.type) + ? resolve(ACTIVITY_LABELS[item.type as keyof typeof ACTIVITY_LABELS]) + : null; + const title = item.title?.trim() || null; + if (label === null && title === null) { + // Notices and the like are their own text. + const { head, rest } = firstLine(text); + return head.trim() === "" + ? null + : { kind: "activity", summary: head, body: rest, failed, truncated }; + } + return { + kind: "activity", + summary: label !== null && title !== null ? `${label} · ${title}` : (label ?? title)!, + body: text.trim() === "" ? null : text, + failed, + truncated, + }; +} + +export const isLinkedThreadWorking = (transcript: LinkedThreadTranscript): boolean => + ACTIVE_THREAD_STATUSES.has(transcript.thread.status); + +export interface LinkedThreadCursor { + readonly beforePosition?: number; + readonly afterPosition?: number; +} + +export type LinkedThreadReadResult = + | { readonly ok: true; readonly page: Page } + | { readonly ok: false; readonly error: unknown }; + +export interface LinkedThreadSessionState { + readonly transcript: LinkedThreadTranscript | null; + /** The last read's failure, cleared by the next read that succeeds. */ + readonly error: unknown; + readonly loadingEarlier: boolean; +} + +/** + * The reads behind one open linked thread view. It reads only while something subscribes, so a + * view that unmounts stops asking the linked environment at once, and while `isActive` says the + * view is not being looked at it only waits. + */ +export function createLinkedThreadSession(options: { + readonly read: (cursor: LinkedThreadCursor) => Promise; + /** Runs `run` after `delayMs` and returns how to cancel it. */ + readonly schedule: (run: () => void, delayMs: number) => () => void; + readonly isActive?: () => boolean; +}) { + let state: LinkedThreadSessionState = { transcript: null, error: null, loadingEarlier: false }; + const listeners = new Set<() => void>(); + // Bumped on stop and restart, so a read that outlives its view changes nothing. + let generation = 0; + let cancelNext: (() => void) | null = null; + + const update = (patch: Partial) => { + state = { ...state, ...patch }; + for (const listener of listeners) listener(); + }; + + const scheduleNext = (delayMs: number) => { + cancelNext?.(); + cancelNext = options.schedule(() => { + cancelNext = null; + if (options.isActive?.() === false) scheduleNext(LINKED_THREAD_ACTIVE_POLL_MS); + else void readLatest(); + }, delayMs); + }; + + const readLatest = async () => { + const run = generation; + cancelNext?.(); + cancelNext = null; + const shown = state.transcript; + const result = await options.read( + shown === null ? {} : { afterPosition: linkedThreadRefreshCursor(shown) }, + ); + if (run !== generation) return; + if (!result.ok) { + update({ error: result.error }); + if (isLinkedThreadFailureRetryable(result.error)) scheduleNext(LINKED_THREAD_IDLE_POLL_MS); + return; + } + // An earlier page may have landed while this read was out. + const transcript = mergeLinkedThreadPage(state.transcript, result.page, "later"); + update({ transcript, error: null }); + scheduleNext(linkedThreadPollDelayMs(transcript)); + }; + + return { + getSnapshot: () => state, + subscribe: (listener: () => void) => { + listeners.add(listener); + if (listeners.size === 1) { + generation += 1; + void readLatest(); + } + return () => { + if (!listeners.delete(listener) || listeners.size > 0) return; + generation += 1; + cancelNext?.(); + cancelNext = null; + state = { ...state, loadingEarlier: false }; + }; + }, + /** Reads the page before the oldest one shown. */ + loadEarlier: async () => { + const before = state.transcript?.earlierPosition ?? null; + if (before === null || state.loadingEarlier) return; + const run = generation; + update({ loadingEarlier: true }); + const result = await options.read({ beforePosition: before }); + if (run !== generation) return; + update( + result.ok + ? { + transcript: mergeLinkedThreadPage(state.transcript, result.page, "earlier"), + loadingEarlier: false, + } + : { error: result.error, loadingEarlier: false }, + ); + }, + /** Reads again now, after a failure the user asked to retry. */ + retry: () => { + if (listeners.size > 0) void readLatest(); + }, + }; +} + +export type LinkedThreadSession = ReturnType; diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 0fc89a1fd2f63..78e66d24192c1 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -516,6 +516,37 @@ it.effect( }), ); +it.effect( + "reads a linked environment's thread with thread read access, not access management", + () => + Effect.gen(function* () { + const registry = yield* setup; + const read = createCommandPermissions(runtime, WS_METHODS.peerLinksReadThread); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthAccessWriteScope], + permissions: [AuthAccessWriteScope], + }), + ); + expect(registry.get(read.permissionAtom(env))).toBe(false); + expect((yield* read.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe( + AuthOrchestrationReadScope, + ); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthOrchestrationReadScope], + permissions: [AuthOrchestrationReadScope], + }), + ); + expect(registry.get(read.permissionAtom(env))).toBe(true); + yield* read.authorize(registry, env); + }), +); + it.effect("requires access management to answer a link request", () => Effect.gen(function* () { const registry = yield* setup; diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 9295bf1b40156..40e780617a0ca 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -30,6 +30,11 @@ export function createPeerLinkEnvironmentAtoms( onSuccess: ({ environmentId }, registry) => Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), }), + /** One page of a linked environment's thread. An open view calls it; nothing is cached. */ + readThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:read-thread", + tag: WS_METHODS.peerLinksReadThread, + }), // An agent's link card. One answer per card at a time. answerRequest: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:answer-request", From 05ff0c8415a420b5a294551dcb8ac6266ad38860 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:01:17 -0800 Subject: [PATCH 03/17] fix(mobile): thread links to a linked-only machine open the read-only sheet A thread link or chip whose environment this app is not connected to, but which the message's environment links to, now opens the LinkedThread sheet through that link instead of a thread screen that cannot load. The decision is resolveLinkedThreadOpen, the same one web and the subagent rows use. Co-Authored-By: Claude Fable 5.2 --- .../components/ComposerEditor.ios.test.tsx | 2 +- apps/mobile/src/components/ComposerEditor.tsx | 9 ++-- .../src/features/threads/ThreadFeed.tsx | 32 ++++++------- .../src/features/threads/useOpenThreadLink.ts | 45 +++++++++++++++++++ apps/mobile/src/lib/filePreview.test.ts | 2 + apps/mobile/src/state/entities.ts | 24 +++++++--- packages/shared/src/threadLinksCopy.ts | 4 +- 7 files changed, 88 insertions(+), 30 deletions(-) create mode 100644 apps/mobile/src/features/threads/useOpenThreadLink.ts 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/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 6165ac6f2fff3..13334de41d97c 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -85,7 +85,7 @@ import { } from "@t3tools/contracts"; import type { ToolCallVisibility } from "@t3tools/contracts/settings"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; -import { hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; +import { hasThreadLinks, hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks"; import { parseComposerContextHref, @@ -296,6 +296,7 @@ import { import { useEnvironmentPresentation } from "../../state/presentation"; import { useThreadSelection } from "../../state/use-thread-selection"; import { useEnvironmentQuery } from "../../state/query"; +import { useLinkedEnvironments } from "../../state/peerLinks"; import { serverEnvironment } from "../../state/server"; import { useModelMentions } from "../../state/model-mentions"; import { composerDocumentAttachmentRecord } from "../../lib/composerContext"; @@ -321,6 +322,7 @@ import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge"; import { fileChipClipboardPath, fileChipMenu, resolveFileChipTarget } from "./fileChipMenu"; import { useFileChipShare } from "./useFileChipShare"; import { useOpenLinkedThread } from "./useOpenLinkedThread"; +import { useOpenThreadLink } from "./useOpenThreadLink"; import { MarkdownImageAvailableWidthContext, ThreadMarkdownImage, @@ -1327,7 +1329,11 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly skills?: ReadonlyArray | undefined; }) { const gt = useGT(); - const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); + const liveMarkdown = useLiveThreadLinkLabels( + props.markdown, + props.environmentId, + useLinkedEnvironments(hasThreadLinks(props.markdown) ? props.environmentId : null), + ); const [quoteSelection, setQuoteSelection] = useState<{ markdown: string; selectors: ReturnType; @@ -2795,9 +2801,12 @@ function UserMessageContent(props: UserMessageContentProps) { const gt = useGT(); const [selected, setSelected] = useState<{ contextId: string; label: string } | null>(null); const navigation = useNavigation(); - const openLinkedThread = useOpenLinkedThread(); const { selectedThread } = useThreadSelection(); - const liveText = useLiveThreadLinkLabels(props.text, props.environmentId); + const liveText = useLiveThreadLinkLabels( + props.text, + props.environmentId, + useLinkedEnvironments(hasThreadLinks(props.text) ? props.environmentId : null), + ); const threadIcons = useThreadChipIcons(props.environmentId, liveText, props.context?.records); const text = replaceComposerContextReferences(liveText, (ref) => { const available = props.context?.records.some((record) => record.contextId === ref.contextId); @@ -2815,10 +2824,8 @@ function UserMessageContent(props: UserMessageContentProps) { return; } if (record?.kind === "thread" && "threadId" in record) { - openLinkedThread({ - environmentId: String(record.environmentId), - threadId: String(record.threadId), - }); + // The feed's link handler decides between the thread itself and its linked read-only view. + props.linkHandlers.onLinkPress?.(hostedThreadLink(record)); return; } const document = composerDocumentAttachmentRecord(record); @@ -3137,7 +3144,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const duoColumns = useNativeWorkspaceColumnsSupported() && isDuoDevice(deviceType); const openPullRequest = useOpenPullRequest(); const navigation = useNavigation(); - const openLinkedThread = useOpenLinkedThread(); + const openThreadLink = useOpenThreadLink(props.environmentId); const openLocalPreview = useOpenLocalPreview(); // Recycling a row disposes its native audio player, so a started clip's row stays rendered. const [retainedMediaRowId, setRetainedMediaRowId] = useState(null); @@ -3431,12 +3438,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } if (parseThreadLinkHref(href)) { const target = resolveLinkedThread(href); - if (target) { - openLinkedThread({ - environmentId: String(target.environmentId), - threadId: String(target.threadId), - }); - } + if (target) openThreadLink(target); return; } const media = resolveMarkdownMediaPreview(href, { diff --git a/apps/mobile/src/features/threads/useOpenThreadLink.ts b/apps/mobile/src/features/threads/useOpenThreadLink.ts new file mode 100644 index 0000000000000..27e5c5ecdea75 --- /dev/null +++ b/apps/mobile/src/features/threads/useOpenThreadLink.ts @@ -0,0 +1,45 @@ +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"; + +/** + * 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 linkedEnvironments = useLinkedEnvironments(viaEnvironmentId); + const { presentationById } = useEnvironments(); + return (thread: ScopedThreadRef, title: string | null = null) => { + const label = linkedEnvironments.get(thread.environmentId); + const own = presentationById.get(thread.environmentId); + if ( + viaEnvironmentId !== null && + label !== undefined && + resolveLinkedThreadOpen({ + environmentId: thread.environmentId, + viaEnvironmentId, + own: own && { connected: own.connection.phase === "connected" }, + linked: true, + }) === "linked" + ) { + navigation.dispatch( + StackActions.push( + "LinkedThread", + linkedThreadRouteParams(thread, { viaEnvironmentId, label }, title), + ), + ); + return; + } + openThread({ + environmentId: String(thread.environmentId), + threadId: String(thread.threadId), + }); + }; +} diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index b93913c00da55..248f375971bb4 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -185,6 +185,8 @@ vi.mock("../state/entities", () => ({ useLiveThreadLinkLabels: (text: string) => text, useThreadChipIcons: () => new Map(), })); +vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => new Map() })); +vi.mock("../features/threads/useOpenThreadLink", () => ({ useOpenThreadLink: () => vi.fn() })); vi.mock("../state/use-thread-selection", () => ({ useThreadSelection: () => ({ selectedThread: null }), })); diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts index 9ca7f1d64496f..4cd6b00b9804f 100644 --- a/apps/mobile/src/state/entities.ts +++ b/apps/mobile/src/state/entities.ts @@ -27,7 +27,7 @@ import { import { relabelThreadLinks } from "@t3tools/shared/threadLinksCopy"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; -import { msg, useMessages } from "gt-react-native"; +import { msg, useGT, useMessages } from "gt-react-native"; import { threadChipTargets } from "../lib/enrichedLinkPresentation"; import { resolveProjectChipIcon } from "../lib/projectIcon"; @@ -239,8 +239,16 @@ export function useSideChats(ref: ScopedThreadRef) { return useAtomValue(environmentThreadShells.sideChatsAtom(ref)); } -export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string { +const NO_LINKED_ENVIRONMENTS: ReadonlyMap = new Map(); + +/** `linked` names the machines `environmentId` links to, whose threads open read-only. */ +export function useLiveThreadLinkLabels( + markdown: string, + environmentId: EnvironmentId, + linked = NO_LINKED_ENVIRONMENTS, +): string { const resolve = useMessages(); + const gt = useGT(); const titles = useAtomValue( hasThreadLinks(markdown) ? threadLinkTitlesAtom(JSON.stringify(threadLinkRefs(markdown, environmentId).map(threadKey))) @@ -249,11 +257,15 @@ export function useLiveThreadLinkLabels(markdown: string, environmentId: Environ return relabelThreadLinks( markdown, environmentId, - (ref) => { + (ref, label) => { const title = titles.get(threadKey(ref)); - return title === FALLBACK_THREAD_TITLE - ? resolve(msg("Thread", { $context: "fallback title of a linked thread" })) - : title; + if (typeof title === "string") return title; + // A thread only the message's environment can reach keeps its written name. + const machine = linked.get(ref.environmentId); + if (machine !== undefined) { + return label?.trim() || gt("Thread on {label}", { label: machine }); + } + return title && resolve(msg("Thread", { $context: "fallback title of a linked thread" })); }, resolve, ); 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 5027347c177f75340132d18148cc879c5a346c67 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:21:42 -0800 Subject: [PATCH 04/17] fix: linked thread view follows review findings - Thread links read through the link whenever this client is not connected to the linked environment, not only when it is absent from the catalog. - A forward read cut short continues from where its page ended, and a successful earlier read clears the last failure. - Delegated task rows use the link the environment still holds. - Mobile stops reading while another screen covers the sheet, and long activity summaries and bodies open in full. - The reader keeps the wrapped failure as cause and builds its own message. - The web sheet starts below the header's panel toggles, so its close button is reachable. - German, French and Swedish name the plan activity a plan. Co-Authored-By: Claude Fable 5.2 --- .../features/threads/LinkedThreadSheet.tsx | 7 +- .../features/threads/ThreadAgentsSheet.tsx | 14 +-- .../threads/thread-subagent-group.tsx | 14 +-- .../threads/threadAgentsPresentation.ts | 14 +-- apps/mobile/src/state/linkedThread.ts | 37 +++++++- apps/server/src/peer/PeerThreadReader.ts | 40 +++++---- .../chat/LinkedThreadSheet.browser.test.tsx | 87 +++++++++++++++++++ .../src/components/chat/LinkedThreadSheet.tsx | 11 ++- .../chat/MarkdownThreadLink.browser.test.tsx | 32 ++++++- .../components/chat/MarkdownThreadLink.tsx | 28 ++++-- ...hreadRelationshipsControl.browser.test.tsx | 1 + apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/state/linkedThreadView.ts | 17 ++-- .../client-runtime/src/linkedThread.test.ts | 51 +++++++++-- packages/client-runtime/src/linkedThread.ts | 24 +++-- packages/contracts/src/peerLink.ts | 2 + 18 files changed, 309 insertions(+), 76 deletions(-) create mode 100644 apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index e772a1c3e4c50..1b617998c1fcc 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -66,7 +66,6 @@ function ActivityRow(props: { {item.summary} ); - if (item.body === null) return summary; return ( {summary} - {open ? ( + {open && item.body !== null ? ( - + {item.body} {item.truncated ? : null} @@ -141,7 +140,7 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { useEnvironments().environments.find( (environment) => environment.environmentId === target.viaEnvironmentId, )?.label ?? gt("this environment"); - const { state, session } = useLinkedThreadSession(target); + const { state, session } = useLinkedThreadSession(target, () => navigation.isFocused()); const { transcript } = state; const label = transcript?.label ?? target.label; const failure = state.error === null ? null : linkedThreadFailure(state.error, { via, label }, m); diff --git a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx index 73ee2d7e07916..0299b688dd86a 100644 --- a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx @@ -24,7 +24,6 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SheetHeader } from "../../components/ui/SheetHeader"; import { AppText as Text } from "../../components/ui/AppText"; import { environmentThreadDetails } from "../../state/threads"; -import { useEnvironments } from "../../state/environments"; import { SubagentRow } from "./SubagentRow"; import { useVisibleSecondClock } from "./use-visible-second-clock"; import { SubagentStopButton } from "./SubagentStopButton"; @@ -32,6 +31,7 @@ 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"; @@ -152,11 +152,13 @@ function AgentRow(props: { }) { const { subagent } = props; const gt = useGT(); - const { presentationById } = useEnvironments(); - const target = subagentThreadTarget(subagent, props.environmentId, (id) => { - const own = presentationById.get(id); - return own && { connected: own.connection.phase === "connected" }; - }); + const reach = useLinkedThreadReach(props.environmentId, [subagent]); + const target = subagentThreadTarget( + subagent, + props.environmentId, + reach.ownConnection, + reach.isLinked, + ); const row = ( diff --git a/apps/mobile/src/features/threads/thread-subagent-group.tsx b/apps/mobile/src/features/threads/thread-subagent-group.tsx index 31c6da8abe14d..0ef23f27a06b4 100644 --- a/apps/mobile/src/features/threads/thread-subagent-group.tsx +++ b/apps/mobile/src/features/threads/thread-subagent-group.tsx @@ -24,12 +24,12 @@ import type { ThreadFeedActivity } from "../../lib/threadActivity"; import { serverEnvironment } from "../../state/server"; import { environmentThreadDetails } from "../../state/threads"; import { subagentCardElapsed } from "./subagent-card-presentation"; -import { useEnvironments } from "../../state/environments"; 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"; @@ -121,7 +121,6 @@ export function ThreadSubagentGroup(props: { environmentThreadDetails.threadAtom(scopeThreadRef(props.environmentId, members[0]!.threadId)), (thread) => thread?.projection.subagents, ); - const { presentationById } = useEnvironments(); const agents = members.map((item) => { const live = liveAgents?.find((agent) => agent.id === item.subagentId); return { @@ -136,6 +135,7 @@ export function ThreadSubagentGroup(props: { modelSelection: live?.modelSelection, }; }); + const reach = useLinkedThreadReach(props.environmentId, agents); const grouped = agents.length > 1; const label = gt("{count, plural, one {{count} subagent} other {{count} subagents}}", { count: agents.length, @@ -200,10 +200,12 @@ export function ThreadSubagentGroup(props: { {agents.map((agent) => { // A task in a linked environment opens there, if this app is connected to it. - const target = subagentThreadTarget(agent, props.environmentId, (id) => { - const own = presentationById.get(id); - return own && { connected: own.connection.phase === "connected" }; - }); + const target = subagentThreadTarget( + agent, + props.environmentId, + reach.ownConnection, + reach.isLinked, + ); return ( , environmentId: EnvironmentId, ownConnection: (environmentId: EnvironmentId) => { readonly connected: boolean } | undefined, + /** Whether `environmentId` still holds a link to the given environment. */ + isLinked: (environmentId: EnvironmentId) => boolean, ): SubagentThreadTarget | null { if (subagent.childThreadId !== null) { return { environmentId, threadId: subagent.childThreadId }; @@ -63,11 +67,11 @@ export function subagentThreadTarget( environmentId: remote.environmentId, viaEnvironmentId: environmentId, own: ownConnection(remote.environmentId), - linked: true, + linked: isLinked(remote.environmentId), }); - return open === "linked" - ? { ...target, linked: { viaEnvironmentId: environmentId, label: remote.label } } - : target; + return open === "direct" + ? target + : { ...target, linked: { viaEnvironmentId: environmentId, label: remote.label } }; } function rowTitle( diff --git a/apps/mobile/src/state/linkedThread.ts b/apps/mobile/src/state/linkedThread.ts index ac59dffa358d4..81230b35a2dc9 100644 --- a/apps/mobile/src/state/linkedThread.ts +++ b/apps/mobile/src/state/linkedThread.ts @@ -3,17 +3,46 @@ import { type LinkedThreadTarget, } from "@t3tools/client-runtime/linked-thread"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts"; import { useState, useSyncExternalStore } from "react"; import { AppState } from "react-native"; -import { peerLinkEnvironment } from "./peerLinks"; +import { useEnvironments } from "./environments"; +import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks"; import { useAtomCommand } from "./use-atom-command"; +/** + * What places a delegated task's thread: this app's own connections, and the links `environmentId` + * holds. Links are listed only while a task runs somewhere this app is not connected to. + */ +export function useLinkedThreadReach( + environmentId: EnvironmentId, + subagents: ReadonlyArray>, +) { + const { presentationById } = useEnvironments(); + const ownConnection = (id: EnvironmentId) => { + const own = presentationById.get(id); + return own && { connected: own.connection.phase === "connected" }; + }; + const links = useLinkedEnvironments( + subagents.some( + (subagent) => + subagent.childThreadId === null && + subagent.remoteChild !== undefined && + ownConnection(subagent.remoteChild.environmentId)?.connected !== true, + ) + ? environmentId + : null, + ); + return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) }; +} + /** * The transcript of `target`, read through the environment that links to it. Reads start when the - * calling screen mounts, stop when it unmounts, and wait while the app is in the background. + * calling screen mounts, stop when it unmounts, and wait while the app is in the background or + * `isFocused` says another screen covers this one. */ -export function useLinkedThreadSession(target: LinkedThreadTarget) { +export function useLinkedThreadSession(target: LinkedThreadTarget, isFocused: () => boolean) { const read = useAtomCommand(peerLinkEnvironment.readThread, { reportFailure: false, reportDefect: false, @@ -33,7 +62,7 @@ export function useLinkedThreadSession(target: LinkedThreadTarget) { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); }, - isActive: () => AppState.currentState === "active", + isActive: () => AppState.currentState === "active" && isFocused(), }), ); const state = useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot); diff --git a/apps/server/src/peer/PeerThreadReader.ts b/apps/server/src/peer/PeerThreadReader.ts index 07ca86f0237da..c247039d39a4a 100644 --- a/apps/server/src/peer/PeerThreadReader.ts +++ b/apps/server/src/peer/PeerThreadReader.ts @@ -43,12 +43,26 @@ export class PeerThreadReader extends Context.Service< } >()("t3/peer/PeerThreadReader") {} -const reasonOf = (failure: OrchestratorMcpFailure): PeerLinkThreadReadError["reason"] => - failure.code === "thread_not_found" - ? "thread_not_found" - : failure.code === "capability_denied" || failure.code === "invalid_request" - ? "rejected" - : "unreachable"; +/** The linked environment's refusal or silence, as the client that asked hears it. */ +const fromCallFailure = (failure: OrchestratorMcpFailure, label: string) => { + const reason = + failure.code === "thread_not_found" + ? "thread_not_found" + : failure.code === "capability_denied" || failure.code === "invalid_request" + ? "rejected" + : "unreachable"; + return new PeerLinkThreadReadError({ + reason, + label, + message: + reason === "thread_not_found" + ? `That thread is no longer on ${label}.` + : reason === "rejected" + ? `${label} refused the read. Its link may have been revoked there; link it again.` + : `${label} did not answer.`, + cause: failure, + }); +}; const make = Effect.gen(function* () { const links = yield* PeerLinks.PeerLinks; @@ -69,7 +83,8 @@ const make = Effect.gen(function* () { new PeerLinkThreadReadError({ reason: "unreachable", label: null, - message: error.message, + message: "This environment could not read its links.", + cause: error, }), ), ); @@ -111,16 +126,7 @@ const make = Effect.gen(function* () { limits: CLIENT_READ_LIMITS, success: OrchestratorMcpThreadReadResult, }) - .pipe( - Effect.mapError( - (failure) => - new PeerLinkThreadReadError({ - reason: reasonOf(failure), - label, - message: failure.message, - }), - ), - ); + .pipe(Effect.mapError((failure) => fromCallFailure(failure, label))); // A version that only reads forward ignores `beforePosition` and answers from the start. if (backwards && page.earlierPosition === undefined) { return yield* new PeerLinkThreadReadError({ diff --git a/apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx b/apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx new file mode 100644 index 0000000000000..0b82c7ad6f182 --- /dev/null +++ b/apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx @@ -0,0 +1,87 @@ +import { RegistryContext } from "@effect/atom-react"; +import { mergeLinkedThreadPage } from "@t3tools/client-runtime/linked-thread"; +import { EnvironmentId, type PeerLinkThreadPage, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { Atom, AtomRegistry } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import "../../index.css"; + +import { LinkedThreadSheet } from "./LinkedThreadSheet"; + +const state = vi.hoisted(() => ({ view: null as unknown, transcript: null as unknown })); +vi.mock(import("../../state/linkedThreadView"), async () => { + const reactivity = await import("effect/reactivity"); + state.view = reactivity.Atom.make(null); + return { + linkedThreadViewAtom: state.view as never, + useOpenLinkedThread: () => () => {}, + useLinkedThreadOpener: () => null, + useLinkedThreadSession: () => + ({ + state: { transcript: state.transcript, error: null, loadingEarlier: false }, + session: { retry: () => {}, loadEarlier: async () => {} }, + }) as never, + }; +}); + +const threadId = ThreadId.make("thread:box"); +const item = ( + position: number, + type: string, + text: string, +): PeerLinkThreadPage["items"][number] => ({ + position, + visibility: "local", + sourceThreadId: threadId, + itemId: TurnItemId.make(`item:${position}`), + runId: null, + messageId: null, + createdBy: null, + creationSource: null, + type, + status: "completed", + title: null, + text, + textTruncated: false, + updatedAt: "2026-11-19T00:00:00.000Z", +}); + +it("shows the user's message and a fenced block's code, with a close button", async () => { + const target = { + viaEnvironmentId: EnvironmentId.make("laptop"), + environmentId: EnvironmentId.make("box"), + threadId, + label: "Box", + title: null, + }; + state.transcript = mergeLinkedThreadPage( + null, + { + label: "Box", + thread: { threadId, title: "Fix flaky checkout test", status: "idle", model: "showcase" }, + items: [ + item(0, "user_message", "Find out why the checkout test is flaky"), + item(1, "command_execution", "$ Preparing workspace\nWorkspace preparation completed."), + item(2, "assistant_message", "## Done\n\n```ts\nclamp(12, 0, 10); // 10\n```\n\nThe end."), + ], + earlierPosition: null, + hasMore: false, + }, + "later", + ); + const registry = AtomRegistry.make(); + const view = state.view as Atom.Writable; + registry.set(view, target); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + await using _screen = await render( + + + , + ); + await expect.element(page.getByText("Find out why the checkout test is flaky")).toBeVisible(); + await expect.element(page.getByText("clamp(12, 0, 10); // 10")).toBeVisible(); + await page.getByRole("button", { name: "Close" }).click(); + expect(registry.get(view)).toBeNull(); +}); diff --git a/apps/web/src/components/chat/LinkedThreadSheet.tsx b/apps/web/src/components/chat/LinkedThreadSheet.tsx index ca14902052b82..2593cbed85a50 100644 --- a/apps/web/src/components/chat/LinkedThreadSheet.tsx +++ b/apps/web/src/components/chat/LinkedThreadSheet.tsx @@ -81,7 +81,10 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { <> - {transcript?.thread.title || target.title || gt("Thread on {label}", { label })} + {/* Clear of the close button in the sheet's corner. */} + + {transcript?.thread.title || target.title || gt("Thread on {label}", { label })} + @@ -170,7 +173,11 @@ export function LinkedThreadSheet() { if (!open) setTarget(null); }} > - + {/* The header's panel toggles float above sheets, so the sheet starts below them. */} + {target === null ? null : ( ({ reply: null as unknown, remote: null as unknown, linked: new Map(), + connected: [] as Array, openedLinked: [] as Array, })); vi.mock(import("../../state/entities"), () => ({ @@ -27,7 +28,9 @@ 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) => @@ -58,6 +61,7 @@ function setup() { >(AsyncResult.initial()); state.reply = reply; state.linked = new Map(); + state.connected = ["environment", "remote"]; state.openedLinked = []; state.remote = { environmentId: EnvironmentId.make("remote"), @@ -170,12 +174,15 @@ it("names a thread on a machine this client has no connection to, without waitin await expect.element(screen.getByRole("link")).not.toBeInTheDocument(); }); -it("opens a thread on a machine only this environment links to as a read through it", async () => { +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([["linked-vm", "fs-17"]]); + state.linked = new Map([[linkedId, "fs-17"]]); const environmentId = EnvironmentId.make("environment"); - const link = { environmentId: EnvironmentId.make("linked-vm"), threadId: ThreadId.make("there") }; + const link = { environmentId: EnvironmentId.make(linkedId), threadId: ThreadId.make("there") }; await using screen = await render( @@ -187,3 +194,22 @@ it("opens a thread on a machine only this environment links to as a read through ]); expect(screen.router?.state.location.pathname).toBe("/"); }); + +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(); + expect(state.openedLinked).toEqual([]); +}); diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 917d36f7bddd1..9ed59f795a956 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -8,10 +8,11 @@ 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 { useOpenLinkedThread } from "../../state/linkedThreadView"; import { useLinkedEnvironments } from "../../state/peerLinks"; import { orchestrationEnvironment } from "../../state/orchestration"; @@ -32,10 +33,25 @@ export function MarkdownThreadLink(props: { 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( + written !== null || connected || writtenRef.environmentId === props.environmentId + ? null + : props.environmentId, + ).get(writtenRef.environmentId); + const linked = + written === null && + 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({ @@ -63,12 +79,8 @@ export function MarkdownThreadLink(props: { : null; const remote = useThreadShell(remoteRef); const resolved = target ?? (remoteRef && remote ? { ref: remoteRef, metadata: remote } : null); - // A thread on a machine this client cannot reach still reads through the one that links to it. - const linkedLabel = useLinkedEnvironments(reachable ? null : props.environmentId).get( - writtenRef.environmentId, - ); const openLinked = useOpenLinkedThread(); - if (resolved === null && linkedLabel !== undefined) { + if (resolved === null && linked && linkedLabel !== undefined) { const title = props.label ?? gt("Thread on {label}", { label: linkedLabel }); return ( diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 2d8e67ed294ed..914adf19777ad 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -47,6 +47,7 @@ vi.mock(import("../../state/environments"), () => ({ })); vi.mock(import("../../state/peerLinks"), () => ({ peerLinkEnvironment: { readThread: {} } as never, + useLinkedEnvironments: (() => new Map()) as never, })); vi.mock(import("../../lib/archivedThreadsState"), () => ({ useArchivedThreadSnapshots: (() => ({ diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index e65afae756622..6decd3eae763d 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -96,7 +96,7 @@ "f7870ef3a4828ab1": "{label} braucht ein Update", "eabbf064657519ee": "{label} antwortet {via} nicht", "6ab96e26bda35288": "Denkt nach", - "67733c48eaaec73a": "Tarif", + "67733c48eaaec73a": "Plan", "75aaf70eabf15f4b": "Dateisuche", "ac511f991a3c1fab": "Websuche", "5e30649065b60d94": "Genehmigungsanfrage", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 2d19651e0f370..fe84a31c3ae6c 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -96,7 +96,7 @@ "f7870ef3a4828ab1": "{label} a besoin d’une mise à jour", "eabbf064657519ee": "{label} ne répond pas à {via}", "6ab96e26bda35288": "Réflexion", - "67733c48eaaec73a": "Forfait", + "67733c48eaaec73a": "Plan", "75aaf70eabf15f4b": "Recherche de fichiers", "ac511f991a3c1fab": "Recherche web", "5e30649065b60d94": "Demande d’approbation", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 06363ce596933..cb6480f80562c 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -96,7 +96,7 @@ "f7870ef3a4828ab1": "{label} behöver uppdateras", "eabbf064657519ee": "{label} svarar inte {via}", "6ab96e26bda35288": "Tänker", - "67733c48eaaec73a": "Abonnemang", + "67733c48eaaec73a": "Plan", "75aaf70eabf15f4b": "Filsökning", "ac511f991a3c1fab": "Webbsökning", "5e30649065b60d94": "Begäran om godkännande", diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index bf27c529622d9..f5066585af1e1 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -15,7 +15,7 @@ import { useState, useSyncExternalStore } from "react"; import { getDocumentActivity } from "../lib/documentActivity"; import { buildThreadRouteParams } from "../threadRoutes"; import { useEnvironment } from "./environments"; -import { peerLinkEnvironment } from "./peerLinks"; +import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks"; import { useAtomCommand } from "./use-atom-command"; /** The linked environment's thread the read-only view shows, or none. */ @@ -30,7 +30,9 @@ export function useOpenLinkedThread(): (target: LinkedThreadTarget) => void { /** * How a click opens a thread that a thread in `viaEnvironmentId` says is on a linked environment: - * in place when this client is connected there itself, else read-only through the link. + * in place when this client is connected there itself, else read-only through the link. Once the + * link is gone a saved environment opens in place, where the client can reconnect to it; with + * neither, the read-only view says what to link again. */ export function useLinkedThreadOpener( viaEnvironmentId: EnvironmentId, @@ -42,17 +44,20 @@ export function useLinkedThreadOpener( } | undefined, title: string | null, -): { readonly mode: LinkedThreadOpen; readonly open: () => void } | null { +): { readonly mode: Exclude; readonly open: () => void } | null { const navigate = useNavigate(); const openLinked = useOpenLinkedThread(); 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 mode = resolveLinkedThreadOpen({ + const resolved = resolveLinkedThreadOpen({ environmentId: thread.environmentId, viaEnvironmentId, - own: own === null ? undefined : { connected: own.connection.phase === "connected" }, - linked: true, + own: own === null ? undefined : { connected }, + linked: links.has(thread.environmentId), }); + const mode = resolved === "direct" ? "direct" : "linked"; return { mode, open: () => { diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index c33862372bf0a..01d617820463a 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -83,7 +83,11 @@ describe("resolveLinkedThreadOpen", () => { }); describe("mergeLinkedThreadPage", () => { - const newest = page([item(10, "ten"), item(11, "eleven", "running")], { earlierPosition: 10 }); + const newest = mergeLinkedThreadPage( + null, + page([item(10, "ten"), item(11, "eleven", "running")], { earlierPosition: 10 }), + "later", + ); it("moves the start back with an earlier page and keeps the forward state", () => { const merged = mergeLinkedThreadPage( @@ -112,29 +116,51 @@ describe("mergeLinkedThreadPage", () => { }); describe("linkedThreadRefreshCursor", () => { + const linkedThreadRefreshCursorOf = (shown: PeerLinkThreadPage) => + linkedThreadRefreshCursor(mergeLinkedThreadPage(null, shown, "later")); it("reads after the last item once everything shown has settled", () => { - expect(linkedThreadRefreshCursor(page([item(4, "a"), item(5, "b")]))).toBe(5); - expect(linkedThreadRefreshCursor(page([]))).toBe(-1); + expect(linkedThreadRefreshCursorOf(page([item(4, "a"), item(5, "b")]))).toBe(5); + expect(linkedThreadRefreshCursorOf(page([]))).toBe(-1); }); it("re-reads from an item that is still being written", () => { expect( - linkedThreadRefreshCursor(page([item(4, "a"), item(5, "b", "running"), item(6, "c")])), + linkedThreadRefreshCursorOf(page([item(4, "a"), item(5, "b", "running"), item(6, "c")])), ).toBe(4); }); it("continues from the last item while a page left more behind it", () => { expect( - linkedThreadRefreshCursor(page([item(4, "a", "running"), item(5, "b")], { hasMore: true })), + linkedThreadRefreshCursorOf(page([item(4, "a", "running"), item(5, "b")], { hasMore: true })), ).toBe(5); }); + it("continues from where a page cut short ended, not from the items it left untouched", () => { + const shown = mergeLinkedThreadPage( + mergeLinkedThreadPage( + null, + page([item(80, "a", "running"), item(81, "b"), item(99, "z")]), + "later", + ), + page([item(80, "a, done")], { hasMore: true }), + "later", + ); + expect(shown.items.map((entry) => entry.position)).toEqual([80, 81, 99]); + expect(linkedThreadRefreshCursor(shown)).toBe(80); + // An earlier page leaves the forward continuation alone. + const earlier = mergeLinkedThreadPage(shown, page([item(79, "y")]), "earlier"); + expect(linkedThreadRefreshCursor(earlier)).toBe(80); + expect( + linkedThreadRefreshCursor(mergeLinkedThreadPage(earlier, page([item(81, "b2")]), "later")), + ).toBe(99); + }); + it("stops re-reading an item that stays unsettled once it is far behind", () => { const items = [ item(0, "stuck", "waiting"), ...Array.from({ length: 30 }, (_, i) => item(i + 1, "x")), ]; - expect(linkedThreadRefreshCursor(page(items))).toBe(30); + expect(linkedThreadRefreshCursorOf(page(items))).toBe(30); }); }); @@ -309,6 +335,19 @@ describe("createLinkedThreadSession", () => { expect(session.getSnapshot().transcript?.earlierPosition).toBeNull(); }); + it("forgets a failed earlier read once the next one succeeds", async () => { + const { session, reads } = harness(); + session.subscribe(() => {}); + await reads[0]!.answer({ ok: true, page: page([item(5, "five")], { earlierPosition: 5 }) }); + void session.loadEarlier(); + await reads[1]!.answer({ ok: false, error: new Error("offline") }); + expect(session.getSnapshot()).toMatchObject({ loadingEarlier: false }); + expect(session.getSnapshot().error).not.toBeNull(); + void session.loadEarlier(); + await reads[2]!.answer({ ok: true, page: page([item(4, "four")]) }); + expect(session.getSnapshot().error).toBeNull(); + }); + it("stops asking once the view closes or the read cannot recover", async () => { const closing = harness(); const close = closing.session.subscribe(() => {}); diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 9fc42b3b1c12c..3f1bd0ce0595e 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -44,7 +44,16 @@ const hasStringField = (value: unknown, key: K): value is Reco type Page = Pick; /** What a linked thread view holds: the pages read so far, as one run of items, oldest first. */ -export type LinkedThreadTranscript = Page; +export type LinkedThreadTranscript = Page & { + /** + * Where the next forward read continues while the last one left more behind it, else null. A + * page cut short can end before items already shown, so this is not the last item's position. + */ + readonly continueAfter: number | null; +}; + +const continuationOf = (page: Page, fallback: number | null) => + page.hasMore ? (page.items.at(-1)?.position ?? fallback) : null; /** * Adds a page to what is shown. An earlier page moves the start back; a later one replaces the @@ -56,7 +65,7 @@ export function mergeLinkedThreadPage( page: Page, direction: "earlier" | "later", ): LinkedThreadTranscript { - if (current === null) return page; + if (current === null) return { ...page, continueAfter: continuationOf(page, null) }; const byPosition = new Map(current.items.map((item) => [item.position, item])); for (const item of page.items) byPosition.set(item.position, item); return { @@ -65,6 +74,8 @@ export function mergeLinkedThreadPage( items: [...byPosition.values()].sort((left, right) => left.position - right.position), earlierPosition: direction === "earlier" ? page.earlierPosition : current.earlierPosition, hasMore: direction === "later" ? page.hasMore : current.hasMore, + continueAfter: + direction === "later" ? continuationOf(page, current.continueAfter) : current.continueAfter, }; } @@ -74,12 +85,12 @@ const REFRESH_WINDOW = 20; /** * The `afterPosition` of the next forward read. While a page left more behind it, that continues - * from the last item. Otherwise it re-reads from the oldest recent item still in progress, since + * from where the page ended. Otherwise it re-reads from the oldest recent item still in progress, since * its text and status change in place. */ export function linkedThreadRefreshCursor(transcript: LinkedThreadTranscript): number { + if (transcript.continueAfter !== null) return transcript.continueAfter; const last = transcript.items.at(-1)?.position ?? -1; - if (transcript.hasMore) return last; const unsettled = transcript.items .slice(-REFRESH_WINDOW) .find((item) => UNSETTLED_ITEM_STATUSES.has(item.status)); @@ -92,7 +103,7 @@ export const LINKED_THREAD_ACTIVE_POLL_MS = 2_500; export const LINKED_THREAD_IDLE_POLL_MS = 15_000; /** How long an open view waits before its next read: none while catching up, short while the thread works. */ -export function linkedThreadPollDelayMs(transcript: LinkedThreadTranscript): number { +export function linkedThreadPollDelayMs(transcript: Pick): number { if (transcript.hasMore) return 0; return ACTIVE_THREAD_STATUSES.has(transcript.thread.status) ? LINKED_THREAD_ACTIVE_POLL_MS @@ -268,7 +279,7 @@ export function presentLinkedThreadItem( }; } -export const isLinkedThreadWorking = (transcript: LinkedThreadTranscript): boolean => +export const isLinkedThreadWorking = (transcript: Pick): boolean => ACTIVE_THREAD_STATUSES.has(transcript.thread.status); export interface LinkedThreadCursor { @@ -366,6 +377,7 @@ export function createLinkedThreadSession(options: { result.ok ? { transcript: mergeLinkedThreadPage(state.transcript, result.page, "earlier"), + error: null, loadingEarlier: false, } : { error: result.error, loadingEarlier: false }, diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index 949f57bc8c392..0654f3a36f176 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -134,6 +134,8 @@ export class PeerLinkThreadReadError extends Schema.TaggedError Date: Thu, 19 Nov 2026 15:32:38 -0800 Subject: [PATCH 05/17] fix(mobile): a thread chip opens the exact thread it recorded Co-Authored-By: Claude Fable 5.2 --- apps/mobile/src/features/threads/ThreadFeed.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 13334de41d97c..3e89a8587ca4a 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -2801,6 +2801,7 @@ function UserMessageContent(props: UserMessageContentProps) { const gt = useGT(); const [selected, setSelected] = useState<{ contextId: string; label: string } | null>(null); const navigation = useNavigation(); + const openThreadLink = useOpenThreadLink(props.environmentId); const { selectedThread } = useThreadSelection(); const liveText = useLiveThreadLinkLabels( props.text, @@ -2824,8 +2825,7 @@ function UserMessageContent(props: UserMessageContentProps) { return; } if (record?.kind === "thread" && "threadId" in record) { - // The feed's link handler decides between the thread itself and its linked read-only view. - props.linkHandlers.onLinkPress?.(hostedThreadLink(record)); + openThreadLink(scopeThreadRef(record.environmentId, record.threadId)); return; } const document = composerDocumentAttachmentRecord(record); From f48afb7443e6ed28fa8616c2506202427c592322 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:43:21 -0800 Subject: [PATCH 06/17] fix(client-runtime): a linked thread read that a newer one overtook changes nothing Co-Authored-By: Claude Fable 5.2 --- packages/client-runtime/src/linkedThread.test.ts | 9 +++++++++ packages/client-runtime/src/linkedThread.ts | 6 +++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 01d617820463a..4ac87ada7207e 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -315,6 +315,15 @@ describe("createLinkedThreadSession", () => { expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_IDLE_POLL_MS]); }); + it("ignores a read that a newer one overtook", async () => { + const { session, reads } = harness(); + session.subscribe(() => {}); + session.retry(); + await reads[1]!.answer({ ok: true, page: page([item(4, "new")]) }); + await reads[0]!.answer({ ok: true, page: page([item(4, "old")]) }); + expect(session.getSnapshot().transcript?.items.map((entry) => entry.text)).toEqual(["new"]); + }); + it("pages back without losing what a refresh brought in meanwhile", async () => { const { session, reads, fire } = harness(); session.subscribe(() => {}); diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 3f1bd0ce0595e..a978dc51196e9 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -329,15 +329,19 @@ export function createLinkedThreadSession(options: { }, delayMs); }; + // Only the newest forward read applies: a retry can start one while another is still out. + let latestRead = 0; + const readLatest = async () => { const run = generation; + const read = ++latestRead; cancelNext?.(); cancelNext = null; const shown = state.transcript; const result = await options.read( shown === null ? {} : { afterPosition: linkedThreadRefreshCursor(shown) }, ); - if (run !== generation) return; + if (run !== generation || read !== latestRead) return; if (!result.ok) { update({ error: result.error }); if (isLinkedThreadFailureRetryable(result.error)) scheduleNext(LINKED_THREAD_IDLE_POLL_MS); From c50f061cb84d6d3b15aef5f651dacdd789e25bcc Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:49:51 -0800 Subject: [PATCH 07/17] fix(web): a thread cached from a dropped connection still reads through the link Co-Authored-By: Claude Fable 5.2 --- .../chat/MarkdownThreadLink.browser.test.tsx | 26 ++++++++++++++++++- .../components/chat/MarkdownThreadLink.tsx | 13 +++++----- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx index 87be973c2f85a..c67a41cbef06a 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx @@ -10,13 +10,18 @@ import { MarkdownThreadLink } from "./MarkdownThreadLink"; const state = vi.hoisted(() => ({ reply: null as unknown, remote: null as unknown, + cached: null as unknown, linked: new Map(), connected: [] as Array, openedLinked: [] 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") }] @@ -61,6 +66,7 @@ function setup() { >(AsyncResult.initial()); state.reply = reply; state.linked = new Map(); + state.cached = null; state.connected = ["environment", "remote"]; state.openedLinked = []; state.remote = { @@ -195,6 +201,24 @@ it.for([ 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(state.openedLinked).toEqual([ + { 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() }; diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 9ed59f795a956..e7eef372d5b7c 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -39,12 +39,10 @@ export function MarkdownThreadLink(props: { 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( - written !== null || connected || writtenRef.environmentId === props.environmentId - ? null - : props.environmentId, + 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. const linked = - written === null && resolveLinkedThreadOpen({ environmentId: writtenRef.environmentId, viaEnvironmentId: props.environmentId, @@ -80,8 +78,9 @@ export function MarkdownThreadLink(props: { const remote = useThreadShell(remoteRef); const resolved = target ?? (remoteRef && remote ? { ref: remoteRef, metadata: remote } : null); const openLinked = useOpenLinkedThread(); - if (resolved === null && linked && linkedLabel !== undefined) { - const title = props.label ?? gt("Thread on {label}", { label: linkedLabel }); + if (linked && linkedLabel !== undefined) { + const knownTitle = props.label ?? written?.title ?? null; + const title = knownTitle ?? gt("Thread on {label}", { label: linkedLabel }); return ( From 4b8a8cf509b6303bf367dfc2192c1e42e6b47089 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:54:10 -0800 Subject: [PATCH 08/17] fix(client-runtime): a linked thread view opened out of sight waits to read Co-Authored-By: Claude Fable 5.2 --- packages/client-runtime/src/linkedThread.test.ts | 10 ++++++++++ packages/client-runtime/src/linkedThread.ts | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 4ac87ada7207e..8022e69bf808c 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -315,6 +315,16 @@ describe("createLinkedThreadSession", () => { expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_IDLE_POLL_MS]); }); + it("waits to read a view that opens while nobody is looking", () => { + const active = { current: false }; + const { session, reads, fire } = harness(active); + session.subscribe(() => {}); + expect(reads).toEqual([]); + active.current = true; + fire(); + expect(reads.map((read) => read.cursor)).toEqual([{}]); + }); + it("ignores a read that a newer one overtook", async () => { const { session, reads } = harness(); session.subscribe(() => {}); diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index a978dc51196e9..18f7efb48e30e 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -359,7 +359,8 @@ export function createLinkedThreadSession(options: { listeners.add(listener); if (listeners.size === 1) { generation += 1; - void readLatest(); + if (options.isActive?.() === false) scheduleNext(LINKED_THREAD_ACTIVE_POLL_MS); + else void readLatest(); } return () => { if (!listeners.delete(listener) || listeners.size > 0) return; From 9cca3de69a0a3eb2d02e6530166dfd5f705e883a Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:59:04 -0800 Subject: [PATCH 09/17] test(web): drop the linked thread sheet smoke test It guarded two defects that a live run showed were not defects. Co-Authored-By: Claude Fable 5.2 --- .../chat/LinkedThreadSheet.browser.test.tsx | 87 ------------------- 1 file changed, 87 deletions(-) delete mode 100644 apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx diff --git a/apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx b/apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx deleted file mode 100644 index 0b82c7ad6f182..0000000000000 --- a/apps/web/src/components/chat/LinkedThreadSheet.browser.test.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { RegistryContext } from "@effect/atom-react"; -import { mergeLinkedThreadPage } from "@t3tools/client-runtime/linked-thread"; -import { EnvironmentId, type PeerLinkThreadPage, ThreadId, TurnItemId } from "@t3tools/contracts"; -import { Atom, AtomRegistry } from "effect/reactivity"; -import { expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { LinkedThreadSheet } from "./LinkedThreadSheet"; - -const state = vi.hoisted(() => ({ view: null as unknown, transcript: null as unknown })); -vi.mock(import("../../state/linkedThreadView"), async () => { - const reactivity = await import("effect/reactivity"); - state.view = reactivity.Atom.make(null); - return { - linkedThreadViewAtom: state.view as never, - useOpenLinkedThread: () => () => {}, - useLinkedThreadOpener: () => null, - useLinkedThreadSession: () => - ({ - state: { transcript: state.transcript, error: null, loadingEarlier: false }, - session: { retry: () => {}, loadEarlier: async () => {} }, - }) as never, - }; -}); - -const threadId = ThreadId.make("thread:box"); -const item = ( - position: number, - type: string, - text: string, -): PeerLinkThreadPage["items"][number] => ({ - position, - visibility: "local", - sourceThreadId: threadId, - itemId: TurnItemId.make(`item:${position}`), - runId: null, - messageId: null, - createdBy: null, - creationSource: null, - type, - status: "completed", - title: null, - text, - textTruncated: false, - updatedAt: "2026-11-19T00:00:00.000Z", -}); - -it("shows the user's message and a fenced block's code, with a close button", async () => { - const target = { - viaEnvironmentId: EnvironmentId.make("laptop"), - environmentId: EnvironmentId.make("box"), - threadId, - label: "Box", - title: null, - }; - state.transcript = mergeLinkedThreadPage( - null, - { - label: "Box", - thread: { threadId, title: "Fix flaky checkout test", status: "idle", model: "showcase" }, - items: [ - item(0, "user_message", "Find out why the checkout test is flaky"), - item(1, "command_execution", "$ Preparing workspace\nWorkspace preparation completed."), - item(2, "assistant_message", "## Done\n\n```ts\nclamp(12, 0, 10); // 10\n```\n\nThe end."), - ], - earlierPosition: null, - hasMore: false, - }, - "later", - ); - const registry = AtomRegistry.make(); - const view = state.view as Atom.Writable; - registry.set(view, target); - using _registry = { [Symbol.dispose]: () => registry.dispose() }; - await using _screen = await render( - - - , - ); - await expect.element(page.getByText("Find out why the checkout test is flaky")).toBeVisible(); - await expect.element(page.getByText("clamp(12, 0, 10); // 10")).toBeVisible(); - await page.getByRole("button", { name: "Close" }).click(); - expect(registry.get(view)).toBeNull(); -}); From 237e150ea39a94dcbf1c26cace6cf631365685c4 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:44:48 -0800 Subject: [PATCH 10/17] feat(web): a linked environment's thread opens as a right panel tab The read-only view of a thread on a linked environment was a modal sheet over the chat. It is now a tab in the right panel of the thread you are in, so you keep working while it sits beside. Reads wait while the tab or panel is not showing and stop when the tab closes. Co-Authored-By: Claude Fable 5.2 --- apps/web/src/closedViewStore.test.ts | 6 + apps/web/src/closedViewStore.ts | 3 + apps/web/src/components/ChatMarkdown.tsx | 7 +- apps/web/src/components/RightPanelTabs.tsx | 8 ++ ...edThreadSheet.tsx => LinkedThreadPane.tsx} | 133 +++++++++--------- .../chat/MarkdownThreadLink.browser.test.tsx | 45 +++--- .../components/chat/MarkdownThreadLink.tsx | 14 +- .../chat/RightPanelSurfaceContent.tsx | 10 ++ .../chat/ThreadRelationshipsControl.tsx | 9 +- .../src/components/chat/V2LifecycleRow.tsx | 2 +- 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 +- 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/routes/__root.tsx | 2 - apps/web/src/state/linkedThreadView.ts | 57 ++++---- docs/user/remote-access.md | 3 +- 27 files changed, 388 insertions(+), 135 deletions(-) rename apps/web/src/components/chat/{LinkedThreadSheet.tsx => LinkedThreadPane.tsx} (65%) create mode 100644 apps/web/src/linkedThreadSurface.ts diff --git a/apps/web/src/closedViewStore.test.ts b/apps/web/src/closedViewStore.test.ts index 3e2cacc57e736..6b12b53330825 100644 --- a/apps/web/src/closedViewStore.test.ts +++ b/apps/web/src/closedViewStore.test.ts @@ -60,6 +60,12 @@ describe("closedViewStore", () => { threadRef: refA, surface: { kind: "side-chat", id: "side-chat:x" }, }, + { + id: "bad", + kind: "panel-tab", + threadRef: refA, + surface: { kind: "linked-thread", id: "linked-thread:x", viaEnvironmentId: "env-1" }, + }, ])("discards incomplete saved views %j while retaining valid history", async (entry) => { const id = useClosedViewStore.getState().remember(diff(refA)); const { storage, name } = useClosedViewStore.persist.getOptions(); diff --git a/apps/web/src/closedViewStore.ts b/apps/web/src/closedViewStore.ts index 2578922db3d11..7ebf151aa8fab 100644 --- a/apps/web/src/closedViewStore.ts +++ b/apps/web/src/closedViewStore.ts @@ -9,6 +9,7 @@ import * as Schema from "effect/Schema"; import { create } from "zustand"; 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"; @@ -85,6 +86,8 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => { ); case "side-chat": return typeof surface.threadId === "string" && surface.id === `side-chat:${surface.threadId}`; + case "linked-thread": + return decodeLinkedThreadSurface(surface)?.id === surface.id; case "pull-request": return ( typeof surface.projectId === "string" && diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index f6062475ac25b..8c0d14520871d 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1243,7 +1243,12 @@ const CHAT_MARKDOWN_COMPONENTS = { // An autolink's text is its own URL, which is no label. const label = written && parseThreadLinkHref(written) === null ? written : null; return environmentId ? ( - + ) : ( {label ?? gt("Thread")} ); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 2ce8f22f63f5e..32f1e07da92dc 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -66,6 +66,7 @@ import { import { isElectron } from "~/env"; import type { DesktopPreviewOverlay } from "~/previewStateStore"; +import { linkedThreadTitle } from "~/linkedThreadSurface"; import type { RightPanelSurface } from "~/rightPanelStore"; import { cn } from "~/lib/utils"; import { issueStatePresentation } from "~/components/issue/issuePresentation"; @@ -614,6 +615,11 @@ function surfaceTitle( return surface.title ?? surface.target?.name ?? resolve(msg("Device")); case "side-chat": return resolve(msg("Side chat")); + case "linked-thread": + return linkedThreadTitle( + surface, + resolve(msg("Thread on {label}", { label: surface.label })), + ); case "preview": { const snapshot = surface.resourceId ? sessions[surface.resourceId] : null; if (!snapshot || snapshot.navStatus._tag === "Idle") return resolve(msg("Browser")); @@ -706,6 +712,8 @@ function SurfaceIcon({ return ; case "side-chat": return ; + case "linked-thread": + return ; case "device": return surface.target?.platform === "ios" ? ( diff --git a/apps/web/src/components/chat/LinkedThreadSheet.tsx b/apps/web/src/components/chat/LinkedThreadPane.tsx similarity index 65% rename from apps/web/src/components/chat/LinkedThreadSheet.tsx rename to apps/web/src/components/chat/LinkedThreadPane.tsx index 2593cbed85a50..9b4e5532de350 100644 --- a/apps/web/src/components/chat/LinkedThreadSheet.tsx +++ b/apps/web/src/components/chat/LinkedThreadPane.tsx @@ -1,20 +1,23 @@ -import { useAtom } from "@effect/atom-react"; import { isLinkedThreadWorking, linkedThreadFailure, type LinkedThreadItemPresentation, - type LinkedThreadTarget, presentLinkedThreadItem, } from "@t3tools/client-runtime/linked-thread"; +import type { ScopedThreadRef } from "@t3tools/contracts"; import { T, useGT, useMessages, Var } from "gt-react"; import { ChevronRightIcon, EyeIcon } from "lucide-react"; +import type { ReactNode } from "react"; +import { useStableCallback } from "../../hooks/useStableCallback"; +import { getDocumentActivity } from "../../lib/documentActivity"; +import { type LinkedThreadSurface, linkedThreadTitle } from "../../linkedThreadSurface"; +import { useRightPanelStore } from "../../rightPanelStore"; import { useEnvironment } from "../../state/environments"; -import { linkedThreadViewAtom, useLinkedThreadSession } from "../../state/linkedThreadView"; +import { useLinkedThreadSession } from "../../state/linkedThreadView"; import ChatMarkdown from "../ChatMarkdown"; import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert"; import { Button } from "../ui/button"; -import { Sheet, SheetDescription, SheetHeader, SheetPopup, SheetTitle } from "../ui/sheet"; import { Spinner } from "../ui/spinner"; function TruncatedNote() { @@ -61,14 +64,60 @@ function LinkedThreadItem(props: { readonly item: LinkedThreadItemPresentation } ); } -function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { - const { target } = props; +/** Names the thread and where it is read from. `actions` sits at the trailing edge. */ +function LinkedThreadHeader(props: { + readonly title: string; + /** The linked environment the thread is on. */ + readonly label: string; + /** The environment that reads it. */ + readonly via: string; + readonly working: boolean; + readonly actions?: ReactNode; +}) { + return ( +
    +
    +

    {props.title}

    +

    + + + Read-only · on {props.label} via {props.via} + + {props.working ? ( + + · Working + + ) : null} +

    +
    + {props.actions} +
    + ); +} + +/** + * A linked environment's thread, read through the environment this client is connected to. The + * client never connects to the linked one, so the view only reads. 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 panel is showing; reads wait while it is not. */ + readonly visible: boolean; +}) { + const { surface, panelRef } = props; const gt = useGT(); const m = useMessages(); - const via = useEnvironment(target.viaEnvironmentId)?.label ?? gt("this environment"); - const { state, session } = useLinkedThreadSession(target); + const via = useEnvironment(surface.viaEnvironmentId)?.label ?? gt("this environment"); + const isActive = useStableCallback(() => props.visible && getDocumentActivity().visible); + const { state, session } = useLinkedThreadSession(surface, { + isActive, + onTitle: (title) => + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surface.id, title), + }); const { transcript } = state; - const label = transcript?.label ?? target.label; + const label = transcript?.label ?? surface.label; const failure = state.error === null ? null : linkedThreadFailure(state.error, { via, label }, m); const retry = failure?.retryable ? ( @@ -78,31 +127,18 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { ) : null; return ( - <> - - - {/* Clear of the close button in the sheet's corner. */} - - {transcript?.thread.title || target.title || gt("Thread on {label}", { label })} - - - - - - - Read-only · on {label} via {via} - - {transcript !== null && isLinkedThreadWorking(transcript) ? ( - - · Working - - ) : null} - - - {/* A "Connect to interact" action belongs here once this client can pair with the linked environment. */} - +
    + {/* Reversed, so the view opens at the newest item and stays there as items arrive. */} -
    +
    {transcript === null ? ( failure === null ? ( @@ -156,35 +192,6 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { )}
    - - ); -} - -/** - * A linked environment's thread, read through the environment this client is connected to. The - * client never connects to the linked one, so the view only reads. - */ -export function LinkedThreadSheet() { - const [target, setTarget] = useAtom(linkedThreadViewAtom); - return ( - { - if (!open) setTarget(null); - }} - > - {/* The header's panel toggles float above sheets, so the sheet starts below them. */} - - {target === null ? null : ( - - )} - - +
    ); } diff --git a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx index c67a41cbef06a..960589ea4d417 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx @@ -1,19 +1,24 @@ 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, - openedLinked: [] as Array, })); vi.mock(import("../../state/entities"), () => ({ useThreadShell: ((ref: { environmentId: string } | null) => @@ -41,11 +46,6 @@ vi.mock(import("../../state/peerLinks"), () => ({ useLinkedEnvironments: ((environmentId: string | null) => environmentId === null ? new Map() : state.linked) as never, })); -vi.mock(import("../../state/linkedThreadView"), () => ({ - useOpenLinkedThread: () => (target) => { - state.openedLinked.push(target); - }, -})); vi.mock(import("../ProjectFavicon"), () => ({ ProjectFavicon: () => ( @@ -68,7 +68,7 @@ function setup() { state.linked = new Map(); state.cached = null; state.connected = ["environment", "remote"]; - state.openedLinked = []; + useRightPanelStore.setState({ byThreadKey: {} }); state.remote = { environmentId: EnvironmentId.make("remote"), id: ThreadId.make("older-thread"), @@ -191,13 +191,20 @@ it.for([ const link = { environmentId: EnvironmentId.make(linkedId), threadId: ThreadId.make("there") }; await using screen = await render( - + , ); - await screen.getByRole("button", { name: "Thread, Thread on fs-17" }).click(); - expect(state.openedLinked).toEqual([ - { viaEnvironmentId: environmentId, ...link, label: "fs-17", title: null }, - ]); + 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("/"); }); @@ -210,12 +217,17 @@ it("reads through the link when a disconnected machine's thread is only cached h 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(state.openedLinked).toEqual([ - { viaEnvironmentId: environmentId, ...link, label: "fs-17", title: "Cached title" }, + expect(panel().surfaces).toEqual([ + linkedThreadSurface({ + viaEnvironmentId: environmentId, + ...link, + label: "fs-17", + title: "Cached title", + }), ]); }); @@ -229,11 +241,12 @@ it("opens a linked machine's thread directly once this client is connected to it , ); await expect.element(screen.getByText("Fix the build")).toBeVisible(); - expect(state.openedLinked).toEqual([]); + 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 e7eef372d5b7c..1e4c823b458b4 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -1,4 +1,4 @@ -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 { @@ -13,7 +13,7 @@ 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 { useOpenLinkedThread } from "../../state/linkedThreadView"; +import { useRightPanelStore } from "../../rightPanelStore"; import { useLinkedEnvironments } from "../../state/peerLinks"; import { orchestrationEnvironment } from "../../state/orchestration"; import { useEnvironmentQuery } from "../../state/query"; @@ -25,11 +25,14 @@ 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); @@ -41,8 +44,10 @@ 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. + // 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, @@ -77,7 +82,6 @@ export function MarkdownThreadLink(props: { : null; const remote = useThreadShell(remoteRef); const resolved = target ?? (remoteRef && remote ? { ref: remoteRef, metadata: remote } : null); - const openLinked = useOpenLinkedThread(); if (linked && linkedLabel !== undefined) { const knownTitle = props.label ?? written?.title ?? null; const title = knownTitle ?? gt("Thread on {label}", { label: linkedLabel }); @@ -91,7 +95,7 @@ export function MarkdownThreadLink(props: { - ) : 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/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7ea3b22b106e0..abd972f4aeaa7 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3597,23 +3597,11 @@ " 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", "c8e6ea4d6313e912": "Langer Text, hier gekürzt.", - "59fb6d9ab29a1513": [ - "Schreibgeschützt · auf ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " über ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "Arbeitet", + "0014ce0aaf1bd68a": "Schreibgeschützt", "d0bda35aeec66684": [ "Wird von ", { @@ -5787,7 +5775,6 @@ "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", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index eef33ee6f4670..7a755da34798e 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3596,23 +3596,11 @@ ". 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", "c8e6ea4d6313e912": "Long text, cut short here.", - "59fb6d9ab29a1513": [ - "Read-only · on ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " via ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "Working", + "0014ce0aaf1bd68a": "Read-only", "d0bda35aeec66684": [ "Reading from ", { @@ -5788,7 +5776,6 @@ "56ca98b79cc9ce49": "Activity ({count})", "ddc5e5413923c471": "You cannot comment here.", "516def6f5a881e00": "Closes this issue", - "0014ce0aaf1bd68a": "Read-only", "fd93f4720ff70aaf": "None", "b6a29fff7c7c0808": "None", "54420465784bb1bd": "Load older comments", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 8aba7dbc953b5..61f9367feab9a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3596,23 +3596,11 @@ ". 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", "c8e6ea4d6313e912": "Texto largo, recortado aquí.", - "59fb6d9ab29a1513": [ - "Solo lectura · en ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " a través de ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "Trabajando", + "0014ce0aaf1bd68a": "Solo lectura", "d0bda35aeec66684": [ "Leyendo desde ", { @@ -5786,7 +5774,6 @@ "56ca98b79cc9ce49": "Actividad ({count})", "ddc5e5413923c471": "No puedes comentar aquí.", "516def6f5a881e00": "Cierra esta issue", - "0014ce0aaf1bd68a": "Solo lectura", "fd93f4720ff70aaf": "Ninguna", "b6a29fff7c7c0808": "Nadie", "54420465784bb1bd": "Cargar comentarios anteriores", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index cd55e9e8b020e..84e99dfe303a9 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3596,23 +3596,11 @@ ". 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", "c8e6ea4d6313e912": "Texte long, coupé ici.", - "59fb6d9ab29a1513": [ - "Lecture seule · sur ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " via ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "En cours", + "0014ce0aaf1bd68a": "Lecture seule", "d0bda35aeec66684": [ "Lecture depuis ", { @@ -5787,7 +5775,6 @@ "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", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f06efb6de2f23..09b5e93e0e883 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3591,24 +3591,11 @@ " にリンクされています。エージェントはそのリンクをそのまま使用できます。アクセス権は [設定] → [環境] で変更してください。" ], "000b0df227182d39": "別のアドレス…", + "6bb5b1b35b2796ae": "{label}({via} 経由) · 作業中", + "a73b7ab25d6e9bdf": "{label}({via} 経由)", "009e2ca841fdc1ef": "この環境", "c8e6ea4d6313e912": "長いテキストのため、ここで省略されています。", - "59fb6d9ab29a1513": [ - "読み取り専用 · ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - "(", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - " 経由)" - ], - "ff1728d6a7065373": "作業中", + "0014ce0aaf1bd68a": "読み取り専用", "d0bda35aeec66684": [ "読み取り中: ", { @@ -5770,7 +5757,6 @@ "56ca98b79cc9ce49": "アクティビティ ({count})", "ddc5e5413923c471": "ここではコメントできません。", "516def6f5a881e00": "この Issue をクローズします", - "0014ce0aaf1bd68a": "読み取り専用", "fd93f4720ff70aaf": "なし", "b6a29fff7c7c0808": "なし", "54420465784bb1bd": "以前のコメントを読み込む", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index f2131dc3d4d7c..593018e21364a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3591,24 +3591,11 @@ "에 연결되어 있습니다. 에이전트는 이 연결을 그대로 사용할 수 있으며, 액세스는 설정 → 환경에서 변경하세요." ], "000b0df227182d39": "다른 주소…", + "6bb5b1b35b2796ae": "{label} ({via} 경유) · 작업 중", + "a73b7ab25d6e9bdf": "{label} ({via} 경유)", "009e2ca841fdc1ef": "이 환경", "c8e6ea4d6313e912": "긴 텍스트라 여기에서 잘렸습니다.", - "59fb6d9ab29a1513": [ - "읽기 전용 · ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " (", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - " 경유)" - ], - "ff1728d6a7065373": "작업 중", + "0014ce0aaf1bd68a": "읽기 전용", "d0bda35aeec66684": [ "읽는 중: ", { @@ -5768,7 +5755,6 @@ "56ca98b79cc9ce49": "활동({count})", "ddc5e5413923c471": "여기에는 댓글을 달 수 없습니다.", "516def6f5a881e00": "이 이슈를 닫음", - "0014ce0aaf1bd68a": "읽기 전용", "fd93f4720ff70aaf": "없음", "b6a29fff7c7c0808": "없음", "54420465784bb1bd": "이전 댓글 불러오기", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index aa7609a8d4626..8955b14d0fa5c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3596,23 +3596,11 @@ ". 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", "c8e6ea4d6313e912": "Texto longo, cortado aqui.", - "59fb6d9ab29a1513": [ - "Somente leitura · em ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " via ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "Trabalhando", + "0014ce0aaf1bd68a": "Somente leitura", "d0bda35aeec66684": [ "Lendo de ", { @@ -5786,7 +5774,6 @@ "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", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6db78b58100e4..d693e729c0f14 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3596,23 +3596,11 @@ ". Агент может использовать эту привязку как есть; изменить её доступ можно в «Настройки → Окружения»." ], "000b0df227182d39": "Другой адрес…", + "6bb5b1b35b2796ae": "На {label} через {via} · Работает", + "a73b7ab25d6e9bdf": "На {label} через {via}", "009e2ca841fdc1ef": "это окружение", "c8e6ea4d6313e912": "Длинный текст, здесь обрезан.", - "59fb6d9ab29a1513": [ - "Только чтение · на ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " через ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "Работает", + "0014ce0aaf1bd68a": "Только чтение", "d0bda35aeec66684": [ "Чтение с ", { @@ -5786,7 +5774,6 @@ "56ca98b79cc9ce49": "Активность ({count})", "ddc5e5413923c471": "Здесь нельзя комментировать.", "516def6f5a881e00": "Закроет этот issue", - "0014ce0aaf1bd68a": "Только чтение", "fd93f4720ff70aaf": "Нет", "b6a29fff7c7c0808": "Нет", "54420465784bb1bd": "Загрузить старые комментарии", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index a637f200720b4..f763b0f1461ff 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3596,23 +3596,11 @@ ". 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", "c8e6ea4d6313e912": "Lång text, avkortad här.", - "59fb6d9ab29a1513": [ - "Skrivskyddad · på ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " via ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "Arbetar", + "0014ce0aaf1bd68a": "Skrivskyddad", "d0bda35aeec66684": [ "Läser från ", { @@ -5787,7 +5775,6 @@ "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", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 7bf2f18f108b7..91b37026474f7 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3601,23 +3601,11 @@ "。智能体可以直接使用该关联;请在“设置 → 环境”中更改其访问权限。" ], "000b0df227182d39": "其他地址…", + "6bb5b1b35b2796ae": "位于 {label},经由 {via} · 运行中", + "a73b7ab25d6e9bdf": "位于 {label},经由 {via}", "009e2ca841fdc1ef": "此环境", "c8e6ea4d6313e912": "文本较长,此处已截断。", - "59fb6d9ab29a1513": [ - "只读 · 位于 ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - ",经由 ", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - } - ], - "ff1728d6a7065373": "运行中", + "0014ce0aaf1bd68a": "只读", "d0bda35aeec66684": [ "正在从 ", { @@ -5793,7 +5781,6 @@ "56ca98b79cc9ce49": "活动({count})", "ddc5e5413923c471": "你无法在此评论。", "516def6f5a881e00": "将关闭此 issue", - "0014ce0aaf1bd68a": "只读", "fd93f4720ff70aaf": "无", "b6a29fff7c7c0808": "无", "54420465784bb1bd": "加载较早的评论", diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index 4a456d89dd8b0..4cb826ee2fd47 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -1,21 +1,22 @@ +import { useAtomValue } from "@effect/atom-react"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { createLinkedThreadSession, type LinkedThreadOpen, - type LinkedThreadTarget, resolveLinkedThreadOpen, } from "@t3tools/client-runtime/linked-thread"; -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; import { useNavigate } from "@tanstack/react-router"; -import { useState, useSyncExternalStore } from "react"; +import { Atom } from "effect/reactivity"; +import { useSyncExternalStore } from "react"; import { useRightPanelStore } from "../rightPanelStore"; -import { useStableCallback } from "../hooks/useStableCallback"; +import { getDocumentActivity } from "../lib/documentActivity"; +import type { LinkedThreadSurface } from "../linkedThreadSurface"; import { buildThreadRouteParams } from "../threadRoutes"; import { useEnvironment } from "./environments"; import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks"; -import { useAtomCommand } from "./use-atom-command"; /** * How a click opens a thread that the thread `panelRef` says is on a linked environment: in place @@ -68,43 +69,72 @@ export function useLinkedThreadOpener( }; } +type SessionKey = readonly [ + panelEnvironmentId: EnvironmentId, + panelThreadId: ThreadId, + surfaceId: string, + viaEnvironmentId: EnvironmentId, + environmentId: EnvironmentId, + threadId: ThreadId, +]; + /** - * The transcript of `target`, read through the environment that links to it. Reads start when the - * calling view mounts and stop when it unmounts; key the view by its target. + * One tab's reads. It outlives the pane for a while, so coming back to the tab shows what was + * read and carries on from there; a session nothing subscribes to asks for nothing. */ -export function useLinkedThreadSession( - target: Pick, - options: { - /** Whether the view is being looked at; reads wait while it is not. */ - readonly isActive: () => boolean; - /** The thread's own title, each time a read names it. */ - readonly onTitle: (title: string) => void; - }, -) { - const onTitle = useStableCallback(options.onTitle); - const read = useAtomCommand(peerLinkEnvironment.readThread, { - reportFailure: false, - reportDefect: false, - }); - const [session] = useState(() => +const linkedThreadSessionAtom = Atom.family((key: string) => { + const [panelEnvironmentId, panelThreadId, surfaceId, viaEnvironmentId, environmentId, threadId] = + JSON.parse(key) as SessionKey; + const panelRef = scopeThreadRef(panelEnvironmentId, panelThreadId); + return Atom.make((get) => createLinkedThreadSession({ read: async (cursor) => { - const result = await read({ - environmentId: target.viaEnvironmentId, - input: { environmentId: target.environmentId, threadId: target.threadId, ...cursor }, - }); - if (result._tag !== "Success") + const result = await runAtomCommand( + get.registry, + peerLinkEnvironment.readThread, + { environmentId: viaEnvironmentId, input: { environmentId, threadId, ...cursor } }, + { reportFailure: false, reportDefect: false }, + ); + if (result._tag !== "Success") { return { ok: false, error: squashAtomCommandFailure(result) }; - if (result.value.thread.title) onTitle(result.value.thread.title); + } + const { title } = result.value.thread; + if (title) useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); return { ok: true, page: result.value }; }, schedule: (run, delayMs) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); }, - isActive: options.isActive, + isActive: () => getDocumentActivity().visible, }), + ).pipe(Atom.setIdleTTL(5 * 60_000), Atom.withLabel(`linked-thread-session:${key}`)); +}); + +const noSubscription = () => () => {}; + +/** + * The transcript of `surface`, read through the environment that links to it for the tab in + * `panelRef`'s panel. Reads run only while `visible`. + */ +export function useLinkedThreadSession( + panelRef: ScopedThreadRef, + surface: Pick, + visible: boolean, +) { + const key: SessionKey = [ + panelRef.environmentId, + panelRef.threadId, + surface.id, + surface.viaEnvironmentId, + surface.environmentId, + surface.threadId, + ]; + const session = useAtomValue(linkedThreadSessionAtom(JSON.stringify(key))); + const state = useSyncExternalStore( + visible ? session.subscribe : noSubscription, + session.getSnapshot, + session.getSnapshot, ); - const state = useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot); return { state, session }; } diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 8022e69bf808c..d744d6c3c89df 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -373,6 +373,10 @@ describe("createLinkedThreadSession", () => { await closing.reads[0]!.answer({ ok: true, page: page([item(1, "one")]) }); close(); expect(closing.pending()).toEqual([]); + // Opened again, it shows what it read and asks only for what followed. + closing.session.subscribe(() => {}); + expect(closing.session.getSnapshot().transcript?.items).toHaveLength(1); + expect(closing.reads[1]!.cursor).toEqual({ afterPosition: 1 }); const late = harness(); const closeLate = late.session.subscribe(() => {}); From d6874bad82a819ce18d640a02ec907e0e3c6bc60 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:18:16 -0800 Subject: [PATCH 12/17] fix(web): a linked thread tab takes its title only from reads it kept Co-Authored-By: Claude Fable 5.2 --- apps/web/src/closedViewStore.ts | 5 ++++- apps/web/src/state/linkedThreadView.ts | 6 ++++-- packages/client-runtime/src/linkedThread.test.ts | 7 +++++-- packages/client-runtime/src/linkedThread.ts | 3 +++ 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/apps/web/src/closedViewStore.ts b/apps/web/src/closedViewStore.ts index 7ebf151aa8fab..12087195cc67b 100644 --- a/apps/web/src/closedViewStore.ts +++ b/apps/web/src/closedViewStore.ts @@ -87,7 +87,10 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => { case "side-chat": return typeof surface.threadId === "string" && surface.id === `side-chat:${surface.threadId}`; case "linked-thread": - return decodeLinkedThreadSurface(surface)?.id === surface.id; + return ( + (surface.title === null || typeof surface.title === "string") && + decodeLinkedThreadSurface(surface)?.id === surface.id + ); case "pull-request": return ( typeof surface.projectId === "string" && diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index 4cb826ee2fd47..cca27c4d290a0 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -98,10 +98,12 @@ const linkedThreadSessionAtom = Atom.family((key: string) => { if (result._tag !== "Success") { return { ok: false, error: squashAtomCommandFailure(result) }; } - const { title } = result.value.thread; - if (title) useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); return { ok: true, page: result.value }; }, + onRead: (page) => { + const { title } = page.thread; + if (title) useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + }, schedule: (run, delayMs) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index d744d6c3c89df..84f08a7a4cd9d 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -261,6 +261,7 @@ describe("createLinkedThreadSession", () => { readonly answer: (result: LinkedThreadReadResult) => Promise; }> = []; const timers: Array<{ readonly run: () => void; readonly delayMs: number; live: boolean }> = []; + const kept: Array = []; const session = createLinkedThreadSession({ read: (cursor) => new Promise((resolve) => { @@ -280,6 +281,7 @@ describe("createLinkedThreadSession", () => { }; }, isActive: () => active.current, + onRead: (page) => kept.push(page), }); const pending = () => timers.filter((timer) => timer.live); const fire = () => { @@ -287,7 +289,7 @@ describe("createLinkedThreadSession", () => { timer.live = false; timer.run(); }; - return { session, reads, pending, fire }; + return { session, reads, pending, fire, kept }; }; it("reads the newest page on open, then follows the thread at its pace", async () => { @@ -326,12 +328,13 @@ describe("createLinkedThreadSession", () => { }); it("ignores a read that a newer one overtook", async () => { - const { session, reads } = harness(); + const { session, reads, kept } = harness(); session.subscribe(() => {}); session.retry(); await reads[1]!.answer({ ok: true, page: page([item(4, "new")]) }); await reads[0]!.answer({ ok: true, page: page([item(4, "old")]) }); expect(session.getSnapshot().transcript?.items.map((entry) => entry.text)).toEqual(["new"]); + expect(kept.map((kept) => kept.items[0]?.text)).toEqual(["new"]); }); it("pages back without losing what a refresh brought in meanwhile", async () => { diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 18f7efb48e30e..f0aff4e424205 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -308,6 +308,8 @@ export function createLinkedThreadSession(options: { /** Runs `run` after `delayMs` and returns how to cancel it. */ readonly schedule: (run: () => void, delayMs: number) => () => void; readonly isActive?: () => boolean; + /** Called with each forward read the session keeps, never with one a newer read overtook. */ + readonly onRead?: (page: Page) => void; }) { let state: LinkedThreadSessionState = { transcript: null, error: null, loadingEarlier: false }; const listeners = new Set<() => void>(); @@ -350,6 +352,7 @@ export function createLinkedThreadSession(options: { // An earlier page may have landed while this read was out. const transcript = mergeLinkedThreadPage(state.transcript, result.page, "later"); update({ transcript, error: null }); + options.onRead?.(result.page); scheduleNext(linkedThreadPollDelayMs(transcript)); }; From a2c1a8376912c24d671678531d6230083b101b19 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 03:59:34 +0000 Subject: [PATCH 13/17] test(client-runtime): drop linked thread tests of constants and copy The poll-delay case restated constants the session tests already drive, and the failure case asserted wording; retryability stays covered by the session tests. Co-Authored-By: Claude Opus 5.5 --- .../client-runtime/src/linkedThread.test.ts | 57 ------------------- packages/client-runtime/src/linkedThread.ts | 2 +- 2 files changed, 1 insertion(+), 58 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 84f08a7a4cd9d..c36dca8359dbb 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -8,8 +8,6 @@ import { presentLinkedThreadItem, LINKED_THREAD_ACTIVE_POLL_MS, LINKED_THREAD_IDLE_POLL_MS, - linkedThreadFailure, - linkedThreadPollDelayMs, linkedThreadRefreshCursor, mergeLinkedThreadPage, resolveLinkedThreadOpen, @@ -164,61 +162,6 @@ describe("linkedThreadRefreshCursor", () => { }); }); -describe("linkedThreadPollDelayMs", () => { - it("reads again at once while catching up, soon while working, and rarely when idle", () => { - expect(linkedThreadPollDelayMs(page([], { hasMore: true }))).toBe(0); - expect(linkedThreadPollDelayMs(page([]))).toBe(LINKED_THREAD_ACTIVE_POLL_MS); - expect( - linkedThreadPollDelayMs( - page([], { thread: { threadId, title: "Done", status: "idle", model: "gpt-5" } }), - ), - ).toBe(LINKED_THREAD_IDLE_POLL_MS); - }); -}); - -describe("linkedThreadFailure", () => { - const names = { via: "nucbox", label: "VM" }; - const failure = (reason: string, label: string | null = "fs-17") => - linkedThreadFailure( - { _tag: "PeerLinkThreadReadError", reason, label, message: "From the server." }, - names, - ); - - it("names the environment that has to change, and only retries what can recover", () => { - expect(failure("disabled", null)).toMatchObject({ - title: "Linked environments is off on nucbox", - retryable: false, - }); - expect(failure("expired")).toMatchObject({ - title: "The link from nucbox to fs-17 expired", - retryable: false, - }); - expect(failure("thread_not_found")).toMatchObject({ - title: "This thread is no longer on fs-17", - retryable: false, - }); - expect(failure("incompatible")).toEqual({ - title: "fs-17 needs an update", - detail: "From the server.", - retryable: false, - }); - expect(failure("unreachable")).toEqual({ - title: "fs-17 is not answering nucbox", - detail: "From the server.", - retryable: true, - }); - }); - - it("falls back to the client's name for the linked environment, and explains an old host", () => { - expect(failure("unknown_link", null).title).toBe("nucbox is no longer linked to VM"); - expect(linkedThreadFailure(new Error(""), names)).toMatchObject({ - title: "Could not read this thread through nucbox", - detail: "nucbox may need an update before it can read linked threads.", - retryable: true, - }); - }); -}); - describe("presentLinkedThreadItem", () => { const present = ( type: string, diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index f0aff4e424205..b77d1096fae03 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -103,7 +103,7 @@ export const LINKED_THREAD_ACTIVE_POLL_MS = 2_500; export const LINKED_THREAD_IDLE_POLL_MS = 15_000; /** How long an open view waits before its next read: none while catching up, short while the thread works. */ -export function linkedThreadPollDelayMs(transcript: Pick): number { +function linkedThreadPollDelayMs(transcript: Pick): number { if (transcript.hasMore) return 0; return ACTIVE_THREAD_STATUSES.has(transcript.thread.status) ? LINKED_THREAD_ACTIVE_POLL_MS From 8542dd1c7fbc0274f53d3a3147943461df4da7d0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 04:25:31 +0000 Subject: [PATCH 14/17] fix: linked thread links resolve with thread read access Opening a linked environment's thread from a link needs the links' names, which came from peerLinks.list, gated by access:read. A client allowed to read threads but not access therefore could not open them, though peerLinks.readThread lets it. peerLinks.names returns only the unexpired links' ids and labels, under orchestration:read, without probing any peer; the client hooks that name linked environments read it instead. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/state/peerLinks.ts | 5 +-- apps/server/src/auth/RpcAuthorization.test.ts | 41 +++++++++++-------- apps/server/src/auth/RpcAuthorization.ts | 2 + .../src/observability/RpcInstrumentation.ts | 1 + apps/server/src/peer/PeerLinks.test.ts | 2 + apps/server/src/peer/PeerLinks.ts | 14 +++++++ apps/server/src/ws.ts | 2 + apps/web/src/state/peerLinks.ts | 5 +-- .../client-runtime/src/linkRequest.test.ts | 7 ++-- packages/client-runtime/src/linkRequest.ts | 13 +++--- .../client-runtime/src/state/peerLinks.ts | 25 +++++++---- packages/contracts/src/peerLink.ts | 10 +++++ packages/contracts/src/rpc.ts | 10 +++++ 13 files changed, 96 insertions(+), 41 deletions(-) diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.ts index baed9be90412a..40a13f2150234 100644 --- a/apps/mobile/src/state/peerLinks.ts +++ b/apps/mobile/src/state/peerLinks.ts @@ -18,8 +18,7 @@ export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtom /** * 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, @@ -30,7 +29,7 @@ export function useLinkedEnvironments( ); const links = useEnvironmentQuery( offered && environmentId !== null - ? peerLinkEnvironment.list({ environmentId, input: {} }) + ? peerLinkEnvironment.names({ environmentId, input: {} }) : null, ); return useMemo( diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 624e353712cb8..dad5c2705f66a 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -204,33 +204,36 @@ it.effect("allows issue reads but requires a source-control grant before comment it.effect("reads a linked environment's thread only for a client that may read threads here", () => Effect.gen(function* () { + const linkedThreadTags = [WS_METHODS.peerLinksReadThread, WS_METHODS.peerLinksNames] as const; const group = WsRpcGroup.omit( ...[...WsRpcGroup.requests.keys()].filter( ( tag, - ): tag is Exclude< - keyof typeof RPC_REQUIRED_SCOPES, - typeof WS_METHODS.peerLinksReadThread - > => tag !== WS_METHODS.peerLinksReadThread, + ): tag is Exclude => + !(linkedThreadTags as ReadonlyArray).includes(tag), ), ); const read: string[] = []; - const handlers = group.toLayerHandler(WS_METHODS.peerLinksReadThread, ({ threadId }) => - Effect.sync(() => { - read.push(threadId); - return { - label: "Box", - thread: { threadId, title: "There", status: "idle" as const, model: "gpt-5" }, - items: [], - earlierPosition: null, - hasMore: false, - }; - }), - ); const input = { environmentId: EnvironmentId.make("environment-box"), threadId: ThreadId.make("thread:box"), }; + const handlers = group.toLayer({ + [WS_METHODS.peerLinksReadThread]: ({ threadId }) => + Effect.sync(() => { + read.push(threadId); + return { + label: "Box", + thread: { threadId, title: "There", status: "idle" as const, model: "gpt-5" }, + items: [], + earlierPosition: null, + hasMore: false, + }; + }), + // A thread link resolves to the linked environment by its name. + [WS_METHODS.peerLinksNames]: () => + Effect.succeed({ links: [{ environmentId: input.environmentId, label: "Box" }] }), + }); // Managing links and writing settings here say nothing about reading threads. const outsider = yield* RpcTest.makeClient(group).pipe( Effect.provide( @@ -245,12 +248,18 @@ it.effect("reads a linked environment's thread only for a client that may read t requiredPermission: AuthOrchestrationReadScope, }); expect(read).toEqual([]); + expect(yield* outsider[WS_METHODS.peerLinksNames]({}).pipe(Effect.flip)).toMatchObject({ + requiredPermission: AuthOrchestrationReadScope, + }); const reader = yield* RpcTest.makeClient(group).pipe( Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))), ); expect((yield* reader[WS_METHODS.peerLinksReadThread](input)).label).toBe("Box"); expect(read).toEqual([input.threadId]); + expect((yield* reader[WS_METHODS.peerLinksNames]({})).links).toEqual([ + { environmentId: input.environmentId, label: "Box" }, + ]); }).pipe(Effect.scoped), ); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 859beb21d354a..37b957a905606 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -96,6 +96,8 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope, [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope, [WS_METHODS.peerLinksList]: AuthAccessReadScope, + // Names only, so a client that reads threads can open a linked environment's. + [WS_METHODS.peerLinksNames]: AuthOrchestrationReadScope, [WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope, [WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope, [WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 40405c2fb2a09..8679903071146 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -66,6 +66,7 @@ const RPC_AGGREGATES = { [WS_METHODS.serverGetDatabaseStorage]: "server", [WS_METHODS.serverReclaimDatabaseSpace]: "server", [WS_METHODS.peerLinksList]: "peerLinks", + [WS_METHODS.peerLinksNames]: "peerLinks", [WS_METHODS.peerLinksLink]: "peerLinks", [WS_METHODS.peerLinksUnlink]: "peerLinks", [WS_METHODS.peerLinksAnswerRequest]: "peerLinks", diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 70a1c48a33ff4..0b1f4f716474c 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -575,6 +575,7 @@ it.effect("reads one stored link without asking the peer", () => const stored = yield* a.links.get(box.environmentId); expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box")); expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true); + expect(yield* a.links.names).toEqual([{ environmentId: box.environmentId, label: "Box" }]); expect(yield* Ref.get(b.probes)).toBe(0); // An older answer that lands after a newer one never moves the expiry back. @@ -691,6 +692,7 @@ it.effect("tells the agent to link again once the peer revokes the link or it ex yield* TestClock.adjust(Duration.days(31)); expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]); + expect(yield* a.links.names).toEqual([]); yield* Ref.set(b.bearers, []); const expired = yield* probe(a).pipe(Effect.flip); expect(expired.code).toBe("capability_denied"); diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 4fa159dd70337..2e5f843c6528c 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -9,6 +9,7 @@ import { type PeerLink, type PeerLinkCreateInput, PeerLinkError, + type PeerLinkName, type PeerLinkSummary, } from "@t3tools/contracts"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -104,6 +105,8 @@ export class PeerLinks extends Context.Service< input: PeerLinkCreateInput, ) => Effect.Effect<{ readonly link: PeerLink; readonly alreadyLinked: boolean }, PeerLinkError>; readonly list: Effect.Effect, PeerLinkError>; + /** The unexpired links' names, from what is stored, without asking any peer. */ + readonly names: Effect.Effect, PeerLinkError>; /** The stored link, without asking the peer whether it answers. */ readonly get: ( environmentId: EnvironmentId, @@ -637,6 +640,16 @@ const make = Effect.gen(function* () { }); }); + const names: PeerLinks["Service"]["names"] = Effect.gen(function* () { + const links = yield* Effect.forEach(yield* readRows, toLink); + const now = yield* DateTime.now; + return links.flatMap((link) => + DateTime.isGreaterThan(link.expiresAt, now) + ? [{ environmentId: link.environmentId, label: link.label }] + : [], + ); + }); + const get: PeerLinks["Service"]["get"] = (environmentId) => readRow(environmentId).pipe( Effect.flatMap( @@ -750,6 +763,7 @@ const make = Effect.gen(function* () { link, linkUnlessLinked, list, + names, get, unlink, resolve, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index acb0e6866bd6d..2865e3544755a 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2706,6 +2706,8 @@ export const layerWsRpc = ( [WS_METHODS.serverReclaimDatabaseSpace]: () => databaseStorage.requestReclaim, [WS_METHODS.peerLinksList]: (_input) => peerLinks.list.pipe(Effect.map((links) => ({ links }))), + [WS_METHODS.peerLinksNames]: (_input) => + peerLinks.names.pipe(Effect.map((links) => ({ links }))), [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), 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/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/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index ba60711f40dd7..486ae06ec5d75 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -1,8 +1,8 @@ -import { type PeerLinkSummary, WS_METHODS } from "@t3tools/contracts"; +import { type EnvironmentId, type PeerLinkSummary, 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 { Atom, type AtomRegistry } from "effect/reactivity"; import type { EnvironmentRegistry } from "../connection/registry.ts"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; @@ -16,13 +16,24 @@ 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: {} })); + }); 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 +43,7 @@ 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), }), /** One page of a linked environment's thread. An open view calls it; nothing is cached. */ readThread: createEnvironmentRpcCommand(runtime, { @@ -49,8 +59,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/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index 3aa388e5adcbd..2e927df0e2a39 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -42,6 +42,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, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index fc9e13982456a..2f5b27363032e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -20,6 +20,7 @@ import { PeerLink, PeerLinkCreateInput, PeerLinkError, + PeerLinkName, PeerLinkRemoveInput, PeerLinkRemoveResult, PeerLinkRequestAnswerInput, @@ -549,6 +550,7 @@ 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", @@ -894,6 +896,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, @@ -2312,6 +2321,7 @@ export const WsRpcGroup = RpcGroup.make( WsServerReclaimDatabaseSpaceRpc, WsServerUpdateSettingsRpc, WsPeerLinksListRpc, + WsPeerLinksNamesRpc, WsPeerLinksLinkRpc, WsPeerLinksUnlinkRpc, WsPeerLinksAnswerRequestRpc, From a64e1fb1da32cef9ca6ffef52e8092026ae775ee Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:19:07 -0800 Subject: [PATCH 15/17] feat: a linked environment's thread is the thread's own stream, read-only Reading a thread on a linked environment had its own data path: the linking environment called the agent tool t3_thread_read, returned pages in a contract of its own, and each client polled, merged and drew them with a transcript renderer of its own. That made a third transcript format beside the full thread and the guest share. The linked environment now serves the owner's thread subscription to a peer link's session (stream, history pages, item detail), the linking environment relays it over peerLinks.subscribeThread, and clients reduce it with the reducer the guest page uses and draw it with the standard timeline, read-only. PeerThreadReader, the paged contract, the polling session and both bespoke renderers are gone. Co-Authored-By: Claude Fable 5.2 --- .../features/threads/LinkedThreadSheet.tsx | 143 +++--- apps/mobile/src/i18n/translations/de.json | 17 +- apps/mobile/src/i18n/translations/en.json | 17 +- apps/mobile/src/i18n/translations/es.json | 17 +- apps/mobile/src/i18n/translations/fr.json | 17 +- apps/mobile/src/i18n/translations/ja.json | 17 +- apps/mobile/src/i18n/translations/ko.json | 17 +- apps/mobile/src/i18n/translations/pt-BR.json | 17 +- apps/mobile/src/i18n/translations/ru.json | 17 +- apps/mobile/src/i18n/translations/sv.json | 17 +- apps/mobile/src/i18n/translations/zh.json | 17 +- apps/mobile/src/state/linkedThread.ts | 55 +-- apps/server/src/auth/RpcAuthorization.test.ts | 49 +- apps/server/src/auth/RpcAuthorization.ts | 4 + .../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/PeerForwarding.test.ts | 206 +------- apps/server/src/peer/PeerLinks.testkit.ts | 6 +- apps/server/src/peer/PeerLinks.ts | 3 + apps/server/src/peer/PeerMcpClient.test.ts | 2 + apps/server/src/peer/PeerThreadReader.ts | 156 ------ apps/server/src/peer/PeerThreadRelay.test.ts | 228 +++++++++ apps/server/src/peer/PeerThreadRelay.ts | 262 ++++++++++ apps/server/src/peer/linkThreadHttp.ts | 162 +++++++ apps/server/src/server.ts | 6 +- apps/server/src/ws.test.ts | 4 +- apps/server/src/ws.ts | 17 +- .../src/components/chat/LinkedThreadPane.tsx | 181 +++---- .../chat/ReadOnlyThreadTimeline.tsx | 143 ++++++ .../src/components/chat/V2ItemInspector.tsx | 4 +- .../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 | 28 +- apps/web/src/i18n/translations/en.json | 28 +- apps/web/src/i18n/translations/es.json | 28 +- apps/web/src/i18n/translations/fr.json | 28 +- apps/web/src/i18n/translations/ja.json | 28 +- apps/web/src/i18n/translations/ko.json | 28 +- apps/web/src/i18n/translations/pt-BR.json | 28 +- apps/web/src/i18n/translations/ru.json | 28 +- apps/web/src/i18n/translations/sv.json | 28 +- apps/web/src/i18n/translations/zh.json | 28 +- apps/web/src/state/linkedThreadView.ts | 97 ++-- docs/internals/environment-auth.md | 4 +- docs/internals/remote.md | 12 + docs/user/remote-access.md | 9 +- packages/client-runtime/package.json | 4 + .../client-runtime/src/linkedThread.test.ts | 455 ++++-------------- packages/client-runtime/src/linkedThread.ts | 373 +++++--------- packages/client-runtime/src/rpc/client.ts | 1 + .../src/state/commandPermissions.test.ts | 31 -- .../client-runtime/src/state/peerLinks.ts | 72 ++- .../client-runtime/src/state/threadStream.ts | 94 ++++ .../contracts/src/clientRpcPermissions.ts | 2 - packages/contracts/src/environment.ts | 3 + packages/contracts/src/peerLink.ts | 61 +-- packages/contracts/src/rpc.ts | 34 +- 60 files changed, 1822 insertions(+), 1837 deletions(-) create mode 100644 apps/server/src/eventStreamResponse.ts delete mode 100644 apps/server/src/peer/PeerThreadReader.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/ReadOnlyThreadTimeline.tsx create mode 100644 packages/client-runtime/src/state/threadStream.ts diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index c1b8be4651d8f..e0be0d5ee4c8a 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -1,17 +1,15 @@ -import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { isLinkedThreadWorking, linkedThreadFailure, type LinkedThreadFailure, - type LinkedThreadItemPresentation, type LinkedThreadTarget, - presentLinkedThreadItem, } from "@t3tools/client-runtime/linked-thread"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { T, useGT, useMessages } from "gt-react-native"; -import { useRef, useState } from "react"; +import { T, useGT, useLocale, useMessages } from "gt-react-native"; +import { useRef, useState, useSyncExternalStore } from "react"; import type * as React from "react"; -import { Pressable, ScrollView, View } from "react-native"; +import { AppState, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; @@ -21,7 +19,13 @@ import { ScreenContent } from "../../components/ui/ScreenContent"; import { SheetHeader } from "../../components/ui/SheetHeader"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useEnvironments } from "../../state/environments"; -import { useLinkedThreadSession } from "../../state/linkedThread"; +import { + buildThreadFeed, + createThreadFeedCache, + type ThreadFeedActivity, + type ThreadFeedEntry, +} from "../../lib/threadActivity"; +import { useLinkedThreadView } from "../../state/linkedThread"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; import { ReadOnlyComposerBar } from "./ReadOnlyComposerBar"; @@ -46,63 +50,60 @@ export const linkedThreadRouteParams = ( ...(title === null ? {} : { title }), }); -function TruncatedNote() { - return ( - - Long text, cut short here. - - ); -} - -function ActivityRow(props: { - readonly item: Extract; -}) { - const { item } = props; +function ActivityRow(props: { readonly activity: ThreadFeedActivity }) { + const { activity } = props; const [open, setOpen] = useState(false); - const summary = ( - - {item.summary} - - ); + const body = open ? (activity.getFullDetail() ?? activity.detail) : null; return ( setOpen(!open)} className="active:opacity-70" > - {summary} - {open && item.body !== null ? ( + + {activity.summary} + + {body ? ( - {item.body} + {body} - {item.truncated ? : null} ) : null} ); } -function LinkedThreadItem(props: { readonly item: LinkedThreadItemPresentation }) { - const { item } = props; +/** + * One entry of the thread's feed, as the thread screen's own feed model has it. Only reading + * rows are drawn: what needs the thread's environment (files, visuals, apps) is left out. + */ +function LinkedThreadEntry(props: { readonly entry: ThreadFeedEntry }) { + const { entry } = props; const styles = useMarkdownPreviewStyles(); - if (item.kind === "activity") return ; - return item.kind === "user" ? ( + if (entry.type === "activity-group") { + return ( + + {entry.activities.map((activity) => ( + + ))} + + ); + } + if (entry.type !== "message" || entry.message.text.trim() === "") return null; + return entry.message.role === "user" ? ( - {item.text} + {entry.message.text} - {item.truncated ? : null} ) : ( - - - {item.truncated ? : null} - + ); } @@ -166,28 +167,49 @@ function LinkedThreadComposer(props: { ); } +const subscribeAppState = (onChange: () => void) => { + const subscription = AppState.addEventListener("change", onChange); + return () => subscription.remove(); +}; +const appIsActive = () => AppState.currentState === "active"; + function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { const { target } = props; const gt = useGT(); const m = useMessages(); + const locale = useLocale(); const navigation = useNavigation(); const insets = useSafeAreaInsets(); const via = useEnvironments().environments.find( (environment) => environment.environmentId === target.viaEnvironmentId, )?.label ?? gt("this environment"); - const { state, session } = useLinkedThreadSession(target, () => navigation.isFocused()); - const { transcript } = state; - const label = transcript?.label ?? target.label; - const failure = state.error === null ? null : linkedThreadFailure(state.error, { via, label }, m); + // The stream runs only while this screen is the one being looked at. + const focused = useIsFocused(); + const appActive = useSyncExternalStore(subscribeAppState, appIsActive); + const { view, error, retry } = useLinkedThreadView(target, focused && appActive); + const projection = view?.thread.projection ?? null; + const label = target.label; + const failure = error === null ? null : linkedThreadFailure(error, { via, label }, m); + const [feedCache] = useState(() => createThreadFeedCache()); + const feed = + projection === null + ? [] + : buildThreadFeed(projection.visibleTurnItems, { + attempts: projection.attempts, + nodes: projection.nodes, + cache: feedCache, + resolve: m, + locale, + }); const scroll = useRef>(null); // Follows new items only while the reader is already at the end. const atEnd = useRef(true); - const working = transcript !== null && isLinkedThreadWorking(transcript); + const working = projection !== null && isLinkedThreadWorking(projection); return ( navigation.goBack()} /> @@ -208,7 +230,7 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) { if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); }} > - {transcript === null ? ( + {view === null || projection === null ? ( failure === null ? ( @@ -217,36 +239,31 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) {
    ) : ( - + ) ) : ( <> - {transcript.earlierPosition !== null ? ( + {view.thread.historyCursor !== null ? ( ) : 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: transcript?.thread.title || surface.title }, + { title: projection?.thread.title || surface.title }, gt("Thread on {label}", { label }), )}

    - {/* Reversed, so the view opens at the newest item and stays there as items arrive. */} -
    -
    - {transcript === null ? ( - failure === null ? ( + {projection === null ? ( + <> +
    + {failure === null ? (
    @@ -158,51 +132,42 @@ export function LinkedThreadPane(props: { {failure.title} {failure.detail} - {retry} + {retryAction} - ) - ) : ( + )} +
    + + + ) : ( + + {() => ( <> - {transcript.earlierPosition !== null ? ( - - ) : null} - {transcript.items.length === 0 ? ( -

    - Nothing in this thread yet. -

    - ) : null} - {transcript.items.map((item) => { - const presented = presentLinkedThreadItem(item, m); - return presented === null ? null : ( - - ); - })} {failure === null ? null : ( - - {failure.title} - - {failure.detail} Showing what was read before. - - {retry} - +
    + + {failure.title} + + {failure.detail} Showing what was read before. + + {retryAction} + +
    )} + )} -
    -
    - + + )}
    ); } 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/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx index ad4fd7dd33175..9a8708266a5e7 100644 --- a/apps/web/src/components/chat/V2ItemInspector.tsx +++ b/apps/web/src/components/chat/V2ItemInspector.tsx @@ -246,7 +246,9 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec // Command rows stream their output, including the final output, from the server. const environmentStreamsOutput = useCommandOutputStreaming(props.environmentId); const streamsOutput = - (props.source !== undefined || environmentStreamsOutput) && + (props.source === undefined + ? environmentStreamsOutput + : props.source.commandOutput !== undefined) && props.projectedItem.item.type === "command_execution"; const fetched = useFetchedTurnItem( props.projectedItem, 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 368d55179079c..c41e76ab3b808 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "Möglicherweise wurde er dort gelöscht.", "f7870ef3a4828ab1": "{label} braucht ein Update", "eabbf064657519ee": "{label} antwortet {via} nicht", - "6ab96e26bda35288": "Denkt nach", - "67733c48eaaec73a": "Plan", - "75aaf70eabf15f4b": "Dateisuche", - "ac511f991a3c1fab": "Websuche", - "5e30649065b60d94": "Genehmigungsanfrage", - "5c8772e727c04218": "Frage", - "a06eb47a82969918": "Subagent", - "646de37e0bec85f8": "Tool-Aufruf", - "885ae08a2160a158": "Kontext komprimiert", - "afc8fb892e52f932": "Fehler", "f71597ae3afaef44": "{first} und {second}", "4047174839a16714": "{first} und {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "Komprimieren des Kontexts gestoppt", "2605da0149cd15f1": "Kontext wird komprimiert", "39a82db18ca50c21": "Kontext komprimiert: {before} → {after} Tokens", + "885ae08a2160a158": "Kontext komprimiert", "3ab6b281a0991766": "{count, plural, =1 {Verknüpfte Pull Requests geprüft} other {Verknüpfte Pull Requests {count}-mal geprüft}}", "857e92a89b6b6257": "{count, plural, one {{count} Datei gelesen} other {{count} Dateien gelesen}}", "466ac7fcdb97bb76": "{count, plural, one {{count} Datei geändert} other {{count} Dateien geändert}}", @@ -1959,6 +1950,7 @@ "cf34b1bdf8179c16": "Lokal", "d85877d9ef77c50c": "Änderungen", "b816058fba61e4d6": "Runde {count}", + "646de37e0bec85f8": "Tool-Aufruf", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Letzte Runde", "e6ae3a0fbf3eb49e": "Für diese Auswahl sind keine Diff-Dateiinhalte verfügbar.", @@ -3627,7 +3619,8 @@ "6bb5b1b35b2796ae": "Auf {label} über {via} · Arbeitet", "a73b7ab25d6e9bdf": "Auf {label} über {via}", "009e2ca841fdc1ef": "diese Umgebung", - "c8e6ea4d6313e912": "Langer Text, hier gekürzt.", + "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 ", @@ -3638,8 +3631,6 @@ }, " gelesen …" ], - "50fb8b2ca3db6cad": "Frühere laden", - "048b8a737af895ac": "Noch nichts in diesem Thread.", "c3e8cd9bf44e2f43": "Angezeigt wird, was zuvor gelesen wurde.", "eb6e0584cf4a2a1d": "Sprache: {language}", "d76c606a3c519b78": "Zeilenumbruch deaktivieren", @@ -3716,7 +3707,9 @@ "9bbecec926c3b695": "Wiederholen", "4fd8927b7afc2a92": "Nachricht kopieren", "6f8651e48261911a": "Gedanke", + "ac511f991a3c1fab": "Websuche", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} weitere} other {{path} +{count} weitere}}", + "6ab96e26bda35288": "Denkt nach", "4d4981a1c5bd9728": "Befehl läuft", "a078225c5f197cd2": "Befehl fehlgeschlagen", "37ab148aaa486051": "Befehl abgelehnt", @@ -3815,6 +3808,7 @@ "afe27891aab8cf37": "{label}: Nicht bereit.", "2f77cc3105ddd7f8": "Anbieter", "3b205a1c17c06fbd": "Favoriten", + "a06eb47a82969918": "Subagent", "d567966a45ff32be": "Arbeit der Subagenten", "4740c38b2edd194d": "Nur lesen. Diese Subagenten können keine Nachrichten annehmen.", "5a0125dd9241cdec": "Wird geladen…", @@ -5722,7 +5716,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", @@ -5816,14 +5809,13 @@ "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", @@ -6498,7 +6490,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}}", @@ -9780,6 +9771,7 @@ "51497bd401292062": "Gedrückt halten", "9d6cc6ac23312071": "Doppelt drücken", "f001fa7b329c8fbf": "Erfolgreiche ausblenden", + "ad208e3e32c85029": "Alle ausblenden", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Nur Status", "cf0f7fc3df26fa75": "Status und Nachrichten", @@ -9989,6 +9981,7 @@ "573ea5fdf293a9d6": "Alle Checkouts", "470ad8c54049d1e1": "Checkouts durchsuchen", "7e2dfdd9f97fc027": "Projektbereich", + "1cf216566c1ee064": "Projekt nicht verfügbar", "c1b8c351aa90f319": [ { "t": "span", @@ -11020,6 +11013,7 @@ "af4c158f5758af59": "Bedienelemente der Seitenleiste", "cddde869ea4ceb29": "Auswahl in der Seitenleiste", "735a61ef214f6836": "Terminal-Hintergrund", + "afc8fb892e52f932": "Fehler", "16ad4c65b7cde1bb": "„{label}“ hat keine helle Palette. Erstelle ein Design mit demselben Namen, um eine hinzuzufügen.", "0ec05a92bf5537a2": "„{label}“ hat keine dunkle Palette. Erstelle ein Design mit demselben Namen, um eine hinzuzufügen.", "a9cfdfa41271d7d4": "„{label}“ hat bereits eine helle Palette.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 8d3f6542245f6..a1ef78b60e725 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "It may have been deleted there.", "f7870ef3a4828ab1": "{label} needs an update", "eabbf064657519ee": "{label} is not answering {via}", - "6ab96e26bda35288": "Thinking", - "67733c48eaaec73a": "Plan", - "75aaf70eabf15f4b": "File search", - "ac511f991a3c1fab": "Web search", - "5e30649065b60d94": "Approval request", - "5c8772e727c04218": "Question", - "a06eb47a82969918": "Subagent", - "646de37e0bec85f8": "Tool call", - "885ae08a2160a158": "Context compacted", - "afc8fb892e52f932": "Error", "f71597ae3afaef44": "{first} and {second}", "4047174839a16714": "{first}, and {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "Context compaction stopped", "2605da0149cd15f1": "Compacting context", "39a82db18ca50c21": "Context compacted {before} → {after} tokens", + "885ae08a2160a158": "Context compacted", "3ab6b281a0991766": "{count, plural, =1 {Checked linked pull requests} other {Checked linked pull requests {count} times}}", "857e92a89b6b6257": "{count, plural, one {Read {count} file} other {Read {count} files}}", "466ac7fcdb97bb76": "{count, plural, one {Changed {count} file} other {Changed {count} files}}", @@ -1960,6 +1951,7 @@ "cf34b1bdf8179c16": "Uncommitted", "d85877d9ef77c50c": "Changes", "b816058fba61e4d6": "Turn {count}", + "646de37e0bec85f8": "Tool call", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Latest turn", "e6ae3a0fbf3eb49e": "Diff file contents are unavailable for this selection.", @@ -3626,7 +3618,8 @@ "6bb5b1b35b2796ae": "On {label} via {via} · Working", "a73b7ab25d6e9bdf": "On {label} via {via}", "009e2ca841fdc1ef": "this environment", - "c8e6ea4d6313e912": "Long text, cut short here.", + "8cb2e5692c4f05ab": "Open this thread on {label} to see this visual.", + "745a0b899008618c": "Could not load earlier turns. Try again.", "0014ce0aaf1bd68a": "Read-only", "d0bda35aeec66684": [ "Reading from ", @@ -3637,8 +3630,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "Load earlier", - "048b8a737af895ac": "Nothing in this thread yet.", "c3e8cd9bf44e2f43": "Showing what was read before.", "eb6e0584cf4a2a1d": "Language: {language}", "d76c606a3c519b78": "Disable line wrap", @@ -3715,7 +3706,9 @@ "9bbecec926c3b695": "Retry", "4fd8927b7afc2a92": "Copy message", "6f8651e48261911a": "Thought", + "ac511f991a3c1fab": "Web search", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} more} other {{path} +{count} more}}", + "6ab96e26bda35288": "Thinking", "4d4981a1c5bd9728": "Running command", "a078225c5f197cd2": "Failed command", "37ab148aaa486051": "Declined command", @@ -3814,6 +3807,7 @@ "afe27891aab8cf37": "{label}: Not ready.", "2f77cc3105ddd7f8": "Providers", "3b205a1c17c06fbd": "Favorites", + "a06eb47a82969918": "Subagent", "d567966a45ff32be": "Subagent work", "4740c38b2edd194d": "Read only. These subagents cannot take messages.", "5a0125dd9241cdec": "Loading…", @@ -5723,7 +5717,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", @@ -5817,14 +5810,13 @@ "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", @@ -6505,7 +6497,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}}", @@ -9789,6 +9780,7 @@ "51497bd401292062": "Hold", "9d6cc6ac23312071": "Double press", "f001fa7b329c8fbf": "Hide successful", + "ad208e3e32c85029": "Hide all", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Status only", "cf0f7fc3df26fa75": "Status and messages", @@ -9998,6 +9990,7 @@ "573ea5fdf293a9d6": "All checkouts", "470ad8c54049d1e1": "Search checkouts", "7e2dfdd9f97fc027": "Project scope", + "1cf216566c1ee064": "Unavailable project", "c1b8c351aa90f319": [ { "t": "span", @@ -11030,6 +11023,7 @@ "af4c158f5758af59": "Sidebar controls", "cddde869ea4ceb29": "Sidebar selection", "735a61ef214f6836": "Terminal background", + "afc8fb892e52f932": "Error", "16ad4c65b7cde1bb": "“{label}” has no light palette. Create a theme with the same name to add one.", "0ec05a92bf5537a2": "“{label}” has no dark palette. Create a theme with the same name to add one.", "a9cfdfa41271d7d4": "“{label}” already has a light palette.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index e7018741a678e..06096f4d719e1 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "Puede que se haya eliminado allí.", "f7870ef3a4828ab1": "{label} necesita una actualización", "eabbf064657519ee": "{label} no responde a {via}", - "6ab96e26bda35288": "Pensando", - "67733c48eaaec73a": "Plan", - "75aaf70eabf15f4b": "Búsqueda de archivos", - "ac511f991a3c1fab": "Búsqueda web", - "5e30649065b60d94": "Solicitud de aprobación", - "5c8772e727c04218": "Pregunta", - "a06eb47a82969918": "Subagente", - "646de37e0bec85f8": "Llamada a herramienta", - "885ae08a2160a158": "Contexto compactado", - "afc8fb892e52f932": "Error", "f71597ae3afaef44": "{first} y {second}", "4047174839a16714": "{first} y {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "Se detuvo la compactación del contexto", "2605da0149cd15f1": "Compactando el contexto", "39a82db18ca50c21": "Contexto compactado de {before} → {after} tokens", + "885ae08a2160a158": "Contexto compactado", "3ab6b281a0991766": "{count, plural, =1 {Se comprobaron las pull requests vinculadas} other {Se comprobaron las pull requests vinculadas {count} veces}}", "857e92a89b6b6257": "{count, plural, one {Se leyó {count} archivo} other {Se leyeron {count} archivos}}", "466ac7fcdb97bb76": "{count, plural, one {Se cambió {count} archivo} other {Se cambiaron {count} archivos}}", @@ -1960,6 +1951,7 @@ "cf34b1bdf8179c16": "Sin commit", "d85877d9ef77c50c": "Cambios", "b816058fba61e4d6": "Turno {count}", + "646de37e0bec85f8": "Llamada a herramienta", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Último turno", "e6ae3a0fbf3eb49e": "El contenido de los archivos del diff no está disponible para esta selección.", @@ -3626,7 +3618,8 @@ "6bb5b1b35b2796ae": "En {label} a través de {via} · Trabajando", "a73b7ab25d6e9bdf": "En {label} a través de {via}", "009e2ca841fdc1ef": "este entorno", - "c8e6ea4d6313e912": "Texto largo, recortado aquí.", + "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 ", @@ -3637,8 +3630,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "Cargar anteriores", - "048b8a737af895ac": "Aún no hay nada en este hilo.", "c3e8cd9bf44e2f43": "Se muestra lo que se leyó antes.", "eb6e0584cf4a2a1d": "Lenguaje: {language}", "d76c606a3c519b78": "Desactivar ajuste de línea", @@ -3713,7 +3704,9 @@ "9bbecec926c3b695": "Reintentar", "4fd8927b7afc2a92": "Copiar mensaje", "6f8651e48261911a": "Razonamiento", + "ac511f991a3c1fab": "Búsqueda web", "07e65dba2b16d3f7": "{count, plural, one {{path} y {count} más} other {{path} y {count} más}}", + "6ab96e26bda35288": "Pensando", "4d4981a1c5bd9728": "Ejecutando comando", "a078225c5f197cd2": "Comando fallido", "37ab148aaa486051": "Comando rechazado", @@ -3812,6 +3805,7 @@ "afe27891aab8cf37": "{label}: no está listo.", "2f77cc3105ddd7f8": "Proveedores", "3b205a1c17c06fbd": "Favoritos", + "a06eb47a82969918": "Subagente", "d567966a45ff32be": "Trabajo del subagente", "4740c38b2edd194d": "Solo lectura. Estos subagentes no pueden recibir mensajes.", "5a0125dd9241cdec": "Cargando…", @@ -5721,7 +5715,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", @@ -5815,14 +5808,13 @@ "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", @@ -6498,7 +6490,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}}", @@ -9777,6 +9768,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", @@ -9986,6 +9978,7 @@ "573ea5fdf293a9d6": "Todos los checkouts", "470ad8c54049d1e1": "Buscar checkouts", "7e2dfdd9f97fc027": "Ámbito de proyectos", + "1cf216566c1ee064": "Proyecto no disponible", "c1b8c351aa90f319": [ { "t": "span", @@ -11015,6 +11008,7 @@ "af4c158f5758af59": "Controles de la barra lateral", "cddde869ea4ceb29": "Selección de la barra lateral", "735a61ef214f6836": "Fondo de la terminal", + "afc8fb892e52f932": "Error", "16ad4c65b7cde1bb": "«{label}» no tiene paleta clara. Crea un tema con el mismo nombre para añadir una.", "0ec05a92bf5537a2": "«{label}» no tiene paleta oscura. Crea un tema con el mismo nombre para añadir una.", "a9cfdfa41271d7d4": "«{label}» ya tiene una paleta clara.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 82b1faf90e0bf..d519bf76402c2 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "Il a peut-être été supprimé là-bas.", "f7870ef3a4828ab1": "{label} a besoin d’une mise à jour", "eabbf064657519ee": "{label} ne répond pas à {via}", - "6ab96e26bda35288": "Réflexion", - "67733c48eaaec73a": "Plan", - "75aaf70eabf15f4b": "Recherche de fichiers", - "ac511f991a3c1fab": "Recherche web", - "5e30649065b60d94": "Demande d’approbation", - "5c8772e727c04218": "Question", - "a06eb47a82969918": "Sous-agent", - "646de37e0bec85f8": "Appel d’outil", - "885ae08a2160a158": "Contexte compacté", - "afc8fb892e52f932": "Erreur", "f71597ae3afaef44": "{first} et {second}", "4047174839a16714": "{first} et {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "Compactage du contexte arrêté", "2605da0149cd15f1": "Compactage du contexte", "39a82db18ca50c21": "Contexte compacté de {before} → {after} tokens", + "885ae08a2160a158": "Contexte compacté", "3ab6b281a0991766": "{count, plural, =1 {Pull requests associées vérifiées} other {Pull requests associées vérifiées {count} fois}}", "857e92a89b6b6257": "{count, plural, one {{count} fichier lu} other {{count} fichiers lus}}", "466ac7fcdb97bb76": "{count, plural, one {{count} fichier modifié} other {{count} fichiers modifiés}}", @@ -1960,6 +1951,7 @@ "cf34b1bdf8179c16": "Locales", "d85877d9ef77c50c": "Modifications", "b816058fba61e4d6": "Tour {count}", + "646de37e0bec85f8": "Appel d’outil", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Dernier tour", "e6ae3a0fbf3eb49e": "Le contenu des fichiers du diff n’est pas disponible pour cette sélection.", @@ -3626,7 +3618,8 @@ "6bb5b1b35b2796ae": "Sur {label} via {via} · En cours", "a73b7ab25d6e9bdf": "Sur {label} via {via}", "009e2ca841fdc1ef": "cet environnement", - "c8e6ea4d6313e912": "Texte long, coupé ici.", + "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 ", @@ -3637,8 +3630,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "Charger les précédents", - "048b8a737af895ac": "Rien dans ce fil pour l’instant.", "c3e8cd9bf44e2f43": "Affichage de ce qui a été lu auparavant.", "eb6e0584cf4a2a1d": "Langage : {language}", "d76c606a3c519b78": "Désactiver le retour à la ligne", @@ -3714,7 +3705,9 @@ "9bbecec926c3b695": "Réessayer", "4fd8927b7afc2a92": "Copier le message", "6f8651e48261911a": "Réflexion", + "ac511f991a3c1fab": "Recherche web", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} autre} other {{path} +{count} autres}}", + "6ab96e26bda35288": "Réflexion", "4d4981a1c5bd9728": "Exécution de la commande", "a078225c5f197cd2": "Commande en échec", "37ab148aaa486051": "Commande refusée", @@ -3813,6 +3806,7 @@ "afe27891aab8cf37": "{label} : pas prêt.", "2f77cc3105ddd7f8": "Fournisseurs", "3b205a1c17c06fbd": "Favoris", + "a06eb47a82969918": "Sous-agent", "d567966a45ff32be": "Travail des sous-agents", "4740c38b2edd194d": "Lecture seule. Ces sous-agents ne peuvent pas recevoir de messages.", "5a0125dd9241cdec": "Chargement…", @@ -5722,7 +5716,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é", @@ -5816,14 +5809,13 @@ "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é", @@ -6499,7 +6491,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}}", @@ -9779,6 +9770,7 @@ "51497bd401292062": "Appui long", "9d6cc6ac23312071": "Double appui", "f001fa7b329c8fbf": "Masquer les réussis", + "ad208e3e32c85029": "Tout masquer", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Statut uniquement", "cf0f7fc3df26fa75": "Statut et messages", @@ -9988,6 +9980,7 @@ "573ea5fdf293a9d6": "Tous les checkouts", "470ad8c54049d1e1": "Rechercher des checkouts", "7e2dfdd9f97fc027": "Portée des projets", + "1cf216566c1ee064": "Projet indisponible", "c1b8c351aa90f319": [ { "t": "span", @@ -11020,6 +11013,7 @@ "af4c158f5758af59": "Contrôles de la barre latérale", "cddde869ea4ceb29": "Sélection de la barre latérale", "735a61ef214f6836": "Arrière-plan du terminal", + "afc8fb892e52f932": "Erreur", "16ad4c65b7cde1bb": "« {label} » n’a pas de palette claire. Créez un thème du même nom pour en ajouter une.", "0ec05a92bf5537a2": "« {label} » n’a pas de palette sombre. Créez un thème du même nom pour en ajouter une.", "a9cfdfa41271d7d4": "« {label} » a déjà une palette claire.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 6b18180841458..7e1f2ffd3af8b 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "そちらで削除された可能性があります。", "f7870ef3a4828ab1": "{label} の更新が必要です", "eabbf064657519ee": "{label} が {via} に応答していません", - "6ab96e26bda35288": "思考中", - "67733c48eaaec73a": "プラン", - "75aaf70eabf15f4b": "ファイル検索", - "ac511f991a3c1fab": "Web 検索", - "5e30649065b60d94": "承認リクエスト", - "5c8772e727c04218": "質問", - "a06eb47a82969918": "サブエージェント", - "646de37e0bec85f8": "ツール呼び出し", - "885ae08a2160a158": "コンテキストを圧縮しました", - "afc8fb892e52f932": "エラー", "f71597ae3afaef44": "{first} と {second}", "4047174839a16714": "{first}、{last}", "65ca7867c176afbf": "{first}、{rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "コンテキストの圧縮を停止しました", "2605da0149cd15f1": "コンテキストを圧縮しています", "39a82db18ca50c21": "コンテキストを圧縮しました ({before} → {after} トークン)", + "885ae08a2160a158": "コンテキストを圧縮しました", "3ab6b281a0991766": "{count, plural, =1 {リンクされたプルリクエストを確認しました} other {リンクされたプルリクエストを {count} 回確認しました}}", "857e92a89b6b6257": "{count, plural, other {{count} 個のファイルを読み取りました}}", "466ac7fcdb97bb76": "{count, plural, other {{count} 個のファイルを変更しました}}", @@ -1958,6 +1949,7 @@ "cf34b1bdf8179c16": "未コミット", "d85877d9ef77c50c": "変更", "b816058fba61e4d6": "ターン {count}", + "646de37e0bec85f8": "ツール呼び出し", "975c7fec8175f596": "コミット", "9614272348cc04cf": "最新のターン", "e6ae3a0fbf3eb49e": "この選択では差分ファイルの内容を利用できません。", @@ -3621,7 +3613,8 @@ "6bb5b1b35b2796ae": "{label}({via} 経由) · 作業中", "a73b7ab25d6e9bdf": "{label}({via} 経由)", "009e2ca841fdc1ef": "この環境", - "c8e6ea4d6313e912": "長いテキストのため、ここで省略されています。", + "8cb2e5692c4f05ab": "このビジュアルを見るには、{label} でこのスレッドを開いてください。", + "745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。", "0014ce0aaf1bd68a": "読み取り専用", "d0bda35aeec66684": [ "読み取り中: ", @@ -3632,8 +3625,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "以前のものを読み込む", - "048b8a737af895ac": "このスレッドにはまだ何もありません。", "c3e8cd9bf44e2f43": "以前に読み取った内容を表示しています。", "eb6e0584cf4a2a1d": "言語: {language}", "d76c606a3c519b78": "行の折り返しを無効にする", @@ -3707,7 +3698,9 @@ "9bbecec926c3b695": "再試行", "4fd8927b7afc2a92": "メッセージをコピー", "6f8651e48261911a": "思考", + "ac511f991a3c1fab": "Web 検索", "07e65dba2b16d3f7": "{count, plural, other {{path} と他 {count} 件}}", + "6ab96e26bda35288": "思考中", "4d4981a1c5bd9728": "コマンドを実行中", "a078225c5f197cd2": "失敗したコマンド", "37ab148aaa486051": "拒否されたコマンド", @@ -3806,6 +3799,7 @@ "afe27891aab8cf37": "{label}: 準備ができていません。", "2f77cc3105ddd7f8": "プロバイダー", "3b205a1c17c06fbd": "お気に入り", + "a06eb47a82969918": "サブエージェント", "d567966a45ff32be": "サブエージェントの作業", "4740c38b2edd194d": "読み取り専用です。これらのサブエージェントはメッセージを受け付けません。", "5a0125dd9241cdec": "読み込んでいます…", @@ -5704,7 +5698,6 @@ "4333d220c55ba5e4": "ワークスペースのクエリに失敗しました。", "422c1671dfcfe474": "''{path}'' は存在しません。", "20194b81e50497ad": "フォルダーを読み込めません。", - "745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。", "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", @@ -5798,14 +5791,13 @@ "b6a29fff7c7c0808": "なし", "54420465784bb1bd": "以前のコメントを読み込む", "9d82ebf35bfb4043": "まだアクティビティはありません。", - "1cf216566c1ee064": "利用できないプロジェクト", "b5ddadeb0810688c": "状態", "93c1fc19d9bf1db0": "関与", "d5a8b335d88b65bc": "{hidden} 件非表示", "2160067266a61dd8": "すべて", "cd4ec4acf33c65b9": "{count, plural, other {{count} 個のラベル}}", "bfd20acb8b7dee6b": "すべてのユーザー", - "ad208e3e32c85029": "すべて非表示", + "aead644e2cf1233f": "すべて表示", "77ce79d865716719": "一致するプロジェクトはありません。", "af7eb4f9c7f0f575": "フィルター", "08247dd39b0c85ff": "担当者", @@ -6468,7 +6460,6 @@ "64d0189be492147c": "チェックの詳細を開けません", "600347ca50400a54": "チェックを読み込んでいます…", "1b381201aba745c2": "報告されたチェックはありません", - "aead644e2cf1233f": "すべて表示", "a6d75a4380173c60": "チェックを開く: {summary}", "be3d1766bad18693": "チェック: {summary}", "425e4a3d6c5c2867": "{count, plural, other {{count} 件失敗}}", @@ -9731,6 +9722,7 @@ "51497bd401292062": "長押し", "9d6cc6ac23312071": "2 回押し", "f001fa7b329c8fbf": "成功したものを非表示", + "ad208e3e32c85029": "すべて非表示", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "ステータスのみ", "cf0f7fc3df26fa75": "ステータスとメッセージ", @@ -9940,6 +9932,7 @@ "573ea5fdf293a9d6": "すべてのチェックアウト", "470ad8c54049d1e1": "チェックアウトを検索", "7e2dfdd9f97fc027": "プロジェクトの範囲", + "1cf216566c1ee064": "利用できないプロジェクト", "c1b8c351aa90f319": [ { "t": "span", @@ -10970,6 +10963,7 @@ "af4c158f5758af59": "サイドバーのコントロール", "cddde869ea4ceb29": "サイドバーの選択", "735a61ef214f6836": "ターミナルの背景", + "afc8fb892e52f932": "エラー", "16ad4c65b7cde1bb": "「{label}」にはライトのパレットがありません。追加するには同じ名前のテーマを作成してください。", "0ec05a92bf5537a2": "「{label}」にはダークのパレットがありません。追加するには同じ名前のテーマを作成してください。", "a9cfdfa41271d7d4": "「{label}」にはすでにライトのパレットがあります。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 3a258ad397d7e..91d52b3521c62 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "그곳에서 삭제되었을 수 있습니다.", "f7870ef3a4828ab1": "{label}을(를) 업데이트해야 합니다", "eabbf064657519ee": "{label}이(가) {via}에 응답하지 않습니다", - "6ab96e26bda35288": "생각 중", - "67733c48eaaec73a": "계획", - "75aaf70eabf15f4b": "파일 검색", - "ac511f991a3c1fab": "웹 검색", - "5e30649065b60d94": "승인 요청", - "5c8772e727c04218": "질문", - "a06eb47a82969918": "서브에이전트", - "646de37e0bec85f8": "도구 호출", - "885ae08a2160a158": "컨텍스트 압축됨", - "afc8fb892e52f932": "오류", "f71597ae3afaef44": "{first} 및 {second}", "4047174839a16714": "{first} 및 {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "컨텍스트 압축 중지됨", "2605da0149cd15f1": "컨텍스트 압축 중", "39a82db18ca50c21": "컨텍스트 압축됨: 토큰 {before} → {after}", + "885ae08a2160a158": "컨텍스트 압축됨", "3ab6b281a0991766": "{count, plural, =1 {연결된 풀 리퀘스트 확인함} other {연결된 풀 리퀘스트 {count}번 확인함}}", "857e92a89b6b6257": "{count, plural, other {파일 {count}개 읽음}}", "466ac7fcdb97bb76": "{count, plural, other {파일 {count}개 변경함}}", @@ -1960,6 +1951,7 @@ "cf34b1bdf8179c16": "커밋되지 않음", "d85877d9ef77c50c": "변경 사항", "b816058fba61e4d6": "턴 {count}", + "646de37e0bec85f8": "도구 호출", "975c7fec8175f596": "커밋", "9614272348cc04cf": "최근 턴", "e6ae3a0fbf3eb49e": "이 선택 항목의 변경된 파일 내용을 사용할 수 없습니다.", @@ -3621,7 +3613,8 @@ "6bb5b1b35b2796ae": "{label} ({via} 경유) · 작업 중", "a73b7ab25d6e9bdf": "{label} ({via} 경유)", "009e2ca841fdc1ef": "이 환경", - "c8e6ea4d6313e912": "긴 텍스트라 여기에서 잘렸습니다.", + "8cb2e5692c4f05ab": "이 시각 자료를 보려면 {label}에서 이 스레드를 여세요.", + "745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.", "0014ce0aaf1bd68a": "읽기 전용", "d0bda35aeec66684": [ "읽는 중: ", @@ -3632,8 +3625,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "이전 항목 불러오기", - "048b8a737af895ac": "이 스레드에는 아직 아무것도 없습니다.", "c3e8cd9bf44e2f43": "이전에 읽은 내용을 표시하고 있습니다.", "eb6e0584cf4a2a1d": "언어: {language}", "d76c606a3c519b78": "줄 바꿈 끄기", @@ -3707,7 +3698,9 @@ "9bbecec926c3b695": "다시 시도", "4fd8927b7afc2a92": "메시지 복사", "6f8651e48261911a": "생각", + "ac511f991a3c1fab": "웹 검색", "07e65dba2b16d3f7": "{count, plural, other {{path} 외 {count}개}}", + "6ab96e26bda35288": "생각 중", "4d4981a1c5bd9728": "명령 실행 중", "a078225c5f197cd2": "명령 실패", "37ab148aaa486051": "명령 거부됨", @@ -3804,6 +3797,7 @@ "afe27891aab8cf37": "{label}: 준비되지 않음.", "2f77cc3105ddd7f8": "제공자", "3b205a1c17c06fbd": "즐겨찾기", + "a06eb47a82969918": "서브에이전트", "d567966a45ff32be": "서브에이전트 작업", "4740c38b2edd194d": "읽기 전용입니다. 이 서브에이전트는 메시지를 받을 수 없습니다.", "5a0125dd9241cdec": "불러오는 중…", @@ -5702,7 +5696,6 @@ "4333d220c55ba5e4": "작업 영역 쿼리에 실패했습니다.", "422c1671dfcfe474": "''{path}''이(가) 없습니다.", "20194b81e50497ad": "폴더를 불러올 수 없습니다.", - "745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.", "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", @@ -5796,14 +5789,13 @@ "b6a29fff7c7c0808": "없음", "54420465784bb1bd": "이전 댓글 불러오기", "9d82ebf35bfb4043": "아직 활동이 없습니다.", - "1cf216566c1ee064": "사용할 수 없는 프로젝트", "b5ddadeb0810688c": "상태", "93c1fc19d9bf1db0": "참여", "d5a8b335d88b65bc": "{hidden}개 숨김", "2160067266a61dd8": "전체", "cd4ec4acf33c65b9": "{count, plural, other {레이블 {count}개}}", "bfd20acb8b7dee6b": "모든 사람", - "ad208e3e32c85029": "모두 숨기기", + "aead644e2cf1233f": "모두 표시", "77ce79d865716719": "일치하는 프로젝트가 없습니다.", "af7eb4f9c7f0f575": "필터", "08247dd39b0c85ff": "담당자", @@ -6470,7 +6462,6 @@ "64d0189be492147c": "검사 세부 정보를 열 수 없습니다", "600347ca50400a54": "검사를 불러오는 중…", "1b381201aba745c2": "보고된 검사 없음", - "aead644e2cf1233f": "모두 표시", "a6d75a4380173c60": "검사 열기: {summary}", "be3d1766bad18693": "검사: {summary}", "425e4a3d6c5c2867": "{count, plural, other {{count}개 실패}}", @@ -9734,6 +9725,7 @@ "51497bd401292062": "길게 누르기", "9d6cc6ac23312071": "두 번 누르기", "f001fa7b329c8fbf": "성공한 항목 숨기기", + "ad208e3e32c85029": "모두 숨기기", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "상태만", "cf0f7fc3df26fa75": "상태 및 메시지", @@ -9943,6 +9935,7 @@ "573ea5fdf293a9d6": "모든 체크아웃", "470ad8c54049d1e1": "체크아웃 검색", "7e2dfdd9f97fc027": "프로젝트 범위", + "1cf216566c1ee064": "사용할 수 없는 프로젝트", "c1b8c351aa90f319": [ { "t": "span", @@ -10967,6 +10960,7 @@ "af4c158f5758af59": "사이드바 컨트롤", "cddde869ea4ceb29": "사이드바 선택 항목", "735a61ef214f6836": "터미널 배경", + "afc8fb892e52f932": "오류", "16ad4c65b7cde1bb": "“{label}”에는 밝은 팔레트가 없습니다. 추가하려면 같은 이름으로 테마를 만드세요.", "0ec05a92bf5537a2": "“{label}”에는 어두운 팔레트가 없습니다. 추가하려면 같은 이름으로 테마를 만드세요.", "a9cfdfa41271d7d4": "“{label}”에는 이미 밝은 팔레트가 있습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 802ff10cfb544..446315b7af36e 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "Talvez tenha sido excluída lá.", "f7870ef3a4828ab1": "{label} precisa de uma atualização", "eabbf064657519ee": "{label} não está respondendo a {via}", - "6ab96e26bda35288": "Pensando", - "67733c48eaaec73a": "Plano", - "75aaf70eabf15f4b": "Pesquisa de arquivos", - "ac511f991a3c1fab": "Pesquisa na web", - "5e30649065b60d94": "Solicitação de aprovação", - "5c8772e727c04218": "Pergunta", - "a06eb47a82969918": "Subagente", - "646de37e0bec85f8": "Chamada de ferramenta", - "885ae08a2160a158": "Contexto compactado", - "afc8fb892e52f932": "Erro", "f71597ae3afaef44": "{first} e {second}", "4047174839a16714": "{first} e {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "Compactação do contexto interrompida", "2605da0149cd15f1": "Compactando o contexto", "39a82db18ca50c21": "Contexto compactado de {before} → {after} tokens", + "885ae08a2160a158": "Contexto compactado", "3ab6b281a0991766": "{count, plural, =1 {Verificou os pull requests vinculados} other {Verificou os pull requests vinculados {count} vezes}}", "857e92a89b6b6257": "{count, plural, one {Leu {count} arquivo} other {Leu {count} arquivos}}", "466ac7fcdb97bb76": "{count, plural, one {Alterou {count} arquivo} other {Alterou {count} arquivos}}", @@ -1960,6 +1951,7 @@ "cf34b1bdf8179c16": "Sem commit", "d85877d9ef77c50c": "Alterações", "b816058fba61e4d6": "Turno {count}", + "646de37e0bec85f8": "Chamada de ferramenta", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Último turno", "e6ae3a0fbf3eb49e": "O conteúdo dos arquivos do diff não está disponível para esta seleção.", @@ -3626,7 +3618,8 @@ "6bb5b1b35b2796ae": "Em {label} via {via} · Trabalhando", "a73b7ab25d6e9bdf": "Em {label} via {via}", "009e2ca841fdc1ef": "este ambiente", - "c8e6ea4d6313e912": "Texto longo, cortado aqui.", + "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 ", @@ -3637,8 +3630,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "Carregar anteriores", - "048b8a737af895ac": "Ainda não há nada nesta thread.", "c3e8cd9bf44e2f43": "Mostrando o que foi lido antes.", "eb6e0584cf4a2a1d": "Linguagem: {language}", "d76c606a3c519b78": "Desativar quebra de linha", @@ -3714,7 +3705,9 @@ "9bbecec926c3b695": "Tentar novamente", "4fd8927b7afc2a92": "Copiar mensagem", "6f8651e48261911a": "Raciocínio", + "ac511f991a3c1fab": "Pesquisa na web", "07e65dba2b16d3f7": "{count, plural, one {{path} e mais {count}} other {{path} e mais {count}}}", + "6ab96e26bda35288": "Pensando", "4d4981a1c5bd9728": "Executando comando", "a078225c5f197cd2": "Comando com falha", "37ab148aaa486051": "Comando recusado", @@ -3813,6 +3806,7 @@ "afe27891aab8cf37": "{label}: não está pronto.", "2f77cc3105ddd7f8": "Provedores", "3b205a1c17c06fbd": "Favoritos", + "a06eb47a82969918": "Subagente", "d567966a45ff32be": "Trabalho de subagentes", "4740c38b2edd194d": "Somente leitura. Estes subagentes não aceitam mensagens.", "5a0125dd9241cdec": "Carregando…", @@ -5721,7 +5715,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", @@ -5815,14 +5808,13 @@ "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", @@ -6498,7 +6490,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}}", @@ -9778,6 +9769,7 @@ "51497bd401292062": "Manter pressionado", "9d6cc6ac23312071": "Pressionar duas vezes", "f001fa7b329c8fbf": "Ocultar bem-sucedidas", + "ad208e3e32c85029": "Ocultar todas", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Só status", "cf0f7fc3df26fa75": "Status e mensagens", @@ -9987,6 +9979,7 @@ "573ea5fdf293a9d6": "Todos os checkouts", "470ad8c54049d1e1": "Pesquisar checkouts", "7e2dfdd9f97fc027": "Escopo de projeto", + "1cf216566c1ee064": "Projeto indisponível", "c1b8c351aa90f319": [ { "t": "span", @@ -11019,6 +11012,7 @@ "af4c158f5758af59": "Controles da barra lateral", "cddde869ea4ceb29": "Seleção da barra lateral", "735a61ef214f6836": "Fundo do terminal", + "afc8fb892e52f932": "Erro", "16ad4c65b7cde1bb": "“{label}” não tem paleta clara. Crie um tema com o mesmo nome para adicionar uma.", "0ec05a92bf5537a2": "“{label}” não tem paleta escura. Crie um tema com o mesmo nome para adicionar uma.", "a9cfdfa41271d7d4": "“{label}” já tem uma paleta clara.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index e5fd1efed481b..189746a06c277 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "Возможно, его там удалили.", "f7870ef3a4828ab1": "{label} нужно обновить", "eabbf064657519ee": "{label} не отвечает {via}", - "6ab96e26bda35288": "Думает", - "67733c48eaaec73a": "План", - "75aaf70eabf15f4b": "Поиск файлов", - "ac511f991a3c1fab": "Поиск в интернете", - "5e30649065b60d94": "Запрос подтверждения", - "5c8772e727c04218": "Вопрос", - "a06eb47a82969918": "Субагент", - "646de37e0bec85f8": "Вызов инструмента", - "885ae08a2160a158": "Контекст сжат", - "afc8fb892e52f932": "Ошибка", "f71597ae3afaef44": "{first} и {second}", "4047174839a16714": "{first} и {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "Сжатие контекста остановлено", "2605da0149cd15f1": "Сжатие контекста", "39a82db18ca50c21": "Контекст сжат: {before} → {after} токенов", + "885ae08a2160a158": "Контекст сжат", "3ab6b281a0991766": "{count, plural, =1 {Проверены привязанные пул-реквесты} one {Привязанные пул-реквесты проверены {count} раз} few {Привязанные пул-реквесты проверены {count} раза} many {Привязанные пул-реквесты проверены {count} раз} other {Привязанные пул-реквесты проверены {count} раза}}", "857e92a89b6b6257": "{count, plural, one {Прочитан {count} файл} few {Прочитано {count} файла} many {Прочитано {count} файлов} other {Прочитано {count} файла}}", "466ac7fcdb97bb76": "{count, plural, one {Изменён {count} файл} few {Изменено {count} файла} many {Изменено {count} файлов} other {Изменено {count} файла}}", @@ -1960,6 +1951,7 @@ "cf34b1bdf8179c16": "Без коммита", "d85877d9ef77c50c": "Изменения", "b816058fba61e4d6": "Ход {count}", + "646de37e0bec85f8": "Вызов инструмента", "975c7fec8175f596": "Коммит", "9614272348cc04cf": "Последний ход", "e6ae3a0fbf3eb49e": "Содержимое файлов диффа недоступно для этого выбора.", @@ -3626,7 +3618,8 @@ "6bb5b1b35b2796ae": "На {label} через {via} · Работает", "a73b7ab25d6e9bdf": "На {label} через {via}", "009e2ca841fdc1ef": "это окружение", - "c8e6ea4d6313e912": "Длинный текст, здесь обрезан.", + "8cb2e5692c4f05ab": "Откройте этот тред на {label}, чтобы увидеть это визуальное представление.", + "745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.", "0014ce0aaf1bd68a": "Только чтение", "d0bda35aeec66684": [ "Чтение с ", @@ -3637,8 +3630,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "Загрузить более ранние", - "048b8a737af895ac": "В этом треде пока ничего нет.", "c3e8cd9bf44e2f43": "Показано то, что было прочитано раньше.", "eb6e0584cf4a2a1d": "Язык: {language}", "d76c606a3c519b78": "Отключить перенос строк", @@ -3714,7 +3705,9 @@ "9bbecec926c3b695": "Повторить", "4fd8927b7afc2a92": "Копировать сообщение", "6f8651e48261911a": "Размышление", + "ac511f991a3c1fab": "Поиск в интернете", "07e65dba2b16d3f7": "{count, plural, one {{path} и ещё {count}} few {{path} и ещё {count}} many {{path} и ещё {count}} other {{path} и ещё {count}}}", + "6ab96e26bda35288": "Думает", "4d4981a1c5bd9728": "Выполняется команда", "a078225c5f197cd2": "Команда с ошибкой", "37ab148aaa486051": "Команда отклонена", @@ -3813,6 +3806,7 @@ "afe27891aab8cf37": "{label}: не готов.", "2f77cc3105ddd7f8": "Провайдеры", "3b205a1c17c06fbd": "Избранное", + "a06eb47a82969918": "Субагент", "d567966a45ff32be": "Работа субагентов", "4740c38b2edd194d": "Только чтение. Этим субагентам нельзя отправлять сообщения.", "5a0125dd9241cdec": "Загрузка…", @@ -5721,7 +5715,6 @@ "4333d220c55ba5e4": "Ошибка запроса к рабочей области.", "422c1671dfcfe474": "''{path}'' не существует.", "20194b81e50497ad": "Не удалось загрузить папку.", - "745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.", "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", @@ -5815,14 +5808,13 @@ "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": "Исполнитель", @@ -6498,7 +6490,6 @@ "64d0189be492147c": "Не удалось открыть подробности проверки", "600347ca50400a54": "Загрузка проверок…", "1b381201aba745c2": "Нет проверок", - "aead644e2cf1233f": "Показать все", "a6d75a4380173c60": "Открыть проверки: {summary}", "be3d1766bad18693": "Проверки: {summary}", "425e4a3d6c5c2867": "{count, plural, one {Ошибок: {count}} few {Ошибок: {count}} many {Ошибок: {count}} other {Ошибок: {count}}}", @@ -9781,6 +9772,7 @@ "51497bd401292062": "Удержание", "9d6cc6ac23312071": "Двойное нажатие", "f001fa7b329c8fbf": "Скрывать успешные", + "ad208e3e32c85029": "Скрывать все", "c80e4bb3201efd71": "Дзен", "0cb9ffcd1fb46b0c": "Только статус", "cf0f7fc3df26fa75": "Статус и сообщения", @@ -9990,6 +9982,7 @@ "573ea5fdf293a9d6": "Все копии", "470ad8c54049d1e1": "Поиск копий", "7e2dfdd9f97fc027": "Область проектов", + "1cf216566c1ee064": "Проект недоступен", "c1b8c351aa90f319": [ { "t": "span", @@ -11020,6 +11013,7 @@ "af4c158f5758af59": "Элементы боковой панели", "cddde869ea4ceb29": "Выделение на боковой панели", "735a61ef214f6836": "Фон терминала", + "afc8fb892e52f932": "Ошибка", "16ad4c65b7cde1bb": "У «{label}» нет светлой палитры. Чтобы добавить её, создайте тему с тем же названием.", "0ec05a92bf5537a2": "У «{label}» нет тёмной палитры. Чтобы добавить её, создайте тему с тем же названием.", "a9cfdfa41271d7d4": "У «{label}» уже есть светлая палитра.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index f2517b305b446..5c0252912fdc8 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "Den kan ha raderats där.", "f7870ef3a4828ab1": "{label} behöver uppdateras", "eabbf064657519ee": "{label} svarar inte {via}", - "6ab96e26bda35288": "Tänker", - "67733c48eaaec73a": "Plan", - "75aaf70eabf15f4b": "Filsökning", - "ac511f991a3c1fab": "Webbsökning", - "5e30649065b60d94": "Begäran om godkännande", - "5c8772e727c04218": "Fråga", - "a06eb47a82969918": "Subagent", - "646de37e0bec85f8": "Verktygsanrop", - "885ae08a2160a158": "Kontexten komprimerades", - "afc8fb892e52f932": "Fel", "f71597ae3afaef44": "{first} och {second}", "4047174839a16714": "{first} och {last}", "65ca7867c176afbf": "{first}, {rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "Kontextkomprimeringen stoppades", "2605da0149cd15f1": "Komprimerar kontext", "39a82db18ca50c21": "Kontexten komprimerades {before} → {after} token", + "885ae08a2160a158": "Kontexten komprimerades", "3ab6b281a0991766": "{count, plural, =1 {Kontrollerade länkade pull requests} other {Kontrollerade länkade pull requests {count} gånger}}", "857e92a89b6b6257": "{count, plural, one {Läste {count} fil} other {Läste {count} filer}}", "466ac7fcdb97bb76": "{count, plural, one {Ändrade {count} fil} other {Ändrade {count} filer}}", @@ -1960,6 +1951,7 @@ "cf34b1bdf8179c16": "Ej committat", "d85877d9ef77c50c": "Ändringar", "b816058fba61e4d6": "Omgång {count}", + "646de37e0bec85f8": "Verktygsanrop", "975c7fec8175f596": "Commit", "9614272348cc04cf": "Senaste omgången", "e6ae3a0fbf3eb49e": "Diffens filinnehåll är inte tillgängligt för den här markeringen.", @@ -3626,7 +3618,8 @@ "6bb5b1b35b2796ae": "På {label} via {via} · Arbetar", "a73b7ab25d6e9bdf": "På {label} via {via}", "009e2ca841fdc1ef": "den här miljön", - "c8e6ea4d6313e912": "Lång text, avkortad här.", + "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 ", @@ -3637,8 +3630,6 @@ }, "…" ], - "50fb8b2ca3db6cad": "Läs in tidigare", - "048b8a737af895ac": "Inget i den här tråden ännu.", "c3e8cd9bf44e2f43": "Visar det som lästes tidigare.", "eb6e0584cf4a2a1d": "Språk: {language}", "d76c606a3c519b78": "Inaktivera radbrytning", @@ -3714,7 +3705,9 @@ "9bbecec926c3b695": "Försök igen", "4fd8927b7afc2a92": "Kopiera meddelande", "6f8651e48261911a": "Tanke", + "ac511f991a3c1fab": "Webbsökning", "07e65dba2b16d3f7": "{count, plural, one {{path} +{count} till} other {{path} +{count} till}}", + "6ab96e26bda35288": "Tänker", "4d4981a1c5bd9728": "Kör kommando", "a078225c5f197cd2": "Misslyckat kommando", "37ab148aaa486051": "Avböjt kommando", @@ -3813,6 +3806,7 @@ "afe27891aab8cf37": "{label}: Inte redo.", "2f77cc3105ddd7f8": "Leverantörer", "3b205a1c17c06fbd": "Favoriter", + "a06eb47a82969918": "Subagent", "d567966a45ff32be": "Subagentarbete", "4740c38b2edd194d": "Endast läsning. De här subagenterna kan inte ta emot meddelanden.", "5a0125dd9241cdec": "Läser in…", @@ -5722,7 +5716,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", @@ -5816,14 +5809,13 @@ "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", @@ -6504,7 +6496,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}}", @@ -9787,6 +9778,7 @@ "51497bd401292062": "Håll ned", "9d6cc6ac23312071": "Dubbeltryck", "f001fa7b329c8fbf": "Dölj lyckade", + "ad208e3e32c85029": "Dölj alla", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Endast status", "cf0f7fc3df26fa75": "Status och meddelanden", @@ -9996,6 +9988,7 @@ "573ea5fdf293a9d6": "Alla utcheckningar", "470ad8c54049d1e1": "Sök utcheckningar", "7e2dfdd9f97fc027": "Projektomfång", + "1cf216566c1ee064": "Projektet är inte tillgängligt", "c1b8c351aa90f319": [ { "t": "span", @@ -11028,6 +11021,7 @@ "af4c158f5758af59": "Sidofältets kontroller", "cddde869ea4ceb29": "Sidofältets markering", "735a61ef214f6836": "Terminalens bakgrund", + "afc8fb892e52f932": "Fel", "16ad4c65b7cde1bb": "”{label}” har ingen ljus palett. Skapa ett tema med samma namn för att lägga till en.", "0ec05a92bf5537a2": "”{label}” har ingen mörk palett. Skapa ett tema med samma namn för att lägga till en.", "a9cfdfa41271d7d4": "”{label}” har redan en ljus palett.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 230c2e5993c95..33c979c0cd911 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -107,16 +107,6 @@ "bd29efc163476e72": "它可能已在那里被删除。", "f7870ef3a4828ab1": "{label} 需要更新", "eabbf064657519ee": "{label} 没有响应 {via}", - "6ab96e26bda35288": "正在思考", - "67733c48eaaec73a": "计划", - "75aaf70eabf15f4b": "文件搜索", - "ac511f991a3c1fab": "网络搜索", - "5e30649065b60d94": "审批请求", - "5c8772e727c04218": "问题", - "a06eb47a82969918": "子智能体", - "646de37e0bec85f8": "工具调用", - "885ae08a2160a158": "上下文已压缩", - "afc8fb892e52f932": "错误", "f71597ae3afaef44": "{first} 和 {second}", "4047174839a16714": "{first} 和 {last}", "65ca7867c176afbf": "{first}、{rest}", @@ -892,6 +882,7 @@ "3277065a791a0e06": "上下文压缩已停止", "2605da0149cd15f1": "正在压缩上下文", "39a82db18ca50c21": "上下文已压缩:{before} → {after} token", + "885ae08a2160a158": "上下文已压缩", "3ab6b281a0991766": "{count, plural, =1 {已检查关联的 pull request } other {已检查关联的 pull request {count} 次}}", "857e92a89b6b6257": "{count, plural, other {已读取 {count} 个文件}}", "466ac7fcdb97bb76": "{count, plural, other {已更改 {count} 个文件}}", @@ -1962,6 +1953,7 @@ "cf34b1bdf8179c16": "未提交的更改", "d85877d9ef77c50c": "改动", "b816058fba61e4d6": "第 {count} 轮", + "646de37e0bec85f8": "工具调用", "975c7fec8175f596": "提交", "9614272348cc04cf": "最近一轮", "e6ae3a0fbf3eb49e": "此选择没有可用的差异文件内容。", @@ -3631,7 +3623,8 @@ "6bb5b1b35b2796ae": "位于 {label},经由 {via} · 运行中", "a73b7ab25d6e9bdf": "位于 {label},经由 {via}", "009e2ca841fdc1ef": "此环境", - "c8e6ea4d6313e912": "文本较长,此处已截断。", + "8cb2e5692c4f05ab": "在 {label} 上打开此会话即可查看此可视内容。", + "745a0b899008618c": "无法加载更早的对话。请重试。", "0014ce0aaf1bd68a": "只读", "d0bda35aeec66684": [ "正在从 ", @@ -3642,8 +3635,6 @@ }, " 读取…" ], - "50fb8b2ca3db6cad": "加载更早的内容", - "048b8a737af895ac": "此会话中还没有内容。", "c3e8cd9bf44e2f43": "正在显示之前读取的内容。", "eb6e0584cf4a2a1d": "语言:{language}", "d76c606a3c519b78": "取消自动换行", @@ -3718,7 +3709,9 @@ "9bbecec926c3b695": "重试", "4fd8927b7afc2a92": "复制消息", "6f8651e48261911a": "已思考", + "ac511f991a3c1fab": "网络搜索", "07e65dba2b16d3f7": "{count, plural, other {{path},另有 {count} 个}}", + "6ab96e26bda35288": "正在思考", "4d4981a1c5bd9728": "正在运行命令", "a078225c5f197cd2": "命令失败", "37ab148aaa486051": "已拒绝命令", @@ -3817,6 +3810,7 @@ "afe27891aab8cf37": "{label}:未就绪。", "2f77cc3105ddd7f8": "智能体提供方", "3b205a1c17c06fbd": "收藏", + "a06eb47a82969918": "子智能体", "d567966a45ff32be": "子智能体工作", "4740c38b2edd194d": "只读。这些子智能体无法接收消息。", "5a0125dd9241cdec": "加载中…", @@ -5728,7 +5722,6 @@ "4333d220c55ba5e4": "工作区查询失败。", "422c1671dfcfe474": "''{path}'' 不存在。", "20194b81e50497ad": "无法加载文件夹。", - "745a0b899008618c": "无法加载更早的对话。请重试。", "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", @@ -5822,14 +5815,13 @@ "b6a29fff7c7c0808": "无", "54420465784bb1bd": "加载较早的评论", "9d82ebf35bfb4043": "这里还没有任何动态。", - "1cf216566c1ee064": "不可用的项目", "b5ddadeb0810688c": "状态", "93c1fc19d9bf1db0": "参与方式", "d5a8b335d88b65bc": "已隐藏 {hidden} 个", "2160067266a61dd8": "任意", "cd4ec4acf33c65b9": "{count, plural, other {{count} 个标签}}", "bfd20acb8b7dee6b": "任何人", - "ad208e3e32c85029": "全部隐藏", + "aead644e2cf1233f": "全部显示", "77ce79d865716719": "没有匹配的项目。", "af7eb4f9c7f0f575": "筛选条件", "08247dd39b0c85ff": "受理人", @@ -6510,7 +6502,6 @@ "64d0189be492147c": "无法打开检查详情", "600347ca50400a54": "正在加载检查…", "1b381201aba745c2": "未报告任何检查", - "aead644e2cf1233f": "全部显示", "a6d75a4380173c60": "打开检查:{summary}", "be3d1766bad18693": "检查:{summary}", "425e4a3d6c5c2867": "{count, plural, other {{count} 个失败}}", @@ -9794,6 +9785,7 @@ "51497bd401292062": "长按", "9d6cc6ac23312071": "连按两次", "f001fa7b329c8fbf": "隐藏成功的调用", + "ad208e3e32c85029": "全部隐藏", "c80e4bb3201efd71": "专注模式", "0cb9ffcd1fb46b0c": "仅状态", "cf0f7fc3df26fa75": "状态和消息", @@ -10003,6 +9995,7 @@ "573ea5fdf293a9d6": "所有工作副本", "470ad8c54049d1e1": "搜索工作副本", "7e2dfdd9f97fc027": "项目范围", + "1cf216566c1ee064": "不可用的项目", "c1b8c351aa90f319": [ { "t": "span", @@ -11041,6 +11034,7 @@ "af4c158f5758af59": "侧边栏控件", "cddde869ea4ceb29": "侧边栏选中项", "735a61ef214f6836": "终端背景", + "afc8fb892e52f932": "错误", "16ad4c65b7cde1bb": "“{label}”没有浅色调色板。创建同名主题即可添加。", "0ec05a92bf5537a2": "“{label}”没有深色调色板。创建同名主题即可添加。", "a9cfdfa41271d7d4": "“{label}”已有浅色调色板。", diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index cca27c4d290a0..63145c73119d6 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -1,22 +1,20 @@ import { useAtomValue } from "@effect/atom-react"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { - createLinkedThreadSession, type LinkedThreadOpen, resolveLinkedThreadOpen, } from "@t3tools/client-runtime/linked-thread"; -import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; import { useNavigate } from "@tanstack/react-router"; -import { Atom } from "effect/reactivity"; -import { useSyncExternalStore } from "react"; +import { AsyncResult, Atom } from "effect/reactivity"; +import type { TurnItemSource } from "../components/chat/timelineRowContext"; import { useRightPanelStore } from "../rightPanelStore"; -import { getDocumentActivity } from "../lib/documentActivity"; 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 @@ -69,7 +67,7 @@ export function useLinkedThreadOpener( }; } -type SessionKey = readonly [ +type TabKey = readonly [ panelEnvironmentId: EnvironmentId, panelThreadId: ThreadId, surfaceId: string, @@ -78,53 +76,39 @@ type SessionKey = readonly [ threadId: ThreadId, ]; -/** - * One tab's reads. It outlives the pane for a while, so coming back to the tab shows what was - * read and carries on from there; a session nothing subscribes to asks for nothing. - */ -const linkedThreadSessionAtom = Atom.family((key: string) => { +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 SessionKey; + JSON.parse(key) as TabKey; const panelRef = scopeThreadRef(panelEnvironmentId, panelThreadId); - return Atom.make((get) => - createLinkedThreadSession({ - read: async (cursor) => { - const result = await runAtomCommand( - get.registry, - peerLinkEnvironment.readThread, - { environmentId: viaEnvironmentId, input: { environmentId, threadId, ...cursor } }, - { reportFailure: false, reportDefect: false }, - ); - if (result._tag !== "Success") { - return { ok: false, error: squashAtomCommandFailure(result) }; - } - return { ok: true, page: result.value }; - }, - onRead: (page) => { - const { title } = page.thread; - if (title) useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); - }, - schedule: (run, delayMs) => { - const timer = setTimeout(run, delayMs); - return () => clearTimeout(timer); - }, - isActive: () => getDocumentActivity().visible, - }), - ).pipe(Atom.setIdleTTL(5 * 60_000), Atom.withLabel(`linked-thread-session:${key}`)); + 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}`)); }); -const noSubscription = () => () => {}; - /** - * The transcript of `surface`, read through the environment that links to it for the tab in - * `panelRef`'s panel. Reads run only while `visible`. + * 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 useLinkedThreadSession( +export function useLinkedThreadView( panelRef: ScopedThreadRef, surface: Pick, visible: boolean, ) { - const key: SessionKey = [ + const key: TabKey = [ panelRef.environmentId, panelRef.threadId, surface.id, @@ -132,11 +116,24 @@ export function useLinkedThreadSession( surface.environmentId, surface.threadId, ]; - const session = useAtomValue(linkedThreadSessionAtom(JSON.stringify(key))); - const state = useSyncExternalStore( - visible ? session.subscribe : noSubscription, - session.getSnapshot, - session.getSnapshot, - ); - return { state, session }; + 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/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 434e97f0b3d62..1f6e221b3ebe5 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -481,12 +481,15 @@ fails with that reason. 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 its transcript opens read-only, fetched by the machine you are -connected to over its link. It follows the thread while it runs. On web and -desktop it opens as a tab in the right panel, beside the thread you are in. +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 diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 6f3e396d27376..0663ee293e2e8 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -267,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/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index c36dca8359dbb..e5292291b9fb3 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -1,361 +1,120 @@ -import { EnvironmentId, type PeerLinkThreadPage, ThreadId, TurnItemId } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +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 { - createLinkedThreadSession, - type LinkedThreadCursor, - type LinkedThreadReadResult, - presentLinkedThreadItem, - LINKED_THREAD_ACTIVE_POLL_MS, - LINKED_THREAD_IDLE_POLL_MS, - linkedThreadRefreshCursor, - mergeLinkedThreadPage, - resolveLinkedThreadOpen, + followLinkedThread, + LINKED_THREAD_RETRY_MS, + type LinkedThreadView, } from "./linkedThread.ts"; - -const nucbox = EnvironmentId.make("environment-nucbox"); -const vm = EnvironmentId.make("environment-vm"); -const threadId = ThreadId.make("thread:vm"); - -const item = ( - position: number, - text: string, - status: PeerLinkThreadPage["items"][number]["status"] = "completed", -): PeerLinkThreadPage["items"][number] => ({ - position, - visibility: "local", - sourceThreadId: threadId, - itemId: TurnItemId.make(`item:${position}`), - runId: null, - messageId: null, - createdBy: null, - creationSource: null, - type: "assistant_message", - status, - title: null, - text, - textTruncated: false, - updatedAt: "2026-11-19T00:00:00.000Z", -}); - -const page = ( - items: PeerLinkThreadPage["items"], - overrides: Partial = {}, -): PeerLinkThreadPage => ({ - label: "VM", - thread: { threadId, title: "Fix the build", status: "running", model: "gpt-5" }, - items, - earlierPosition: null, - hasMore: false, - ...overrides, -}); - -describe("resolveLinkedThreadOpen", () => { - const open = (own: { connected: boolean } | undefined, linked: boolean) => - resolveLinkedThreadOpen({ environmentId: vm, viaEnvironmentId: nucbox, own, linked }); - - it("keeps the client's own connection when it has one", () => { - expect(open({ connected: true }, true)).toBe("direct"); - }); - - it("reads through the link when the client is not connected to that environment", () => { - expect(open(undefined, true)).toBe("linked"); - expect(open({ connected: false }, true)).toBe("linked"); - }); - - it("falls back to what the client can do alone when nothing links there", () => { - expect(open({ connected: false }, false)).toBe("direct"); - expect(open(undefined, false)).toBe("unavailable"); - }); - - it("never routes an environment's own thread through a link", () => { - expect( - resolveLinkedThreadOpen({ - environmentId: nucbox, - viaEnvironmentId: nucbox, - own: undefined, - linked: true, - }), - ).toBe("direct"); - }); +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, }); -describe("mergeLinkedThreadPage", () => { - const newest = mergeLinkedThreadPage( - null, - page([item(10, "ten"), item(11, "eleven", "running")], { earlierPosition: 10 }), - "later", - ); - - it("moves the start back with an earlier page and keeps the forward state", () => { - const merged = mergeLinkedThreadPage( - newest, - page([item(8, "eight"), item(9, "nine")], { earlierPosition: null, hasMore: true }), - "earlier", - ); - expect(merged.items.map((entry) => entry.position)).toEqual([8, 9, 10, 11]); - expect(merged.earlierPosition).toBeNull(); - expect(merged.hasMore).toBe(false); - }); - - it("replaces a re-read item and appends what followed, without moving the start", () => { - const merged = mergeLinkedThreadPage( - newest, - page([item(11, "eleven, finished"), item(12, "twelve")], { - earlierPosition: 11, - thread: { threadId, title: "Fix the build", status: "completed", model: "gpt-5" }, - }), - "later", - ); - expect(merged.items.map((entry) => entry.text)).toEqual(["ten", "eleven, finished", "twelve"]); - expect(merged.earlierPosition).toBe(10); - expect(merged.thread.status).toBe("completed"); - }); +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 }, + }, }); -describe("linkedThreadRefreshCursor", () => { - const linkedThreadRefreshCursorOf = (shown: PeerLinkThreadPage) => - linkedThreadRefreshCursor(mergeLinkedThreadPage(null, shown, "later")); - it("reads after the last item once everything shown has settled", () => { - expect(linkedThreadRefreshCursorOf(page([item(4, "a"), item(5, "b")]))).toBe(5); - expect(linkedThreadRefreshCursorOf(page([]))).toBe(-1); - }); - - it("re-reads from an item that is still being written", () => { - expect( - linkedThreadRefreshCursorOf(page([item(4, "a"), item(5, "b", "running"), item(6, "c")])), - ).toBe(4); - }); - - it("continues from the last item while a page left more behind it", () => { - expect( - linkedThreadRefreshCursorOf(page([item(4, "a", "running"), item(5, "b")], { hasMore: true })), - ).toBe(5); - }); +const failure = (reason: string) => ({ _tag: "PeerLinkThreadReadError", reason }); +const titleOf = (view: LinkedThreadView) => view.thread.projection?.thread.title ?? null; - it("continues from where a page cut short ended, not from the items it left untouched", () => { - const shown = mergeLinkedThreadPage( - mergeLinkedThreadPage( - null, - page([item(80, "a", "running"), item(81, "b"), item(99, "z")]), - "later", +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"))), ), - page([item(80, "a, done")], { hasMore: true }), - "later", - ); - expect(shown.items.map((entry) => entry.position)).toEqual([80, 81, 99]); - expect(linkedThreadRefreshCursor(shown)).toBe(80); - // An earlier page leaves the forward continuation alone. - const earlier = mergeLinkedThreadPage(shown, page([item(79, "y")]), "earlier"); - expect(linkedThreadRefreshCursor(earlier)).toBe(80); - expect( - linkedThreadRefreshCursor(mergeLinkedThreadPage(earlier, page([item(81, "b2")]), "later")), - ).toBe(99); - }); - - it("stops re-reading an item that stays unsettled once it is far behind", () => { - const items = [ - item(0, "stuck", "waiting"), - ...Array.from({ length: 30 }, (_, i) => item(i + 1, "x")), + Stream.make(snapshot(5)).pipe(Stream.concat(Stream.fail(failure("expired")))), ]; - expect(linkedThreadRefreshCursorOf(page(items))).toBe(30); - }); -}); - -describe("presentLinkedThreadItem", () => { - const present = ( - type: string, - text: string | null, - extra: Partial> = {}, - ) => presentLinkedThreadItem({ ...item(0, ""), type, text, ...extra }); - - it("shows messages in full and tool work as a row that opens", () => { - expect(present("user_message", "Fix it")).toMatchObject({ kind: "user", text: "Fix it" }); - expect(present("command_execution", "$ vp test\n3 passed")).toEqual({ - kind: "activity", - summary: "$ vp test", - body: "3 passed", - failed: false, - truncated: false, - }); - expect(present("dynamic_tool", "{}", { title: "t3_thread_read" })).toMatchObject({ - summary: "Tool call · t3_thread_read", - body: "{}", - }); - expect(present("error", "Rate limited")).toMatchObject({ summary: "Error", failed: true }); - expect(present("system_notice", "Session restarted")).toMatchObject({ - summary: "Session restarted", - body: null, - }); - }); - - it("hides items with nothing to read", () => { - expect(present("checkpoint", "[]")).toBeNull(); - expect(present("assistant_message", " ")).toBeNull(); - expect(present("system_notice", null)).toBeNull(); - }); -}); - -describe("createLinkedThreadSession", () => { - /** Reads answer when the test says so, and timers run when the test runs them. */ - const harness = (active = { current: true }) => { - const reads: Array<{ - readonly cursor: LinkedThreadCursor; - readonly answer: (result: LinkedThreadReadResult) => Promise; - }> = []; - const timers: Array<{ readonly run: () => void; readonly delayMs: number; live: boolean }> = []; - const kept: Array = []; - const session = createLinkedThreadSession({ - read: (cursor) => - new Promise((resolve) => { - reads.push({ - cursor, - answer: async (result) => { - resolve(result); - await Promise.resolve(); - }, - }); - }), - schedule: (run, delayMs) => { - const timer = { run, delayMs, live: true }; - timers.push(timer); - return () => { - timer.live = false; - }; - }, - isActive: () => active.current, - onRead: (page) => kept.push(page), - }); - const pending = () => timers.filter((timer) => timer.live); - const fire = () => { - const timer = pending()[0]!; - timer.live = false; - timer.run(); - }; - return { session, reads, pending, fire, kept }; - }; - - it("reads the newest page on open, then follows the thread at its pace", async () => { - const { session, reads, pending, fire } = harness(); - session.subscribe(() => {}); - expect(reads.map((read) => read.cursor)).toEqual([{}]); - await reads[0]!.answer({ - ok: true, - page: page([item(4, "a"), item(5, "b", "running")], { earlierPosition: 4 }), - }); - expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_ACTIVE_POLL_MS]); - - fire(); - expect(reads[1]!.cursor).toEqual({ afterPosition: 4 }); - await reads[1]!.answer({ - ok: true, - page: page([item(5, "b, done")], { - thread: { threadId, title: "Fix the build", status: "completed", model: "gpt-5" }, - }), - }); - expect(session.getSnapshot().transcript?.items.map((entry) => entry.text)).toEqual([ - "a", - "b, done", - ]); - expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_IDLE_POLL_MS]); - }); - - it("waits to read a view that opens while nobody is looking", () => { - const active = { current: false }; - const { session, reads, fire } = harness(active); - session.subscribe(() => {}); - expect(reads).toEqual([]); - active.current = true; - fire(); - expect(reads.map((read) => read.cursor)).toEqual([{}]); - }); - - it("ignores a read that a newer one overtook", async () => { - const { session, reads, kept } = harness(); - session.subscribe(() => {}); - session.retry(); - await reads[1]!.answer({ ok: true, page: page([item(4, "new")]) }); - await reads[0]!.answer({ ok: true, page: page([item(4, "old")]) }); - expect(session.getSnapshot().transcript?.items.map((entry) => entry.text)).toEqual(["new"]); - expect(kept.map((kept) => kept.items[0]?.text)).toEqual(["new"]); - }); + 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, + ); - it("pages back without losing what a refresh brought in meanwhile", async () => { - const { session, reads, fire } = harness(); - session.subscribe(() => {}); - await reads[0]!.answer({ ok: true, page: page([item(5, "five")], { earlierPosition: 5 }) }); - fire(); - void session.loadEarlier(); - expect(reads.slice(1).map((read) => read.cursor)).toEqual([ - { afterPosition: 5 }, - { beforePosition: 5 }, + 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, ]); - expect(session.getSnapshot().loadingEarlier).toBe(true); - await reads[2]!.answer({ ok: true, page: page([item(4, "four")]) }); - await reads[1]!.answer({ ok: true, page: page([item(6, "six")]) }); - expect(session.getSnapshot()).toMatchObject({ loadingEarlier: false, error: null }); - expect(session.getSnapshot().transcript?.items.map((entry) => entry.position)).toEqual([ - 4, 5, 6, - ]); - expect(session.getSnapshot().transcript?.earlierPosition).toBeNull(); - }); - - it("forgets a failed earlier read once the next one succeeds", async () => { - const { session, reads } = harness(); - session.subscribe(() => {}); - await reads[0]!.answer({ ok: true, page: page([item(5, "five")], { earlierPosition: 5 }) }); - void session.loadEarlier(); - await reads[1]!.answer({ ok: false, error: new Error("offline") }); - expect(session.getSnapshot()).toMatchObject({ loadingEarlier: false }); - expect(session.getSnapshot().error).not.toBeNull(); - void session.loadEarlier(); - await reads[2]!.answer({ ok: true, page: page([item(4, "four")]) }); - expect(session.getSnapshot().error).toBeNull(); - }); - - it("stops asking once the view closes or the read cannot recover", async () => { - const closing = harness(); - const close = closing.session.subscribe(() => {}); - await closing.reads[0]!.answer({ ok: true, page: page([item(1, "one")]) }); - close(); - expect(closing.pending()).toEqual([]); - // Opened again, it shows what it read and asks only for what followed. - closing.session.subscribe(() => {}); - expect(closing.session.getSnapshot().transcript?.items).toHaveLength(1); - expect(closing.reads[1]!.cursor).toEqual({ afterPosition: 1 }); - - const late = harness(); - const closeLate = late.session.subscribe(() => {}); - closeLate(); - await late.reads[0]!.answer({ ok: true, page: page([item(1, "one")]) }); - expect(late.session.getSnapshot().transcript).toBeNull(); - expect(late.pending()).toEqual([]); - - const expired = harness(); - expired.session.subscribe(() => {}); - const error = { _tag: "PeerLinkThreadReadError", reason: "expired", label: "VM", message: "" }; - await expired.reads[0]!.answer({ ok: false, error }); - expect(expired.session.getSnapshot().error).toBe(error); - expect(expired.pending()).toEqual([]); - }); - - it("keeps trying an environment that is out of reach, and waits while nobody is looking", async () => { - const active = { current: true }; - const { session, reads, pending, fire } = harness(active); - session.subscribe(() => {}); - await reads[0]!.answer({ - ok: false, - error: { _tag: "PeerLinkThreadReadError", reason: "unreachable", label: "VM", message: "" }, - }); - expect(pending().map((timer) => timer.delayMs)).toEqual([LINKED_THREAD_IDLE_POLL_MS]); + // 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("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, + ); - active.current = false; - fire(); - expect(reads).toHaveLength(1); - active.current = true; - fire(); - expect(reads).toHaveLength(2); - await reads[1]!.answer({ ok: true, page: page([item(1, "one")]) }); - expect(session.getSnapshot()).toMatchObject({ error: null }); - }); -}); + 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 index b77d1096fae03..7a6846671364a 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -1,7 +1,27 @@ -import type { EnvironmentId, PeerLinkThreadPage, ThreadId } from "@t3tools/contracts"; +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. */ @@ -41,80 +61,12 @@ const hasStringField = (value: unknown, key: K): value is Reco value !== null && typeof (value as Record)[key] === "string"; -type Page = Pick; - -/** What a linked thread view holds: the pages read so far, as one run of items, oldest first. */ -export type LinkedThreadTranscript = Page & { - /** - * Where the next forward read continues while the last one left more behind it, else null. A - * page cut short can end before items already shown, so this is not the last item's position. - */ - readonly continueAfter: number | null; -}; - -const continuationOf = (page: Page, fallback: number | null) => - page.hasMore ? (page.items.at(-1)?.position ?? fallback) : null; - -/** - * Adds a page to what is shown. An earlier page moves the start back; a later one replaces the - * items it re-reads, which is how an item still being written gets its new text. Every page - * carries the thread's current title and status. - */ -export function mergeLinkedThreadPage( - current: LinkedThreadTranscript | null, - page: Page, - direction: "earlier" | "later", -): LinkedThreadTranscript { - if (current === null) return { ...page, continueAfter: continuationOf(page, null) }; - const byPosition = new Map(current.items.map((item) => [item.position, item])); - for (const item of page.items) byPosition.set(item.position, item); - return { - label: page.label, - thread: page.thread, - items: [...byPosition.values()].sort((left, right) => left.position - right.position), - earlierPosition: direction === "earlier" ? page.earlierPosition : current.earlierPosition, - hasMore: direction === "later" ? page.hasMore : current.hasMore, - continueAfter: - direction === "later" ? continuationOf(page, current.continueAfter) : current.continueAfter, - }; -} - -const UNSETTLED_ITEM_STATUSES = new Set(["pending", "running", "waiting"]); -/** How far back a refresh re-reads for items still changing, so a stuck one cannot grow it. */ -const REFRESH_WINDOW = 20; - -/** - * The `afterPosition` of the next forward read. While a page left more behind it, that continues - * from where the page ended. Otherwise it re-reads from the oldest recent item still in progress, since - * its text and status change in place. - */ -export function linkedThreadRefreshCursor(transcript: LinkedThreadTranscript): number { - if (transcript.continueAfter !== null) return transcript.continueAfter; - const last = transcript.items.at(-1)?.position ?? -1; - const unsettled = transcript.items - .slice(-REFRESH_WINDOW) - .find((item) => UNSETTLED_ITEM_STATUSES.has(item.status)); - return unsettled === undefined ? last : unsettled.position - 1; -} - -const ACTIVE_THREAD_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]); - -export const LINKED_THREAD_ACTIVE_POLL_MS = 2_500; -export const LINKED_THREAD_IDLE_POLL_MS = 15_000; - -/** How long an open view waits before its next read: none while catching up, short while the thread works. */ -function linkedThreadPollDelayMs(transcript: Pick): number { - if (transcript.hasMore) return 0; - return ACTIVE_THREAD_STATUSES.has(transcript.thread.status) - ? LINKED_THREAD_ACTIVE_POLL_MS - : LINKED_THREAD_IDLE_POLL_MS; -} - /** Whether a failed read can succeed later with nothing changed: the linked environment was only out of reach. */ -function isLinkedThreadFailureRetryable(error: unknown): boolean { - if (!hasStringField(error, "_tag") || error._tag !== "PeerLinkThreadReadError") return true; - return hasStringField(error, "reason") && error.reason === "unreachable"; -} +const isLinkedThreadUnreachable = (error: unknown): boolean => + hasStringField(error, "_tag") && + error._tag === "PeerLinkThreadReadError" && + hasStringField(error, "reason") && + error.reason === "unreachable"; export interface LinkedThreadFailure { readonly title: string; @@ -144,7 +96,7 @@ export function linkedThreadFailure( retryable: true, }; } - const retryable = isLinkedThreadFailureRetryable(error); + const retryable = isLinkedThreadUnreachable(error); const label = hasStringField(error, "label") ? error.label : names.label; const reason = hasStringField(error, "reason") ? error.reason : ""; switch (reason) { @@ -206,196 +158,105 @@ export function linkedThreadFailure( } } -type Item = PeerLinkThreadPage["items"][number]; - -export type LinkedThreadItemPresentation = - | { readonly kind: "user" | "assistant"; readonly text: string; readonly truncated: boolean } - | { - readonly kind: "activity"; - readonly summary: string; - /** What the row opens to show; null when the summary says it all. */ - readonly body: string | null; - readonly failed: boolean; - readonly truncated: boolean; - }; - -const ACTIVITY_LABELS = { - reasoning: msg("Thinking"), - todo_list: msg("Plan"), - file_search: msg("File search"), - web_search: msg("Web search"), - approval_request: msg("Approval request"), - user_input_request: msg("Question"), - subagent: msg("Subagent"), - dynamic_tool: msg("Tool call"), - compaction: msg("Context compacted"), - error: msg("Error"), -} as const; - -const firstLine = (text: string) => { - const end = text.indexOf("\n"); - return end === -1 - ? { head: text, rest: null } - : { head: text.slice(0, end), rest: text.slice(end + 1) }; -}; +const WORKING_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]); -/** - * How a transcript item reads in a linked thread view: messages in full, everything else as a - * one-line row that opens. `null` hides items that say nothing to a reader, such as checkpoints. - */ -export function presentLinkedThreadItem( - item: Pick, - resolve: MFunctionType = mFallback, -): LinkedThreadItemPresentation | null { - const text = item.text ?? ""; - const truncated = item.textTruncated; - if (item.type === "checkpoint") return null; - if (item.type === "user_message") return { kind: "user", text, truncated }; - if (item.type === "assistant_message" || item.type === "proposed_plan") { - return text.trim() === "" ? null : { kind: "assistant", text, truncated }; - } - const failed = item.status === "failed" || item.type === "error"; - if (item.type === "command_execution" || item.type === "file_change") { - const { head, rest } = firstLine(text); - return { kind: "activity", summary: head, body: rest, failed, truncated }; - } - const label = Object.hasOwn(ACTIVITY_LABELS, item.type) - ? resolve(ACTIVITY_LABELS[item.type as keyof typeof ACTIVITY_LABELS]) - : null; - const title = item.title?.trim() || null; - if (label === null && title === null) { - // Notices and the like are their own text. - const { head, rest } = firstLine(text); - return head.trim() === "" - ? null - : { kind: "activity", summary: head, body: rest, failed, truncated }; - } - return { - kind: "activity", - summary: label !== null && title !== null ? `${label} · ${title}` : (label ?? title)!, - body: text.trim() === "" ? null : text, - failed, - truncated, - }; +/** 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 + ); } -export const isLinkedThreadWorking = (transcript: Pick): boolean => - ACTIVE_THREAD_STATUSES.has(transcript.thread.status); +/** How long a view waits before asking again for a thread whose environment did not answer. */ +export const LINKED_THREAD_RETRY_MS = 15_000; -export interface LinkedThreadCursor { - readonly beforePosition?: number; - readonly afterPosition?: number; -} - -export type LinkedThreadReadResult = - | { readonly ok: true; readonly page: Page } - | { readonly ok: false; readonly error: unknown }; - -export interface LinkedThreadSessionState { - readonly transcript: LinkedThreadTranscript | null; - /** The last read's failure, cleared by the next read that succeeds. */ +/** 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 loadingEarlier: boolean; + 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; } /** - * The reads behind one open linked thread view. It reads only while something subscribes, so a - * view that unmounts stops asking the linked environment at once, and while `isActive` says the - * view is not being looked at it only waits. + * 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 function createLinkedThreadSession(options: { - readonly read: (cursor: LinkedThreadCursor) => Promise; - /** Runs `run` after `delayMs` and returns how to cancel it. */ - readonly schedule: (run: () => void, delayMs: number) => () => void; - readonly isActive?: () => boolean; - /** Called with each forward read the session keeps, never with one a newer read overtook. */ - readonly onRead?: (page: Page) => void; -}) { - let state: LinkedThreadSessionState = { transcript: null, error: null, loadingEarlier: false }; - const listeners = new Set<() => void>(); - // Bumped on stop and restart, so a read that outlives its view changes nothing. - let generation = 0; - let cancelNext: (() => void) | null = null; - - const update = (patch: Partial) => { - state = { ...state, ...patch }; - for (const listener of listeners) listener(); - }; - - const scheduleNext = (delayMs: number) => { - cancelNext?.(); - cancelNext = options.schedule(() => { - cancelNext = null; - if (options.isActive?.() === false) scheduleNext(LINKED_THREAD_ACTIVE_POLL_MS); - else void readLatest(); - }, delayMs); - }; - - // Only the newest forward read applies: a retry can start one while another is still out. - let latestRead = 0; - - const readLatest = async () => { - const run = generation; - const read = ++latestRead; - cancelNext?.(); - cancelNext = null; - const shown = state.transcript; - const result = await options.read( - shown === null ? {} : { afterPosition: linkedThreadRefreshCursor(shown) }, - ); - if (run !== generation || read !== latestRead) return; - if (!result.ok) { - update({ error: result.error }); - if (isLinkedThreadFailureRetryable(result.error)) scheduleNext(LINKED_THREAD_IDLE_POLL_MS); - return; - } - // An earlier page may have landed while this read was out. - const transcript = mergeLinkedThreadPage(state.transcript, result.page, "later"); - update({ transcript, error: null }); - options.onRead?.(result.page); - scheduleNext(linkedThreadPollDelayMs(transcript)); - }; - - return { - getSnapshot: () => state, - subscribe: (listener: () => void) => { - listeners.add(listener); - if (listeners.size === 1) { - generation += 1; - if (options.isActive?.() === false) scheduleNext(LINKED_THREAD_ACTIVE_POLL_MS); - else void readLatest(); - } - return () => { - if (!listeners.delete(listener) || listeners.size > 0) return; - generation += 1; - cancelNext?.(); - cancelNext = null; - state = { ...state, loadingEarlier: false }; +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); + }, }; - }, - /** Reads the page before the oldest one shown. */ - loadEarlier: async () => { - const before = state.transcript?.earlierPosition ?? null; - if (before === null || state.loadingEarlier) return; - const run = generation; - update({ loadingEarlier: true }); - const result = await options.read({ beforePosition: before }); - if (run !== generation) return; - update( - result.ok - ? { - transcript: mergeLinkedThreadPage(state.transcript, result.page, "earlier"), - error: null, - loadingEarlier: false, + 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; } - : { error: result.error, loadingEarlier: false }, + 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; + }), + ), + ), + ), + ), + ); + }), + ), ); - }, - /** Reads again now, after a failure the user asked to retry. */ - retry: () => { - if (listeners.size > 0) void readLatest(); - }, - }; -} - -export type LinkedThreadSession = ReturnType; + 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/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 78e66d24192c1..0fc89a1fd2f63 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -516,37 +516,6 @@ it.effect( }), ); -it.effect( - "reads a linked environment's thread with thread read access, not access management", - () => - Effect.gen(function* () { - const registry = yield* setup; - const read = createCommandPermissions(runtime, WS_METHODS.peerLinksReadThread); - registry.set( - sessions(env), - AsyncResult.success({ - ...grant(false), - scopes: [AuthAccessWriteScope], - permissions: [AuthAccessWriteScope], - }), - ); - expect(registry.get(read.permissionAtom(env))).toBe(false); - expect((yield* read.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe( - AuthOrchestrationReadScope, - ); - registry.set( - sessions(env), - AsyncResult.success({ - ...grant(false), - scopes: [AuthOrchestrationReadScope], - permissions: [AuthOrchestrationReadScope], - }), - ); - expect(registry.get(read.permissionAtom(env))).toBe(true); - yield* read.authorize(registry, env); - }), -); - it.effect("requires access management to answer a link request", () => Effect.gen(function* () { const registry = yield* setup; diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 486ae06ec5d75..219bfd26e870d 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -1,11 +1,34 @@ -import { type EnvironmentId, 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, type AtomRegistry } 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, 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, @@ -27,6 +50,38 @@ export function createPeerLinkEnvironmentAtoms( 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)) get.set(lastThreadView(key), live.value); + return live; + }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); + }); return { list, names, @@ -45,10 +100,13 @@ export function createPeerLinkEnvironmentAtoms( tag: WS_METHODS.peerLinksUnlink, onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId), }), - /** One page of a linked environment's thread. An open view calls it; nothing is cached. */ - readThread: createEnvironmentRpcCommand(runtime, { - label: "environment-data:peer-links:read-thread", - tag: WS_METHODS.peerLinksReadThread, + 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, { 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/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 2bdaaba5bb2e5..0b6164871a0ad 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -86,8 +86,6 @@ 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, - // Reads a linked environment's thread as this one's own are read. - [WS_METHODS.peerLinksReadThread]: AuthOrchestrationReadScope, } 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 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 2e927df0e2a39..bf25a34e07cf7 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -1,17 +1,7 @@ import * as Schema from "effect/Schema"; import { AuthMcpClientAccess } from "./auth.ts"; -import { - EnvironmentId, - NonNegativeInt, - ThreadId, - TrimmedNonEmptyString, - TurnItemId, -} from "./baseSchemas.ts"; -import { - OrchestratorMcpThreadStatus, - OrchestratorMcpThreadTimelineItem, -} from "./orchestratorMcp.ts"; +import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts"; /** * A link from this environment to another one (the peer). This environment @@ -110,36 +100,37 @@ export const peerLinkFailureKind = ( : "other"; /** - * A page of a linked environment's thread, read for a client of this environment over the link. - * No cursor reads the newest page; `beforePosition` pages back and `afterPosition` reads what - * came after, which is also how an open view refreshes. + * 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. */ -export const PeerLinkThreadReadInput = Schema.Struct({ +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, - beforePosition: Schema.optionalKey(NonNegativeInt), - afterPosition: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(-1))), }); -export type PeerLinkThreadReadInput = typeof PeerLinkThreadReadInput.Type; +export type PeerLinkThreadInput = typeof PeerLinkThreadInput.Type; -export const PeerLinkThreadPage = Schema.Struct({ - /** What this environment calls the linked one. */ - label: Schema.String, - thread: Schema.Struct({ - threadId: ThreadId, - title: Schema.String, - status: OrchestratorMcpThreadStatus, - model: Schema.String, - }), - /** Oldest first. Each page is bounded in items and in bytes. */ - items: Schema.Array(OrchestratorMcpThreadTimelineItem), - /** Pass as `beforePosition` for the page before this one; null at the thread's start. */ - earlierPosition: Schema.NullOr(NonNegativeInt), - /** More items follow this page already, so the next read need not wait. */ - hasMore: Schema.Boolean, +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 PeerLinkThreadPage = typeof PeerLinkThreadPage.Type; +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()( @@ -154,7 +145,7 @@ export class PeerLinkThreadReadError extends Schema.TaggedError Date: Thu, 19 Nov 2026 22:28:36 -0800 Subject: [PATCH 16/17] fix: linked thread reads survive a newer peer, a stalled answer and a reopened view The relay drops event types a newer linked environment sends, which this version reads but cannot encode for its own client. JSON answers are bounded past their headers. A reopened view keeps the thread it showed until the new stream delivers a snapshot. On mobile, an open row reads omitted output through the link, and messages sent with a tool are shown. Co-Authored-By: Claude Fable 5.2 --- .../features/threads/LinkedThreadSheet.tsx | 78 ++++++++++++- apps/server/src/peer/PeerThreadRelay.test.ts | 104 +++++++++++++++++- apps/server/src/peer/PeerThreadRelay.ts | 25 ++++- .../client-runtime/src/linkedThread.test.ts | 40 +++++++ packages/client-runtime/src/linkedThread.ts | 13 +++ .../client-runtime/src/state/peerLinks.ts | 11 +- 6 files changed, 256 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index e0be0d5ee4c8a..1cfae6998baae 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -5,6 +5,10 @@ import { type LinkedThreadFailure, type LinkedThreadTarget, } from "@t3tools/client-runtime/linked-thread"; +import { + 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"; @@ -22,10 +26,13 @@ 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"; @@ -50,10 +57,45 @@ export const linkedThreadRouteParams = ( ...(title === null ? {} : { title }), }); -function ActivityRow(props: { readonly activity: ThreadFeedActivity }) { - const { activity } = props; +function ActivityRow(props: { + readonly activity: ThreadFeedActivity; + readonly target: LinkedThreadTarget; +}) { + const { activity, target } = props; + const gt = useGT(); const [open, setOpen] = useState(false); - const body = open ? (activity.getFullDetail() ?? activity.detail) : null; + 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 body = !open + ? null + : 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 (
    ) : null} + {output ? ( + + + {output} + + + ) : null} + {open && fetched.error ? ( + +