diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts index 576ff9445..9d2b7c584 100644 --- a/apps/server/src/environment/Layers/ServerEnvironment.ts +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -97,6 +97,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function commandRuns: true, followsInsertedCommands: true, computerLinks: true, + linkedThreadRead: true, scheduledTasks: true, themes: true, themeShowcase: true, diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 429c358c6..1e868c705 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -119,7 +119,7 @@ A started thread works in a worktree of its own; in a project without git it sha A started thread gets at most its parent's access level, or a lower one the agent asks for, and the parent's model unless the agent picks another. On a model already in the room it runs at the reasoning you set for that agent there, unless the agent or you name another level; the approval card shows the level. With computers linked in Fleet, an agent can also start a thread on another computer, if that computer allows it ({place:fleet.worksWith}). -A thread on another computer stays under its parent on both computers and shows how it is doing there, even after its answer came back. Once its answer reached the parent it wraps up and moves to Wrapped like any other, unless someone picked it up again there. Its row has Wrap up (and Reopen in Wrapped), which applies on both computers. To open it, connect this app to that computer. +A thread on another computer stays under its parent on both computers and shows how it is doing there, even after its answer came back. Once its answer reached the parent it wraps up and moves to Wrapped like any other, unless someone picked it up again there. Its row has Wrap up (and Reopen in Wrapped), which applies on both computers. Clicking its row or its tab opens it read through the link, even when this app isn't connected to that computer: you see what was asked and what its agent answered, but not its tool steps, and you can't reply there. Connect this app to that computer to work in it. A project's lead chat is a thread set up to coordinate the project; see the lead chat topic.`, }, diff --git a/apps/server/src/links/linkedThreadRead.test.ts b/apps/server/src/links/linkedThreadRead.test.ts new file mode 100644 index 000000000..a17ea2640 --- /dev/null +++ b/apps/server/src/links/linkedThreadRead.test.ts @@ -0,0 +1,130 @@ +import { + type AgentThreadReadResult, + EnvironmentId, + type OrchestrationThreadShell, + type PeerThreadReadInput, + ThreadId, +} from "@threadlines/contracts"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { + type ComputerLinkClientShape, + ComputerLinkUnavailableError, +} from "./ComputerLinkClient.ts"; +import { makeLinkedThreadRead } from "./linkedThreadRead.ts"; + +const WINDOWS = EnvironmentId.make("env-windows"); +const PARENT = ThreadId.make("parent"); +const CHILD = ThreadId.make("child"); + +const ANSWER: AgentThreadReadResult = { + outcome: "ok", + messages: [ + { + messageId: "m1", + sequence: 4, + at: "2026-11-23T10:00:00.000Z", + role: "assistant", + author: "Codex", + origin: "agent", + text: "Done.", + }, + ], + next: 4, + more: false, +}; + +const parentShell = { + id: PARENT, + remoteChildren: [ + { + environmentId: WINDOWS, + label: "Windows PC", + threadId: CHILD, + handle: "Codex", + title: "Fix the build", + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: "2026-11-23T10:00:00.000Z", + }, + ], +} as unknown as OrchestrationThreadShell; + +function makeRead( + peer: (input: PeerThreadReadInput) => Effect.Effect, +) { + const asked: PeerThreadReadInput[] = []; + const client = { + withPeer: (_environmentId, use) => + use({ + "peer.thread.read": (input: PeerThreadReadInput) => { + asked.push(input); + return peer(input); + }, + } as never), + } as Pick as ComputerLinkClientShape; + const read = makeLinkedThreadRead({ + client, + snapshots: { + getThreadShellById: (threadId) => + Effect.succeed(threadId === PARENT ? Option.some(parentShell) : Option.none()), + }, + }); + return { read, asked }; +} + +it.effect("reads a parent's child through the link, and only a child the parent holds", () => + Effect.gen(function* () { + const { read, asked } = makeRead(() => Effect.succeed(ANSWER)); + const page = yield* read({ + parentThreadId: PARENT, + environmentId: WINDOWS, + threadId: CHILD, + limit: 50, + }); + assert.deepStrictEqual(page, ANSWER); + assert.deepStrictEqual(asked, [{ threadId: CHILD, limit: 50 }]); + + const stranger = yield* Effect.flip( + read({ parentThreadId: PARENT, environmentId: WINDOWS, threadId: ThreadId.make("other") }), + ); + assert.strictEqual(stranger.detail, "That thread wasn't started from this computer."); + assert.strictEqual(asked.length, 1); + }), +); + +it.effect("refuses one message an older computer answered with a page instead", () => + Effect.gen(function* () { + const { read } = makeRead(() => Effect.succeed(ANSWER)); + const page = yield* read({ + parentThreadId: PARENT, + environmentId: WINDOWS, + threadId: CHILD, + messageId: "m-asked", + offset: 0, + }); + assert.strictEqual(page.outcome, "refused"); + assert.deepStrictEqual(page.messages, []); + }), +); + +it.effect("says which computer can't be reached", () => + Effect.gen(function* () { + const { read } = makeRead( + () => + Effect.fail( + new ComputerLinkUnavailableError({ + environmentId: WINDOWS, + detail: "socket closed", + revoked: false, + }), + ) as never, + ); + const error = yield* Effect.flip( + read({ parentThreadId: PARENT, environmentId: WINDOWS, threadId: CHILD }), + ); + assert.strictEqual(error.detail, "Windows PC can't be reached right now."); + }), +); diff --git a/apps/server/src/links/linkedThreadRead.ts b/apps/server/src/links/linkedThreadRead.ts new file mode 100644 index 000000000..9c022e270 --- /dev/null +++ b/apps/server/src/links/linkedThreadRead.ts @@ -0,0 +1,71 @@ +/** + * Reading a child on a linked computer for this server's clients + * (`links.readThread`, docs/design/child-threads.md, "Opening a child on a + * computer the app can't see"). A client that isn't connected to that + * computer still opens the child from its family: this server asks the other + * one through the link (`peer.thread.read`), which only serves threads this + * computer's link started. Only a parent here that holds the child is read + * for, so a client reads exactly the children its families show. + */ +import { + type AgentThreadReadResult, + ComputerLinkError, + type LinksReadThreadInput, +} from "@threadlines/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type { ProjectionSnapshotQueryShape } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import type { ComputerLinkClientShape } from "./ComputerLinkClient.ts"; +import { refuseIgnoredMessageRead } from "./threadToolLinks.ts"; + +/** How long a read may take before the client is told that computer didn't answer. */ +const READ_TIMEOUT = Duration.seconds(15); + +const refuse = (detail: string) => Effect.fail(new ComputerLinkError({ detail })); + +export function makeLinkedThreadRead(input: { + readonly client: ComputerLinkClientShape; + readonly snapshots: Pick; +}) { + return (request: LinksReadThreadInput): Effect.Effect => + Effect.gen(function* () { + const parent = yield* input.snapshots.getThreadShellById(request.parentThreadId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + const child = parent?.remoteChildren?.find( + (candidate) => + candidate.environmentId === request.environmentId && + candidate.threadId === request.threadId, + ); + if (child === undefined) { + return yield* refuse("That thread wasn't started from this computer."); + } + return yield* input.client + .withPeer( + request.environmentId, + (peer) => + peer["peer.thread.read"]({ + threadId: request.threadId, + ...(request.after !== undefined ? { after: request.after } : {}), + ...(request.limit !== undefined ? { limit: request.limit } : {}), + ...(request.messageId !== undefined ? { messageId: request.messageId } : {}), + ...(request.offset !== undefined ? { offset: request.offset } : {}), + }), + { timeout: READ_TIMEOUT }, + ) + .pipe( + Effect.map((read) => refuseIgnoredMessageRead(request.messageId, read)), + Effect.catch((error) => + refuse( + // A removed link says so; anything else may pass. + error._tag === "ComputerLinkUnavailableError" && !error.revoked + ? `${child.label} can't be reached right now.` + : error.detail, + ), + ), + ); + }); +} diff --git a/apps/server/src/links/threadToolLinks.ts b/apps/server/src/links/threadToolLinks.ts index b07fe0645..8b9943738 100644 --- a/apps/server/src/links/threadToolLinks.ts +++ b/apps/server/src/links/threadToolLinks.ts @@ -3,7 +3,7 @@ * (A)"): which computers there are, what each offers (its peer.describe, * reused for five minutes and refreshed on use), and reads of threads there. */ -import type { EnvironmentId } from "@threadlines/contracts"; +import type { AgentThreadReadResult, EnvironmentId } from "@threadlines/contracts"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -14,6 +14,35 @@ import type { RepositoryIdentityResolverShape } from "../project/Services/Reposi import type { ComputerLinkClientShape } from "./ComputerLinkClient.ts"; import { type ComputerLinkRepositoryShape, isUsableLink } from "./ComputerLinkRepository.ts"; +/** + * A read of one message (`messageId`) as the linked computer answered it, or + * `refused` when it ignored `messageId`: an older computer answers with a + * page instead, whose one message may even be the one asked for, but clipped, + * without the part's place in it. + */ +export function refuseIgnoredMessageRead( + messageId: string | undefined, + read: AgentThreadReadResult, +): AgentThreadReadResult { + if (messageId === undefined || read.outcome !== "ok") return read; + const only = read.messages.length === 1 ? read.messages[0]! : undefined; + if ( + only !== undefined && + only.messageId === messageId && + (only.clipped !== true || only.offset !== undefined) + ) { + return read; + } + return { + outcome: "refused", + detail: + "That computer's Threadlines is too old to read one message in full. Update it, then try again.", + messages: [], + next: null, + more: false, + }; +} + /** How long thread_agents waits for a computer before listing it as last seen. */ const DESCRIBE_WAIT = Duration.seconds(4); @@ -62,27 +91,7 @@ export function makeThreadToolLinks(input: { }), ) .pipe( - Effect.map((read) => - // An older computer ignores `messageId` and answers with a page - // instead: its one message may even be the one asked for, but - // clipped, without the part's place in it. - request.messageId !== undefined && - read.outcome === "ok" && - !( - read.messages.length === 1 && - read.messages[0]!.messageId === request.messageId && - (read.messages[0]!.clipped !== true || read.messages[0]!.offset !== undefined) - ) - ? { - outcome: "refused" as const, - detail: - "That computer's Threadlines is too old to read one message in full. Update it, then try again.", - messages: [], - next: null, - more: false, - } - : read, - ), + Effect.map((read) => refuseIgnoredMessageRead(request.messageId, read)), Effect.catch((error) => Effect.succeed({ unavailable: error.message })), ), projectPlace: (workspaceRoot) => resolveProjectPlace(identities, workspaceRoot), diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index ff1fbac5d..361b150f6 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -103,6 +103,7 @@ import { RelayDeviceRepository, type RelayDeviceRepositoryShape, } from "./relay/RelayDeviceRepository.ts"; +import { ComputerLinkClient } from "./links/ComputerLinkClient.ts"; import { ComputerLinks, type ComputerLinksShape } from "./links/ComputerLinks.ts"; import { ScheduledTasks, type ScheduledTasksShape } from "./scheduled/ScheduledTasks.ts"; import { ThemeLibrary, type ThemeLibraryShape } from "./themes/ThemeLibrary.ts"; @@ -906,6 +907,11 @@ const buildAppUnderTest = (options?: { }), Layer.mock(ThreadMoves)({}), Layer.mock(MoveQueue)({}), + Layer.mock(ComputerLinkClient)({ + cachedDescribe: () => null, + noteRemoteLabel: () => undefined, + remoteLabelChanges: Stream.empty, + }), Layer.mock(ProjectSetups)({}), Layer.mock(ProjectContext)({ changes: Stream.make({ briefs: [], notes: [], suggestions: [] }), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index c875b714b..6ef37e52f 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -68,6 +68,7 @@ import { WsOutsideAgentsRpcGroup, WsRpcGroup, WsMovesRpcGroup, + WsLinkedThreadsRpcGroup, WsThemeShowcaseRpcGroup, WsThemeVsCodeRpcGroup, WsDeviceRpcGroup, @@ -104,6 +105,8 @@ import { threadsArchivedWith } from "./orchestration/archivedWithParent.ts"; import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts"; import { ProviderCommandReactor } from "./orchestration/Services/ProviderCommandReactor.ts"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { ComputerLinkClient } from "./links/ComputerLinkClient.ts"; +import { makeLinkedThreadRead } from "./links/linkedThreadRead.ts"; import { AgentPages } from "./pages/AgentPages.ts"; import { McpApps } from "./mcpApps/McpApps.ts"; import { CommandRuns } from "./commandRuns/CommandRuns.ts"; @@ -823,6 +826,27 @@ const MovesRpcLayer = WsMovesRpcGroup.toLayer( }), ); +/** + * Reading a parent's child on a linked computer through the link + * (linkedThreadRead.ts): its own RPC group and layer + * (WsLinkedThreadsRpcGroup), merged in makeWsRpcLayer. Open to every paired + * device, as the parent's own thread is. + */ +const LinkedThreadsRpcLayer = WsLinkedThreadsRpcGroup.toLayer( + Effect.gen(function* () { + const readThread = makeLinkedThreadRead({ + client: yield* ComputerLinkClient, + snapshots: yield* ProjectionSnapshotQuery, + }); + return WsLinkedThreadsRpcGroup.of({ + [WS_METHODS.linksReadThread]: (input) => + observeRpcEffect(WS_METHODS.linksReadThread, readThread(input), { + "rpc.aggregate": "links", + }), + }); + }), +); + /** VS Code themes from the Open VSX store (docs/design/custom-themes.md). */ const ThemeVsCodeRpcLayer = WsThemeVsCodeRpcGroup.toLayer( Effect.gen(function* () { @@ -902,6 +926,7 @@ const makeWsRpcLayer = ( MovesRpcLayer, ThemeVsCodeRpcLayer, makeDeviceRpcLayer(viewerId), + LinkedThreadsRpcLayer, ); const makeCoreRpcLayer = ( diff --git a/apps/web/src/childThreads.ts b/apps/web/src/childThreads.ts index b0d6d3719..06c19c12c 100644 --- a/apps/web/src/childThreads.ts +++ b/apps/web/src/childThreads.ts @@ -28,6 +28,7 @@ import { useMemo } from "react"; import { useShallow } from "zustand/react/shallow"; import { formatChildThreadCount } from "./components/Sidebar.logic"; +import { useConnectedComputerCapability } from "./environments/computerCapabilities"; import { useThreadTitle } from "./hooks/useThreadTitle"; import { toSortableTimestamp } from "./lib/threadSort"; import type { ProviderInstanceEntry } from "./providerInstances"; @@ -85,6 +86,11 @@ export interface ThreadMessageSource { readonly computer: { readonly environmentId: EnvironmentId; readonly lastKnown: string } | null; /** This app has the thread to open. */ readonly openable: boolean; + /** + * A child on a linked computer this app can't see, which opens read through + * the link instead (LinkedThreadView): this thread's computer reads it. + */ + readonly linked: boolean; } /** @@ -101,6 +107,7 @@ export function useThreadMessageSource( const remoteEnvironmentId = origin.environmentId ?? null; const sourceEnvironmentId = remoteEnvironmentId ?? environmentId; const liveTitle = useThreadTitle(sourceEnvironmentId, origin.threadId); + const readsLinked = useConnectedComputerCapability(environmentId, "linkedThreadRead"); const remoteChildren = useRemoteChildren( environmentId, remoteEnvironmentId !== null && origin.kind === "report" ? threadId : null, @@ -118,6 +125,7 @@ export function useThreadMessageSource( title: liveTitle, computer: null, openable: origin.neverMade !== true, + linked: false, }; } const child = remoteChildren.find((candidate) => candidate.threadId === origin.threadId); @@ -130,6 +138,7 @@ export function useThreadMessageSource( lastKnown: child?.label ?? parent?.environmentLabel ?? "", }, openable: liveTitle !== null, + linked: liveTitle === null && child !== undefined && readsLinked, }; } diff --git a/apps/web/src/components/ChatView.agents.browser.tsx b/apps/web/src/components/ChatView.agents.browser.tsx index d3ec5c61c..0bf1b8de1 100644 --- a/apps/web/src/components/ChatView.agents.browser.tsx +++ b/apps/web/src/components/ChatView.agents.browser.tsx @@ -76,6 +76,7 @@ import { fixture, rpcHarness, createUserMessage, + withLinkedThreadReadFixture, } from "./ChatView.browser-harness"; import { selectSidebarThreadSummaryByRef, useStore } from "../store"; import { resolveThreadStatusPill } from "./Sidebar.logic"; @@ -1368,6 +1369,117 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { } }); + it("opens a thread started on a computer this app can't see, read through the link", async () => { + const windows = EnvironmentId.make("environment-windows"); + const childId = "thread-child-windows" as ThreadId; + const childKey = scopedThreadKey(scopeThreadRef(windows, childId)); + const base = createSnapshotForTargetUser({ + targetMessageId: "msg-user-linked-child" as MessageId, + targetText: "linked child target", + }); + const reads: Array> = []; + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...base, + threads: base.threads.map((thread) => + thread.id === THREAD_ID + ? { + ...thread, + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + remoteChildren: [ + { + environmentId: windows, + label: "Windows PC", + threadId: childId, + handle: "Codex", + title: "Check the Windows build", + attachmentEpoch: 0, + cachedStatus: "working", + updatedAt: isoAt(300), + }, + ], + }, + } + : thread, + ), + }, + configureFixture: withLinkedThreadReadFixture, + resolveRpc: (body) => { + if (body._tag !== WS_METHODS.linksReadThread) return undefined; + reads.push(body); + return { + outcome: "ok", + messages: [ + { + messageId: "m-ask", + sequence: 1, + at: isoAt(301), + role: "user", + author: "Browser test thread (on Local environment)", + origin: "thread_request", + text: "Check the Windows build.", + }, + { + messageId: "m-answer", + sequence: 2, + at: isoAt(302), + role: "assistant", + author: "Codex", + origin: "agent", + text: "The Windows build passes.", + }, + ], + next: 2, + more: false, + }; + }, + }); + try { + const tab = page.getByTestId(`family-tab-${childKey}`); + await vi.waitFor(() => expect(tab.element()).not.toHaveAttribute("disabled"), { + timeout: 10_000, + }); + await tab.click(); + await waitForURL( + mounted.router, + (pathname) => pathname.endsWith(`/linked/${windows}/${childId}`), + "The tab should open the thread read through the link.", + ); + await expect.element(page.getByText("The Windows build passes.")).toBeVisible(); + await expect.element(page.getByText("Check the Windows build.")).toBeVisible(); + await vi.waitFor(() => + expect( + document + .querySelector('[data-testid="linked-thread-place"]') + ?.textContent?.replace(/\s+/g, " "), + ).toBe("Windows PC·working"), + ); + expect(reads[0]).toMatchObject({ + parentThreadId: THREAD_ID, + environmentId: windows, + threadId: childId, + limit: 50, + }); + // The family row stays, with this thread's tab open. + await vi.waitFor(() => + expect(page.getByTestId(`family-tab-${childKey}`).element()).toHaveAttribute( + "aria-selected", + "true", + ), + ); + await page.getByTestId(`family-tab-${THREAD_KEY}`).click(); + await waitForURL( + mounted.router, + (pathname) => pathname.endsWith(`/${THREAD_ID}`), + "The parent's tab should open the parent again.", + ); + } finally { + await mounted.cleanup(); + } + }); + it("keeps the lead's tab whole on a crowded row, drops a shared topic, and cuts long tabs to one width", async () => { const titles = [ "Panel Jam animation timing review", diff --git a/apps/web/src/components/ChatView.browser-harness.tsx b/apps/web/src/components/ChatView.browser-harness.tsx index 1a3ce7310..9d35b105c 100644 --- a/apps/web/src/components/ChatView.browser-harness.tsx +++ b/apps/web/src/components/ChatView.browser-harness.tsx @@ -1115,6 +1115,11 @@ export function withOutsideAgentsFixture(nextFixture: TestFixture): void { withPrimaryCapabilities(nextFixture, { outsideAgents: true }); } +/** This computer's server reads its threads' children on linked computers for the app (`links.readThread`). */ +export function withLinkedThreadReadFixture(nextFixture: TestFixture): void { + withPrimaryCapabilities(nextFixture, { computerLinks: true, linkedThreadRead: true }); +} + /** This computer's server, and the computers saved from its config, take links. */ export function withComputerLinksFixture(nextFixture: TestFixture): void { withPrimaryCapabilities(nextFixture, { computerLinks: true }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3e1b39f7a..0509950a2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -308,10 +308,12 @@ import { type ComposerGoalSetInput, threadGoalControls } from "./chat/ComposerGo import { getComposerProviderState } from "./chat/composerProviderState"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; import { useProjectBriefSupport } from "../projectBrief"; +import { linkedThreadRouteParams } from "../environments/links/linkedThreads"; import { changeProjectNote, useThreadNoteSuggestions } from "../projectContext"; import { MessagesTimeline, type NoteSuggestionResolver, + type OpenThread, type TimelineProposedPlanState, type TimelineTurnAgentsState, } from "./chat/MessagesTimeline"; @@ -8503,11 +8505,18 @@ export default function ChatView(props: ChatViewProps) { )?.text; void onRevertToTurnCountRef.current(targetTurnCount, revertedMessageText); }, []); - const onOpenForkSourceThread = useCallback( - (sourceThreadId: ThreadId, environmentId?: EnvironmentId) => { + const onOpenForkSourceThread = useCallback( + (sourceThreadId, environmentId, how) => { if (!activeThread) { return; } + if (how === "linked" && environmentId !== undefined) { + void navigate({ + to: "/linked/$computerId/$linkedThreadId", + params: linkedThreadRouteParams(scopeThreadRef(environmentId, sourceThreadId)), + }); + return; + } void navigate({ to: "/$environmentId/$threadId", params: { @@ -8815,8 +8824,8 @@ export default function ChatView(props: ChatViewProps) { {chatHeader} {/* The open thread's family: its parent and the threads it started. */} - {activeThreadRef !== null && routeKind === "server" ? ( - + {activeThreadKey !== null && routeKind === "server" ? ( + ) : null} {threadErrorRateLimitResetCreditDialog} diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 7a3003cb4..0e5ffbb71 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1650,9 +1650,9 @@ export type InboxRemoteChildPhase = AgentThreadStatusWord | RemoteChildRequestSt * A child in a parent's family the app has no thread for, shown from the * parent's own record of it: one on a computer this app can't see (its last * known status, or a start that has no thread there yet), or one started here - * that is still being set up. It can't be opened: there is no thread to open, - * so once wrapped and seen through the parent it has no row until the parent - * wraps and holds it. + * that is still being set up. This app has no thread to open: one on another + * computer opens read through the link where the parent's computer can do + * that (`linkedRefOf`, LinkedThreadView), and stays in the family while open. */ export interface InboxRemoteChild extends InboxFamilyExit { /** @@ -1670,6 +1670,8 @@ export interface InboxRemoteChild extends InboxFamilyExit { readonly computerLabel: string; readonly title: string; readonly phase: InboxRemoteChildPhase; + /** The parent's computer no longer links to that one: nothing can be read from there. */ + readonly unlinked?: true | undefined; /** * The user can wrap it up (or reopen it, once done) from here: a thread * there that nothing holds in front of them. Absent: a start, or one being @@ -1897,8 +1899,11 @@ export function liveFamilyOf(input: { const children = sortFamilyChildren(input.children).filter((child) => isLiveFamilyMember(child, input.parent, input), ); + // One open in the chat (read through the link) stays, as a child here does. const remoteChildren = input.remoteChildren.filter( - (child) => !hasLeftLiveFamily(child, input.parent, input.now), + (child) => + child.threadKey === input.activeThreadKey || + !hasLeftLiveFamily(child, input.parent, input.now), ); return children.length === 0 && remoteChildren.length === 0 ? null : { children, remoteChildren }; } @@ -1995,8 +2000,10 @@ export function buildInboxSections(input: { : []; const remoteChildren: InboxRemoteChild[] = []; for (const child of heads ? remoteChildrenOf(entry) : []) { - if (hasLeftLiveFamily(child, entry, input.now)) doneRemote.push({ child, startedBy: entry }); - else remoteChildren.push(child); + // One open in the chat (read through the link) stays, as a child here does. + if (child.threadKey !== input.activeThreadKey && hasLeftLiveFamily(child, entry, input.now)) { + doneRemote.push({ child, startedBy: entry }); + } else remoteChildren.push(child); } const open = input.isFamilyOpen(entry.threadKey); const shownChildren = open @@ -2006,7 +2013,9 @@ export function buildInboxSections(input: { ); const shownRemoteChildren = open ? remoteChildren - : remoteChildren.filter(isChildThreadNeedingYou); + : remoteChildren.filter( + (child) => isChildThreadNeedingYou(child) || child.threadKey === input.activeThreadKey, + ); return { entry, children, @@ -2102,7 +2111,9 @@ export function inboxLiveRowHoldsOpenChild( activeThreadKey: string | null, ): boolean { return ( - activeThreadKey !== null && row.children.some((child) => child.threadKey === activeThreadKey) + activeThreadKey !== null && + (row.children.some((child) => child.threadKey === activeThreadKey) || + row.remoteChildren.some((child) => child.threadKey === activeThreadKey)) ); } @@ -2133,7 +2144,8 @@ export function windowInboxDoneRows( (row, index) => index < limit || (row.kind === "thread" && - (row.row.openChild !== null || row.row.entry.threadKey === activeThreadKey)), + (row.row.openChild !== null || row.row.entry.threadKey === activeThreadKey)) || + (row.kind === "remote" && row.row.child.threadKey === activeThreadKey), ); } @@ -2520,6 +2532,7 @@ export function remoteChildEntry( phase, // With its link gone, its last word is history, not news. status: linked ? status : null, + ...(linked ? {} : { unlinked: true as const }), }; const filing = child.filing; if (filing === undefined) { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index f038c2c90..ce6ed8273 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -131,9 +131,16 @@ import { InboxRemoteDoneRow, InboxThreadRow, type InboxThreadFamily, + type RemoteChildOpen, type RemoteChildSetDone, type RemoteParentLine, } from "./sidebar/InboxRows"; +import { linkedRefOf } from "./chat/familyTabs.logic"; +import { useConnectedComputerCapabilityCheck } from "../environments/computerCapabilities"; +import { + linkedThreadRouteParams, + resolveLinkedThreadRouteRef, +} from "../environments/links/linkedThreads"; import { groupPendingLinkRequests, useComputerLabel, @@ -653,6 +660,17 @@ export default function Sidebar() { select: (params) => resolveThreadRouteRef(params), }); const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; + // A child on a computer this app can't see, open read through the link. + const linkedRouteKey = useParams({ + strict: false, + select: (params) => { + const ref = resolveLinkedThreadRouteRef(params); + return ref === null ? null : scopedThreadKey(ref); + }, + }); + // The thread open in the chat, as the list keeps it on screen: one here, or + // one read through the link. + const openInboxKey = routeThreadKey ?? linkedRouteKey; const keybindings = useServerKeybindings(); const openAddProjectCommandPalette = useCommandPaletteStore((store) => store.openAddProject); const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility(); @@ -899,7 +917,7 @@ export default function Sidebar() { ), ), isFamilyOpen: (parentKey) => childThreadFamilyOpenById[parentKey] === true, - activeThreadKey: routeThreadKey, + activeThreadKey: openInboxKey, now: nowIso, sortLive: (heads) => sortInboxThreadsBy( @@ -925,6 +943,7 @@ export default function Sidebar() { entries, inboxCustomOrder, inboxSort, + linkedRouteKey, nowIso, roomsFilterActive, routeThreadKey, @@ -1036,13 +1055,13 @@ export default function Sidebar() { groupKey !== null && collapsedInboxGroups[groupKey] === true && !row.entry.isLead && - !inboxLiveRowHolds(row, routeThreadKey); + !inboxLiveRowHolds(row, openInboxKey); const isFamily = row.children.length > 0 || row.remoteChildren.length > 0; return { pinned: staysOnTop(row.entry), alwaysShown: inboxLiveRowHasAttention(row) || - inboxLiveRowHolds(row, routeThreadKey) || + inboxLiveRowHolds(row, openInboxKey) || inboxLiveRowHolds(row, renamingThreadKey), costPx: hiddenByGroup ? 0 : isFamily ? familyPx : plainPx, childrenPx: hiddenByGroup @@ -1078,9 +1097,9 @@ export default function Sidebar() { liveRoomPx, localChildRowPx, plainRowPx, + openInboxKey, remoteChildRowPx, renamingThreadKey, - routeThreadKey, sidebarGrouping, ]); const { visible: visibleLiveEntries, hiddenCount: hiddenLiveCount } = useMemo( @@ -1089,7 +1108,7 @@ export default function Sidebar() { rows: liveEntries, hasAttention: (row) => inboxLiveRowHasAttention(row) || - inboxLiveRowHolds(row, routeThreadKey) || + inboxLiveRowHolds(row, openInboxKey) || inboxLiveRowHolds(row, renamingThreadKey), isPinned: (row) => staysOnTop(row.entry), limit: liveFoldLimit + revealedLiveCount, @@ -1097,12 +1116,12 @@ export default function Sidebar() { // the newest ones. Every row there is where the user put it. expanded: inboxSort === "custom", }), - [inboxSort, liveEntries, liveFoldLimit, renamingThreadKey, revealedLiveCount, routeThreadKey], + [inboxSort, liveEntries, liveFoldLimit, openInboxKey, renamingThreadKey, revealedLiveCount], ); const nextLiveRevealCount = Math.min(LIVE_REVEAL_STEP, hiddenLiveCount); const visibleDoneEntries = useMemo( - () => windowInboxDoneRows(wrappedRows, DONE_PREVIEW_COUNT + revealedDoneCount, routeThreadKey), - [wrappedRows, revealedDoneCount, routeThreadKey], + () => windowInboxDoneRows(wrappedRows, DONE_PREVIEW_COUNT + revealedDoneCount, openInboxKey), + [wrappedRows, revealedDoneCount, openInboxKey], ); const nextDoneRevealCount = Math.min( DONE_REVEAL_STEP, @@ -1116,10 +1135,11 @@ export default function Sidebar() { ? visibleDoneEntries : wrappedRows.filter( (row) => - row.kind === "thread" && - (row.row.entry.threadKey === routeThreadKey || row.row.openChild !== null), + (row.kind === "thread" && + (row.row.entry.threadKey === routeThreadKey || row.row.openChild !== null)) || + (row.kind === "remote" && row.row.child.threadKey === linkedRouteKey), ), - [wrappedRows, routeThreadKey, visibleDoneEntries, wrappedOpen], + [linkedRouteKey, wrappedRows, routeThreadKey, visibleDoneEntries, wrappedOpen], ); // Open, the shelf sorts its rows under days; closed, its header says how // many wrapped today, so a thread filed away on its own is not lost. @@ -1310,7 +1330,7 @@ export default function Sidebar() { (row) => row.entry.isLead || row.entry.threadKey === routeThreadKey || - inboxLiveRowHoldsOpenChild(row, routeThreadKey), + inboxLiveRowHoldsOpenChild(row, openInboxKey), ) : group.rows, }; @@ -1319,6 +1339,7 @@ export default function Sidebar() { collapsedInboxGroups, environmentScopeOptions, liveEntries, + openInboxKey, routeThreadKey, sidebarGrouping, sidebarProjectByKey, @@ -1574,6 +1595,28 @@ export default function Sidebar() { [closeSheet, navigate, navigateToThread], ); + // A child on a computer this app can't see opens read through the link, + // where its parent's computer does that (LinkedThreadView). + const readsLinked = useConnectedComputerCapabilityCheck("linkedThreadRead"); + const openLinkedChild = useCallback( + (child) => { + const ref = linkedRefOf(child); + if (ref === null) return; + closeSheet(); + void navigate({ + to: "/linked/$computerId/$linkedThreadId", + params: linkedThreadRouteParams(ref), + }); + }, + [closeSheet, navigate], + ); + const linkedChildOpener = (child: InboxRemoteChild): RemoteChildOpen | undefined => + child.parentRef !== undefined && + linkedRefOf(child) !== null && + readsLinked(child.parentRef.environmentId) + ? openLinkedChild + : undefined; + const openFleetComputer = useCallback( (environmentId: EnvironmentId) => { closeSheet(); @@ -2352,6 +2395,8 @@ export default function Sidebar() { child={child} shortTitle={childShortTitles.get(child.threadKey)} onSetDone={setRemoteChildDone} + onOpen={linkedChildOpener(child)} + isActive={child.threadKey === linkedRouteKey} /> ))} @@ -2499,6 +2544,8 @@ export default function Sidebar() { child={child} startedByTitle={startedBy.thread.title} onSetDone={setRemoteChildDone} + onOpen={linkedChildOpener(child)} + isActive={child.threadKey === linkedRouteKey} /> ); diff --git a/apps/web/src/components/chat/FamilyTabs.tsx b/apps/web/src/components/chat/FamilyTabs.tsx index c29c7a215..86c0ff8e5 100644 --- a/apps/web/src/components/chat/FamilyTabs.tsx +++ b/apps/web/src/components/chat/FamilyTabs.tsx @@ -8,6 +8,10 @@ * parent, so switching between members keeps it mounted and still. It reads * a narrow model (`sameFamilyTabs`), so a reply streaming in one thread does * not redraw it. + * + * A child on a computer this app can't see opens read through the link + * (LinkedThreadView), where the parent's computer can do that; the row then + * shows with that child's tab open. */ import { parseScopedThreadKey, scopedThreadKey } from "@threadlines/client-runtime"; import type { ScopedThreadRef } from "@threadlines/contracts"; @@ -22,6 +26,8 @@ import { useRemoteFamilyChildren } from "../../hooks/useRemoteFamilyChildren"; import { useKept } from "../../hooks/useStableIdentity"; import { useThreadMenu } from "../../hooks/useThreadMenu"; import { useTouchHoldMenu } from "../../hooks/useTouchHoldMenu"; +import { useConnectedComputerCapabilityCheck } from "../../environments/computerCapabilities"; +import { linkedThreadRouteParams } from "../../environments/links/linkedThreads"; import { requestIdleThreadDetailPrewarm } from "../../environments/runtime/service"; import { cn } from "../../lib/utils"; import { buildThreadRouteParams } from "../../threadRoutes"; @@ -131,18 +137,42 @@ function useRowMeasure( return enabled ? measure : null; } +/** What a tab opens: a thread this app has, or a child read through the link. */ +export type FamilyTabTarget = + | { readonly kind: "thread"; readonly ref: ScopedThreadRef } + | { readonly kind: "linked"; readonly ref: ScopedThreadRef }; + +/** What a click on `tab` opens; null when it opens nothing. */ +function targetOf(tab: FamilyTab): FamilyTabTarget | null { + if (tab.threadRef !== null) return { kind: "thread", ref: tab.threadRef }; + if (tab.linkedRef !== null) return { kind: "linked", ref: tab.linkedRef }; + return null; +} + /** - * The row for `threadRef`'s family, or nothing when it has none. While it - * shows, the header's "Lead chat" and "Started by" chips give way to it + * The row for the open thread's family, or nothing when it has none. + * `openKey` is the open thread's key; for a child read through the link, + * `parentKey` names the parent that holds it. While the row shows, the + * header's "Lead chat" and "Started by" chips give way to it * (`useFamilyTabsShown`). */ -export function FamilyTabs({ threadRef }: { threadRef: ScopedThreadRef }) { - const family = useFamilyTabs(threadRef); +export function FamilyTabs({ openKey, parentKey }: { openKey: string; parentKey?: string }) { + const family = useFamilyTabs(openKey, parentKey); const navigate = useNavigate(); const open = useCallback( - (target: ScopedThreadRef) => { - void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(target) }); + (target: FamilyTabTarget) => { + if (target.kind === "linked") { + void navigate({ + to: "/linked/$computerId/$linkedThreadId", + params: linkedThreadRouteParams(target.ref), + }); + return; + } + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target.ref), + }); }, [navigate], ); @@ -177,22 +207,24 @@ export function FamilyTabs({ threadRef }: { threadRef: ScopedThreadRef }) { * changes. Membership is the sidebar's own rule (`liveFamilyOf`, through * `familyTabsOf`), fed by the same filing (`useInboxThreads`). */ -export function useFamilyTabs(threadRef: ScopedThreadRef): FamilyTabsModel | null { - const openKey = scopedThreadKey(threadRef); +export function useFamilyTabs(openKey: string, parentKey?: string): FamilyTabsModel | null { const { entries, nowIso } = useInboxThreads(); const remoteFamilyChildren = useRemoteFamilyChildren(nowIso); + const readsLinked = useConnectedComputerCapabilityCheck("linkedThreadRead"); const family = useMemo(() => { const keys = new Set(entries.map((entry) => entry.threadKey)); return familyTabsOf({ openKey, + parentKey, entries, remoteChildrenOf: (parent) => remoteFamilyChildren(parent.thread, (threadId) => keys.has(scopedThreadKey({ environmentId: parent.thread.environmentId, threadId })), ), + canReadLinked: (parent) => readsLinked(parent.thread.environmentId), now: nowIso, }); - }, [entries, nowIso, openKey, remoteFamilyChildren]); + }, [entries, nowIso, openKey, parentKey, readsLinked, remoteFamilyChildren]); return useKept(family, sameFamilyTabs); } @@ -201,7 +233,7 @@ const FamilyTabRow = memo(function FamilyTabRow({ onOpen, }: { family: FamilyTabsModel; - onOpen: (target: ScopedThreadRef) => void; + onOpen: (target: FamilyTabTarget) => void; }) { const isMobile = useIsMobile(); const rowRef = useRef(null); @@ -312,10 +344,11 @@ const FamilyTabButton = memo(function FamilyTabButton({ active: boolean; /** May shrink when the row is crowded (desktop); on a phone each keeps its width and the row scrolls. */ fill: boolean; - onOpen: (target: ScopedThreadRef) => void; + onOpen: (target: FamilyTabTarget) => void; buttonRef?: React.RefObject | undefined; }) { const threadMenu = useThreadMenu(); + const target = targetOf(tab); const openMenu = useCallback( (position: { readonly x: number; readonly y: number }) => { if (tab.threadRef !== null) { @@ -348,7 +381,7 @@ const FamilyTabButton = memo(function FamilyTabButton({ title={tab.computerLabel === null ? tab.title : `${tab.title} on ${tab.computerLabel}`} data-testid={`family-tab-${tab.key}`} data-family-tab-kind={tab.kind} - disabled={tab.threadRef === null} + disabled={target === null} className={cn( TAB_BOX_CLASS, "transition-colors focus-ring", @@ -364,7 +397,7 @@ const FamilyTabButton = memo(function FamilyTabButton({ : "text-muted-foreground hover:text-foreground disabled:hover:text-muted-foreground", )} onClick={() => { - if (tab.threadRef !== null && !active) onOpen(tab.threadRef); + if (target !== null && !active) onOpen(target); // A press on the open lead's tab says what a lead is (a phone never hovers). else if (active) showLeadCard?.(); }} @@ -410,7 +443,7 @@ function FamilyTabOverflow({ onOpen, }: { hidden: readonly FamilyTab[]; - onOpen: (target: ScopedThreadRef) => void; + onOpen: (target: FamilyTabTarget) => void; }) { // The colour of the first hidden thread that needs the user: no new colour. const needsYouDot = hidden.find((tab) => tab.needsYou)?.dotClass ?? null; @@ -436,9 +469,10 @@ function FamilyTabOverflow({ {hidden.map((tab) => ( { - if (tab.threadRef !== null) onOpen(tab.threadRef); + const target = targetOf(tab); + if (target !== null) onOpen(target); }} > diff --git a/apps/web/src/components/chat/LinkedThreadView.tsx b/apps/web/src/components/chat/LinkedThreadView.tsx new file mode 100644 index 000000000..48bb1797b --- /dev/null +++ b/apps/web/src/components/chat/LinkedThreadView.tsx @@ -0,0 +1,454 @@ +/** + * A child on a computer this app can't see, read through the link + * (docs/design/child-threads.md, "Opening a child on a computer the app + * can't see"). The parent's computer reads it from the computer it runs on + * (`links.readThread`), so its family's tab and its sidebar row open it even + * where this app has no connection there. It shows the messages as the + * thread tools read them: what was asked and what the agent answered, without + * its tool steps, and with no message box. Connecting to that computer opens + * the real thread instead. + */ +import { scopedThreadKey } from "@threadlines/client-runtime"; +import type { AgentThreadReadResult, ScopedThreadRef } from "@threadlines/contracts"; +import { keepPreviousData, useQuery } from "@tanstack/react-query"; +import { useNavigate } from "@tanstack/react-router"; +import { CloudIcon } from "lucide-react"; +import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; + +import { ELECTRON_HEADER_HEIGHT_CLASS } from "../../desktopChrome"; +import { describeComputerLinkFailure } from "../../environments/links/computerLinks"; +import { readLinkedThread } from "../../environments/links/linkedThreads"; +import { isElectron } from "../../env"; +import { useInboxThreads } from "../../hooks/useInboxThreads"; +import { useRemoteFamilyChildren } from "../../hooks/useRemoteFamilyChildren"; +import { cn } from "../../lib/utils"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import ChatMarkdown from "../ChatMarkdown"; +import { type InboxRemoteChild, remoteChildStatusText } from "../Sidebar.logic"; +import { openConnectComputerDialog } from "../settings/connections/JoinComputerDialog"; +import { + TitleBarContent, + useTitleBarHeaderRef, + useTitleBarRowPresent, +} from "../sidebar/titleBarSlot"; +import { Button } from "../ui/button"; +import { ComposerNoticeDock } from "./ComposerNoticeDock"; +import { SidebarOpenTrigger } from "../ui/sidebar"; +import { FamilyTabs } from "./FamilyTabs"; + +/** The newest messages read at once: thread_read's most. */ +const LINKED_READ_LIMIT = 50; +/** How often an open child that is working is read again. */ +const WORKING_REFRESH_MS = 4_000; +/** The most of one message "Show all" reads, in parts of up to 20,000 characters. */ +const FULL_MESSAGE_PART_LIMIT = 10; + +type LinkedMessage = AgentThreadReadResult["messages"][number]; + +/** Where the open child stands in this app: its parent's record of it, or a thread here. */ +type LinkedChildPlace = + | { + readonly kind: "linked"; + readonly parentRef: ScopedThreadRef; + readonly child: InboxRemoteChild; + } + | { readonly kind: "here" } + | { readonly kind: "missing" }; + +/** Finds the parent that holds `childRef`, as the sidebar files the child. */ +function useLinkedChildPlace(childRef: ScopedThreadRef): LinkedChildPlace { + const { entries, nowIso } = useInboxThreads(); + const remoteFamilyChildren = useRemoteFamilyChildren(nowIso); + const { environmentId, threadId } = childRef; + return useMemo( + () => findLinkedChildPlace(entries, { environmentId, threadId }, remoteFamilyChildren), + [entries, environmentId, remoteFamilyChildren, threadId], + ); +} + +function findLinkedChildPlace( + entries: ReturnType["entries"], + childRef: ScopedThreadRef, + remoteFamilyChildren: ReturnType, +): LinkedChildPlace { + const childKey = scopedThreadKey(childRef); + const keys = new Set(entries.map((entry) => entry.threadKey)); + if (keys.has(childKey)) return { kind: "here" }; + for (const entry of entries) { + const parent = entry.thread; + const holds = parent.remoteChildren?.some( + (child) => + child.environmentId === childRef.environmentId && child.threadId === childRef.threadId, + ); + if (holds !== true) continue; + const child = remoteFamilyChildren(parent, (threadId) => + keys.has(scopedThreadKey({ environmentId: parent.environmentId, threadId })), + ).find((candidate) => candidate.threadKey === childKey); + if (child !== undefined) { + return { + kind: "linked", + parentRef: { environmentId: parent.environmentId, threadId: parent.id }, + child, + }; + } + } + return { kind: "missing" }; +} + +export function LinkedThreadView({ childRef }: { childRef: ScopedThreadRef }) { + const place = useLinkedChildPlace(childRef); + const navigate = useNavigate(); + + // Connected to that computer now: its real thread opens instead. + useEffect(() => { + if (place.kind !== "here") return; + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(childRef), + replace: true, + }); + }, [childRef, navigate, place.kind]); + + if (place.kind !== "linked") { + return ( + + {place.kind === "missing" ? ( +

+ No thread here started this one, so it can't be read from this app. +

+ ) : null} +
+ ); + } + return ( + + } + > + + + ); +} + +/** The header, the family row and the scrolling body, laid out as a thread's chat is. */ +function LinkedThreadFrame({ + title, + computerLabel, + statusText, + familyRow, + children, +}: { + title: string; + computerLabel?: string; + statusText?: string; + familyRow?: React.ReactNode; + children: React.ReactNode; +}) { + const titleRowPresent = useTitleBarRowPresent(); + const header = ( + + ); + return ( +
+ + {header} + + } + > + {header} + + {familyRow} + {children} +
+ ); +} + +function LinkedThreadHeader({ + title, + computerLabel, + statusText, +}: { + title: string; + computerLabel: string | undefined; + statusText: string | undefined; +}) { + const titleBarHeaderRef = useTitleBarHeaderRef(); + return ( +
+ +

+ {title} +

+ {computerLabel !== undefined ? ( + + + ) : null} +
+ ); +} + +function LinkedThreadMessages({ + parentRef, + child, + childRef, +}: { + parentRef: ScopedThreadRef; + child: InboxRemoteChild; + childRef: ScopedThreadRef; +}) { + const working = child.phase === "working" && child.unlinked !== true; + // Read again whenever the parent hears the child moved on: a new read, never + // one already on its way, which may have started before the last turn ended. + const movedOn = `${child.phase}|${child.settledAt ?? ""}|${child.isDone}`; + const query = useQuery({ + queryKey: ["linkedThread", scopedThreadKey(parentRef), scopedThreadKey(childRef), movedOn], + queryFn: () => + readLinkedThread(parentRef.environmentId, { + parentThreadId: parentRef.threadId, + environmentId: childRef.environmentId, + threadId: childRef.threadId, + limit: LINKED_READ_LIMIT, + }), + // The last page stays on screen while the next one is read. + placeholderData: keepPreviousData, + // While it works; a failed read waits for Try again, a focus or a move on. + refetchInterval: (current) => + working && current.state.status !== "error" ? WORKING_REFRESH_MS : false, + refetchOnWindowFocus: true, + retry: false, + }); + const { refetch } = query; + + const read = query.data; + const messages = read?.outcome === "ok" ? read.messages : null; + const failure = query.isError + ? describeComputerLinkFailure(query.error, `Couldn't read it from ${child.computerLabel}.`) + : read !== undefined && read.outcome !== "ok" + ? (read.detail ?? `${child.computerLabel} didn't share this thread.`) + : null; + const failureRow = + failure === null ? null : ( +
+

{failure}

+ +
+ ); + + // Kept at the newest message (its last turn) unless the user scrolled up. + const scrollRef = useRef(null); + const atBottomRef = useRef(true); + const onScroll = useCallback(() => { + const el = scrollRef.current; + if (el === null) return; + atBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80; + }, []); + const messageCount = messages?.length ?? 0; + const lastText = messages?.at(-1)?.text ?? ""; + useLayoutEffect(() => { + const el = scrollRef.current; + if (el === null || !atBottomRef.current || messageCount + lastText.length === 0) return; + el.scrollTop = el.scrollHeight; + }, [lastText, messageCount]); + + return ( + <> +
+
+ {messages === null ? ( + query.isPending ? ( +

+ Reading from {child.computerLabel}… +

+ ) : ( + failureRow + ) + ) : messages.length === 0 ? ( +

No messages yet.

+ ) : ( + <> + {messages.length >= LINKED_READ_LIMIT ? ( +

+ The last {LINKED_READ_LIMIT} messages +

+ ) : null} + {messages.map((message) => ( + + ))} + {/* The last page read stays; this says the newest couldn't be. */} + {failureRow} + + )} +
+
+ {/* Where the message box would be: why there is none, and the way to one. */} +
+
+ + Connect + + ), + }, + ]} + /> +
+
+ + ); +} + +/** One message: the asker's in a bubble on the right, the agent's as the chat draws it. */ +const LinkedMessageRow = memo(function LinkedMessageRow({ + message, + parentRef, + childRef, +}: { + message: LinkedMessage; + parentRef: ScopedThreadRef; + childRef: ScopedThreadRef; +}) { + // The whole message as read for one length of it: a message still being + // written grows, and its newer page drops a whole read of it from before. + const length = message.length ?? message.text.length; + const [full, setFull] = useState< + | { readonly forLength: number; readonly text: string; readonly cut: boolean } + | { readonly error: string } + | "loading" + | null + >(null); + const whole = + full !== null && full !== "loading" && "text" in full && full.forLength === length + ? full + : null; + const text = whole?.text ?? message.text; + const clipped = message.clipped === true && whole === null; + + const showAll = useCallback(async () => { + setFull("loading"); + try { + let joined = ""; + let offset: number | undefined = 0; + for (let part = 0; part < FULL_MESSAGE_PART_LIMIT && offset !== undefined; part += 1) { + const read = await readLinkedThread(parentRef.environmentId, { + parentThreadId: parentRef.threadId, + environmentId: childRef.environmentId, + threadId: childRef.threadId, + messageId: message.messageId, + offset, + }); + const piece = read.outcome === "ok" ? read.messages[0] : undefined; + if (piece === undefined || piece.messageId !== message.messageId) { + throw new Error(read.detail ?? "That message can't be read in full."); + } + joined += piece.text; + offset = piece.nextOffset; + } + setFull({ forLength: length, text: joined, cut: offset !== undefined }); + } catch (error) { + setFull({ error: describeComputerLinkFailure(error, "That message can't be read in full.") }); + } + }, [childRef.environmentId, childRef.threadId, length, message.messageId, parentRef]); + + const footer = clipped ? ( +
+ + {full !== null && full !== "loading" && "error" in full ? {full.error} : null} +
+ ) : whole?.cut === true ? ( +

+ The first {(FULL_MESSAGE_PART_LIMIT * 20_000).toLocaleString()} characters +

+ ) : null; + + const markdown = ( + + ); + + if (message.role === "user") { + return ( +
+ {message.origin !== "user" ? ( + {message.author} + ) : null} +
+ {markdown} + {footer} +
+
+ ); + } + return ( +
+ {markdown} + {footer} +
+ ); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 33b5e6fcc..de0b9e953 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -172,6 +172,7 @@ import { resolveThreadStatusPill, } from "../Sidebar.logic"; import { useComputerLabel } from "../sidebar/linkedComputers"; +import { useConnectedComputerCapability } from "../../environments/computerCapabilities"; import { describeScheduleCall, parseScheduleCallResult, @@ -292,6 +293,13 @@ import { providerInstanceShowsBadge } from "../../providerInstances"; // components (WorkingTimer, LiveElapsed) handle it. // --------------------------------------------------------------------------- +/** Opens another thread; see MessagesTimelineProps.onOpenThread. */ +export type OpenThread = ( + threadId: ThreadId, + environmentId?: EnvironmentId, + how?: "linked", +) => void; + interface TimelineRowSharedState { timestampFormat: TimestampFormat; /** Room agents by `roomAgentKey`; null outside rooms. */ @@ -354,7 +362,7 @@ interface TimelineRowSharedState { /** See MessagesTimelineProps.workflowRunActions. */ workflowRunActions: WorkflowRunActions | null; /** See MessagesTimelineProps.onOpenThread. */ - onOpenThread: ((threadId: ThreadId, environmentId?: EnvironmentId) => void) | null; + onOpenThread: OpenThread | null; /** Every finished `thread_start` call, by turn: a call's record reads its turn's. */ threadStartCallsByTurn: ReadonlyMap>; /** A run thread's own first message and the line it folds to (MessagesTimelineProps.scheduledRunLabel). */ @@ -909,8 +917,10 @@ interface MessagesTimelineProps { * Opens another thread: the one that started this thread, or one this * thread's agent started (child threads). `environmentId` names the * computer it lives on when that is another one; absent, this thread's. + * `"linked"`: a child on a computer this app can't see, read through the + * link (LinkedThreadView). */ - onOpenThread?: ((threadId: ThreadId, environmentId?: EnvironmentId) => void) | null | undefined; + onOpenThread?: OpenThread | null | undefined; /** * The thread was started by a scheduled task's run: its first message, the * run's own, folds to this line ("Event · ", "Scheduled · ") @@ -3344,7 +3354,7 @@ function ThreadMessageTimelineRow({ title={formatTimestamp(message.createdAt, ctx.timestampFormat)} >
- {ctx.onOpenThread && source.openable ? ( + {ctx.onOpenThread && (source.openable || source.linked) ? ( ); } diff --git a/apps/web/src/components/chat/familyTabs.logic.test.ts b/apps/web/src/components/chat/familyTabs.logic.test.ts index f15a318b0..bfa423a26 100644 --- a/apps/web/src/components/chat/familyTabs.logic.test.ts +++ b/apps/web/src/components/chat/familyTabs.logic.test.ts @@ -2,7 +2,7 @@ import { scopedThreadKey, scopeThreadRef } from "@threadlines/client-runtime"; import { EnvironmentId, ThreadId } from "@threadlines/contracts"; import { describe, expect, it } from "vite-plus/test"; -import type { ThreadStatusPill } from "../Sidebar.logic"; +import type { InboxRemoteChild, ThreadStatusPill } from "../Sidebar.logic"; import type { SidebarThreadSummary } from "../../types"; import { type FamilyTab, @@ -62,7 +62,35 @@ function entry( } const tabsFor = (open: string, entries: readonly FamilyTabEntry[]) => - familyTabsOf({ openKey: keyOf(open), entries, remoteChildrenOf: () => [], now: NOW }); + familyTabsOf({ + openKey: keyOf(open), + entries, + remoteChildrenOf: () => [], + canReadLinked: () => true, + now: NOW, + }); + +const windowsId = EnvironmentId.make("environment-windows"); +const windowsKeyOf = (id: string) => scopedThreadKey(scopeThreadRef(windowsId, ThreadId.make(id))); +function remoteChild( + id: string, + options: { threadId?: string | null; done?: boolean } = {}, +): InboxRemoteChild { + const threadId = options.threadId === undefined ? id : options.threadId; + return { + threadKey: threadId === null ? `start:${windowsId}:${id}` : windowsKeyOf(threadId), + environmentId: windowsId, + threadId: threadId === null ? null : ThreadId.make(threadId), + computerLabel: "Windows PC", + title: `Remote ${id}`, + phase: options.done ? "wrapped" : threadId === null ? "sending" : "working", + status: options.done ? null : working, + isDone: options.done ?? false, + // Wrapped and already seen through the parent: gone from the live family. + settledAt: "2026-11-16T10:00:00.000Z", + seenAt: "2026-11-16T11:00:00.000Z", + }; +} describe("family tabs", () => { const family = [ @@ -110,10 +138,63 @@ describe("family tabs", () => { }); }); +describe("family tabs with children on a computer this app can't see", () => { + const parent = entry("parent"); + const children = [remoteChild("busy"), remoteChild("asked", { threadId: null })]; + const tabs = (input: { + open: string; + parentKey?: string; + remote?: readonly InboxRemoteChild[]; + readsLinked?: boolean; + }) => + familyTabsOf({ + openKey: input.open, + parentKey: input.parentKey, + entries: [parent], + remoteChildrenOf: () => input.remote ?? children, + canReadLinked: () => input.readsLinked ?? true, + now: NOW, + }); + + it("opens a child there through the link only where the parent's computer reads it", () => { + const reading = tabs({ open: keyOf("parent") }); + expect(reading?.tabs.map((tab) => tab.linkedRef)).toEqual([ + null, + scopeThreadRef(windowsId, ThreadId.make("busy")), + // A start with no thread there yet has nothing to read. + null, + ]); + const older = tabs({ open: keyOf("parent"), readsLinked: false }); + expect(older?.tabs.every((tab) => tab.linkedRef === null)).toBe(true); + // Nor once the parent's computer no longer links there. + const unlinked = tabs({ + open: keyOf("parent"), + remote: [{ ...remoteChild("busy"), unlinked: true }], + }); + expect(unlinked?.tabs[1]?.linkedRef).toBeNull(); + }); + + it("shows the row on a child open through the link, and keeps it there once wrapped", () => { + const open = tabs({ + open: windowsKeyOf("finished"), + parentKey: keyOf("parent"), + remote: [remoteChild("finished", { done: true })], + }); + expect(open?.familyKey).toBe(keyOf("parent")); + expect(open?.openKey).toBe(windowsKeyOf("finished")); + expect(open?.tabs.map((tab) => tab.key)).toEqual([keyOf("parent"), windowsKeyOf("finished")]); + // Not open: it has left the family, so the parent has no row. + expect( + tabs({ open: keyOf("parent"), remote: [remoteChild("finished", { done: true })] }), + ).toBeNull(); + }); +}); + describe("fitting the row", () => { const tab = (key: string, needsYou = false): FamilyTab => ({ key, threadRef: null, + linkedRef: null, kind: "child", title: key, shortTitle: key, diff --git a/apps/web/src/components/chat/familyTabs.logic.ts b/apps/web/src/components/chat/familyTabs.logic.ts index ca5182677..4667fbb83 100644 --- a/apps/web/src/components/chat/familyTabs.logic.ts +++ b/apps/web/src/components/chat/familyTabs.logic.ts @@ -27,6 +27,11 @@ export interface FamilyTab { readonly key: string; /** What a click opens; null for a child this app has no thread for. */ readonly threadRef: ScopedThreadRef | null; + /** + * A child on a computer this app can't see that a click opens read through + * the link instead (`/linked/...`, LinkedThreadView); null otherwise. + */ + readonly linkedRef: ScopedThreadRef | null; readonly kind: "parent" | "child"; readonly title: string; /** @@ -70,17 +75,25 @@ export interface FamilyTabEntry extends InboxFamilyEntry { * on each member while its parent is live. The parent first, then its * threads in the order the sidebar draws them. Null for a thread with no * family, a child the user made its own, or one whose parent is wrapped. + * + * The open thread may also be a child on a computer this app can't see, read + * through the link: `parentKey` then names the parent that holds it. + * `canReadLinked` says whether a parent's computer reads such children for + * this app (its `linkedThreadRead` capability). */ export function familyTabsOf(input: { readonly openKey: string; + readonly parentKey?: string | undefined; readonly entries: readonly E[]; readonly remoteChildrenOf: (parent: E) => readonly InboxRemoteChild[]; + readonly canReadLinked: (parent: E) => boolean; readonly now: string; }): FamilyTabs | null { const byKey = new Map(input.entries.map((entry) => [entry.threadKey, entry] as const)); const open = byKey.get(input.openKey); - if (open === undefined) return null; - const parentKey = familyParentKeyOf(open.thread) ?? open.threadKey; + const parentKey = + open !== undefined ? (familyParentKeyOf(open.thread) ?? open.threadKey) : input.parentKey; + if (parentKey === undefined) return null; const parent = byKey.get(parentKey); if (parent === undefined) return null; const family = liveFamilyOf({ @@ -97,13 +110,16 @@ export function familyTabsOf(input: { // The open child must be one of them (it always is while its parent is live). if ( parent.threadKey !== input.openKey && - !family.children.some((child) => child.threadKey === input.openKey) + !family.children.some((child) => child.threadKey === input.openKey) && + !family.remoteChildren.some((child) => child.threadKey === input.openKey) ) { return null; } + const readsLinked = input.canReadLinked(parent); const childTab = (child: E): FamilyTab => ({ key: child.threadKey, threadRef: scopeThreadRef(child.thread.environmentId, child.thread.id), + linkedRef: null, kind: "child", title: child.thread.title, shortTitle: child.thread.title, @@ -118,6 +134,7 @@ export function familyTabsOf(input: { const remoteTab = (child: InboxRemoteChild): FamilyTab => ({ key: child.threadKey, threadRef: null, + linkedRef: readsLinked ? linkedRefOf(child) : null, kind: "child", title: child.title, shortTitle: child.title, @@ -138,6 +155,7 @@ export function familyTabsOf(input: { { key: parent.threadKey, threadRef: scopeThreadRef(parent.thread.environmentId, parent.thread.id), + linkedRef: null, kind: "parent", title: parent.thread.title, shortTitle: parent.thread.title, @@ -154,6 +172,17 @@ export function familyTabsOf(input: { }; } +/** + * The thread a child on a computer this app can't see would be read as + * through the link: one that has a thread there. A start with no thread yet, + * a child being set up here, and one whose link is gone have nothing to read. + */ +export function linkedRefOf(child: InboxRemoteChild): ScopedThreadRef | null { + return child.threadId === null || child.phase === "setting_up" || child.unlinked === true + ? null + : scopeThreadRef(child.environmentId, child.threadId); +} + /** Whether two rows draw the same: the row skips a redraw when nothing it shows changed. */ export function sameFamilyTabs(left: FamilyTabs | null, right: FamilyTabs | null): boolean { if (left === right) return true; @@ -166,6 +195,7 @@ export function sameFamilyTabs(left: FamilyTabs | null, right: FamilyTabs | null const other = right.tabs[index]!; return ( tab.key === other.key && + (tab.linkedRef === null) === (other.linkedRef === null) && tab.title === other.title && tab.shortTitle === other.shortTitle && tab.lead === other.lead && diff --git a/apps/web/src/components/sidebar/InboxRows.browser.tsx b/apps/web/src/components/sidebar/InboxRows.browser.tsx index 9e1477a04..19988f8ce 100644 --- a/apps/web/src/components/sidebar/InboxRows.browser.tsx +++ b/apps/web/src/components/sidebar/InboxRows.browser.tsx @@ -961,6 +961,7 @@ describe("a thread another computer asked to start", () => { setAccess: unused, remove: unused, respondRequest, + readThread: unused, }); useComputerLinksStore.getState().put(MAC_MINI, { outbound: [], inbound: [], pending }); } diff --git a/apps/web/src/components/sidebar/InboxRows.tsx b/apps/web/src/components/sidebar/InboxRows.tsx index b8dd65ea7..62858c92e 100644 --- a/apps/web/src/components/sidebar/InboxRows.tsx +++ b/apps/web/src/components/sidebar/InboxRows.tsx @@ -1722,31 +1722,46 @@ export const InboxChildRow = memo(function InboxChildRow(props: InboxChildRowPro * and title as a child row has them, then under the title the cloud (it * isn't on this device) with where it stands ("Mac mini · working", "Waiting for Mac mini to allow * it"): a second line, so a narrow list keeps both the title and the - * computer. The app has no thread to open, so the status line explains - * itself on hover. One that nothing holds in front of the user can be - * wrapped up (or reopened) from here, like a child here. + * computer. The app has no thread there: where the parent's computer reads + * it through the link, a click opens it that way (`onOpen`, LinkedThreadView), + * else the status line explains itself on hover. One that nothing holds in + * front of the user can be wrapped up (or reopened) from here, like a child here. */ export const InboxRemoteChildRow = memo(function InboxRemoteChildRow({ child, shortTitle, onSetDone, + onOpen, + isActive = false, }: { child: InboxRemoteChild; /** See InboxChildRowProps.shortTitle. */ shortTitle?: string | undefined; /** Wraps it up or reopens it; absent: the row has no button. */ onSetDone?: RemoteChildSetDone | undefined; + /** Opens it read through the link; absent: it can't be opened from here. */ + onOpen?: RemoteChildOpen | undefined; + /** It is open in the chat. */ + isActive?: boolean | undefined; }) { const statusText = remoteChildStatusText(child); const isStart = child.threadId === null; const tone = child.isDone ? undefined : child.status?.colorClass; const showAction = onSetDone !== undefined && child.canWrap === true; + const open = useRemoteChildOpen(child, onOpen); return (
  • {child.isDone ? ( @@ -1808,7 +1823,9 @@ export const InboxRemoteChildRow = memo(function InboxRemoteChildRow({ ? "Its worktree is being made. It opens here once it starts." : isStart ? statusText - : `How it stands on ${child.computerLabel}. Connect to ${child.computerLabel} to open it.`} + : open.role !== undefined + ? `How it stands on ${child.computerLabel}. Click to read it through the link.` + : `How it stands on ${child.computerLabel}. Connect to ${child.computerLabel} to open it.`}
    @@ -1819,6 +1836,38 @@ export const InboxRemoteChildRow = memo(function InboxRemoteChildRow({ /** Wraps up (`done`) or reopens (`active`) a child on a computer this app can't see. */ export type RemoteChildSetDone = (child: InboxRemoteChild, state: "done" | "active") => void; +/** Opens a child on a computer this app can't see, read through the link. */ +export type RemoteChildOpen = (child: InboxRemoteChild) => void; + +/** A remote row's props as a button that opens it; none when `onOpen` is absent. */ +function useRemoteChildOpen( + child: InboxRemoteChild, + onOpen: RemoteChildOpen | undefined, +): { + role?: "button"; + tabIndex?: number; + onClick?: () => void; + onKeyDown?: (event: React.KeyboardEvent) => void; +} { + return useMemo( + () => + onOpen === undefined + ? {} + : { + role: "button", + tabIndex: 0, + onClick: () => onOpen(child), + onKeyDown: (event: React.KeyboardEvent) => { + if (event.target !== event.currentTarget) return; + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + onOpen(child); + }, + }, + [child, onOpen], + ); +} + /** The Wrap up or Reopen button of a child on a computer this app can't see. */ function RemoteChildWrapButton({ child, @@ -1866,26 +1915,37 @@ function RemoteChildWrapButton({ * A child on a computer this app can't see that left its parent's family for * Wrapped (`InboxDoneRemoteRow`): one line like a wrapped thread, the arrow * naming the thread that started it, the cloud naming its computer, then - * when it wrapped. There is no thread here to open; Reopen puts it back + * when it wrapped. There is no thread here: a click opens it read through + * the link where the parent's computer can (`onOpen`). Reopen puts it back * under its parent, on both computers. */ export const InboxRemoteDoneRow = memo(function InboxRemoteDoneRow({ child, startedByTitle, onSetDone, + onOpen, + isActive = false, }: { child: InboxRemoteChild; startedByTitle: string; onSetDone?: RemoteChildSetDone | undefined; + /** Opens it read through the link; absent: it can't be opened from here. */ + onOpen?: RemoteChildOpen | undefined; + /** It is open in the chat. */ + isActive?: boolean | undefined; }) { + const open = useRemoteChildOpen(child, onOpen); return (
  • @@ -1902,7 +1962,9 @@ export const InboxRemoteDoneRow = memo(function InboxRemoteDoneRow({ - {`Started by ${startedByTitle}, on ${child.computerLabel}. Connect to ${child.computerLabel} to open it.`} + {open.role !== undefined + ? `Started by ${startedByTitle}, on ${child.computerLabel}. Click to read it through the link.` + : `Started by ${startedByTitle}, on ${child.computerLabel}. Connect to ${child.computerLabel} to open it.`} diff --git a/apps/web/src/environments/computerCapabilities.ts b/apps/web/src/environments/computerCapabilities.ts index 78964f647..8349271a4 100644 --- a/apps/web/src/environments/computerCapabilities.ts +++ b/apps/web/src/environments/computerCapabilities.ts @@ -8,6 +8,7 @@ import type { ExecutionEnvironmentCapabilities, ExecutionEnvironmentDescriptor, } from "@threadlines/contracts"; +import { useCallback } from "react"; import { readPrimaryEnvironmentDescriptor, usePrimaryEnvironmentDescriptor } from "./primary"; import { @@ -51,6 +52,21 @@ export function useConnectedComputerCapability( return environmentId !== null && capabilityOf(environmentId, capability, primary, runtime); } +/** + * {@link useConnectedComputerCapability} for any computer, as a check: for a + * surface that learns which computer it asks about only as it works. + */ +export function useConnectedComputerCapabilityCheck( + capability: keyof ExecutionEnvironmentCapabilities, +): (environmentId: EnvironmentId) => boolean { + const primary = usePrimaryEnvironmentDescriptor(); + const runtimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); + return useCallback( + (environmentId) => capabilityOf(environmentId, capability, primary, runtimeById[environmentId]), + [capability, primary, runtimeById], + ); +} + function capabilityOf( environmentId: EnvironmentId, capability: keyof ExecutionEnvironmentCapabilities, diff --git a/apps/web/src/environments/links/linkedThreads.ts b/apps/web/src/environments/links/linkedThreads.ts new file mode 100644 index 000000000..5f5490243 --- /dev/null +++ b/apps/web/src/environments/links/linkedThreads.ts @@ -0,0 +1,45 @@ +/** + * Children on computers this app can't see, opened read through the link + * (docs/design/child-threads.md, "Opening a child on a computer the app + * can't see"). The parent's computer reads the child from the computer it + * runs on (`links.readThread`), so the app needs no connection of its own + * there. LinkedThreadView draws it at `/linked/$computerId/$linkedThreadId`. + */ +import { scopeThreadRef } from "@threadlines/client-runtime"; +import type { + AgentThreadReadResult, + EnvironmentId, + LinksReadThreadInput, + ScopedThreadRef, + ThreadId, +} from "@threadlines/contracts"; + +import { readEnvironmentConnection } from "../runtime"; + +/** The route params that open `ref` read through the link. */ +export function linkedThreadRouteParams(ref: ScopedThreadRef): { + computerId: string; + linkedThreadId: string; +} { + return { computerId: ref.environmentId, linkedThreadId: ref.threadId }; +} + +/** The child a `/linked/...` route opens; null when the params don't name one. */ +export function resolveLinkedThreadRouteRef( + params: Partial>, +): ScopedThreadRef | null { + if (!params.computerId || !params.linkedThreadId) return null; + return scopeThreadRef(params.computerId as EnvironmentId, params.linkedThreadId as ThreadId); +} + +/** A page of the child's messages, asked of the parent's computer. */ +export async function readLinkedThread( + parentEnvironmentId: EnvironmentId, + input: LinksReadThreadInput, +): Promise { + const connection = readEnvironmentConnection(parentEnvironmentId); + if (connection === null) { + throw new Error("This app isn't connected to the computer that started it."); + } + return connection.client.links.readThread(input); +} diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 5ee6a0e0f..eac41bf1e 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -39,6 +39,7 @@ import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draf import { Route as ChatFleetIndexRouteImport } from './routes/_chat.fleet.index' import { Route as ChatFleetEnvironmentIdRouteImport } from './routes/_chat.fleet.$environmentId' import { Route as ChatFleetDeviceDeviceIdRouteImport } from './routes/_chat.fleet.device.$deviceId' +import { Route as ChatLinkedComputerIdLinkedThreadIdRouteImport } from './routes/_chat.linked.$computerId.$linkedThreadId' const ChatRoute = ChatRouteImport.update({ id: '/_chat', @@ -190,6 +191,12 @@ const ChatFleetDeviceDeviceIdRoute = ChatFleetDeviceDeviceIdRouteImport.update({ path: '/device/$deviceId', getParentRoute: () => ChatFleetRoute, } as any) +const ChatLinkedComputerIdLinkedThreadIdRoute = + ChatLinkedComputerIdLinkedThreadIdRouteImport.update({ + id: '/linked/$computerId/$linkedThreadId', + path: '/linked/$computerId/$linkedThreadId', + getParentRoute: () => ChatRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof ChatIndexRoute @@ -221,6 +228,7 @@ export interface FileRoutesByFullPath { '/fleet/$environmentId': typeof ChatFleetEnvironmentIdRoute '/fleet/': typeof ChatFleetIndexRoute '/fleet/device/$deviceId': typeof ChatFleetDeviceDeviceIdRoute + '/linked/$computerId/$linkedThreadId': typeof ChatLinkedComputerIdLinkedThreadIdRoute } export interface FileRoutesByTo { '/join': typeof JoinRoute @@ -250,6 +258,7 @@ export interface FileRoutesByTo { '/fleet/$environmentId': typeof ChatFleetEnvironmentIdRoute '/fleet': typeof ChatFleetIndexRoute '/fleet/device/$deviceId': typeof ChatFleetDeviceDeviceIdRoute + '/linked/$computerId/$linkedThreadId': typeof ChatLinkedComputerIdLinkedThreadIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -283,6 +292,7 @@ export interface FileRoutesById { '/_chat/fleet/$environmentId': typeof ChatFleetEnvironmentIdRoute '/_chat/fleet/': typeof ChatFleetIndexRoute '/_chat/fleet/device/$deviceId': typeof ChatFleetDeviceDeviceIdRoute + '/_chat/linked/$computerId/$linkedThreadId': typeof ChatLinkedComputerIdLinkedThreadIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -316,6 +326,7 @@ export interface FileRouteTypes { | '/fleet/$environmentId' | '/fleet/' | '/fleet/device/$deviceId' + | '/linked/$computerId/$linkedThreadId' fileRoutesByTo: FileRoutesByTo to: | '/join' @@ -345,6 +356,7 @@ export interface FileRouteTypes { | '/fleet/$environmentId' | '/fleet' | '/fleet/device/$deviceId' + | '/linked/$computerId/$linkedThreadId' id: | '__root__' | '/_chat' @@ -377,6 +389,7 @@ export interface FileRouteTypes { | '/_chat/fleet/$environmentId' | '/_chat/fleet/' | '/_chat/fleet/device/$deviceId' + | '/_chat/linked/$computerId/$linkedThreadId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -599,6 +612,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatFleetDeviceDeviceIdRouteImport parentRoute: typeof ChatFleetRoute } + '/_chat/linked/$computerId/$linkedThreadId': { + id: '/_chat/linked/$computerId/$linkedThreadId' + path: '/linked/$computerId/$linkedThreadId' + fullPath: '/linked/$computerId/$linkedThreadId' + preLoaderRoute: typeof ChatLinkedComputerIdLinkedThreadIdRouteImport + parentRoute: typeof ChatRoute + } } } @@ -628,6 +648,7 @@ interface ChatRouteChildren { ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute + ChatLinkedComputerIdLinkedThreadIdRoute: typeof ChatLinkedComputerIdLinkedThreadIdRoute } const ChatRouteChildren: ChatRouteChildren = { @@ -640,6 +661,8 @@ const ChatRouteChildren: ChatRouteChildren = { ChatIndexRoute: ChatIndexRoute, ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute, ChatDraftDraftIdRoute: ChatDraftDraftIdRoute, + ChatLinkedComputerIdLinkedThreadIdRoute: + ChatLinkedComputerIdLinkedThreadIdRoute, } const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren) diff --git a/apps/web/src/routes/_chat.linked.$computerId.$linkedThreadId.tsx b/apps/web/src/routes/_chat.linked.$computerId.$linkedThreadId.tsx new file mode 100644 index 000000000..510e213c8 --- /dev/null +++ b/apps/web/src/routes/_chat.linked.$computerId.$linkedThreadId.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { LinkedThreadView } from "../components/chat/LinkedThreadView"; +import { resolveLinkedThreadRouteRef } from "../environments/links/linkedThreads"; + +/** A child on a computer this app can't see, read through the link (LinkedThreadView). */ +function LinkedThreadRoute() { + const childRef = resolveLinkedThreadRouteRef(Route.useParams()); + if (childRef === null) return null; + return ( + + ); +} + +export const Route = createFileRoute("/_chat/linked/$computerId/$linkedThreadId")({ + component: LinkedThreadRoute, +}); diff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts index 8320a7d16..b943a4b0f 100644 --- a/apps/web/src/rpc/wsRpcClient.ts +++ b/apps/web/src/rpc/wsRpcClient.ts @@ -561,6 +561,8 @@ export interface WsRpcClient { readonly setAccess: RpcUnaryMethod; readonly remove: RpcUnaryMethod; readonly respondRequest: RpcUnaryMethod; + /** A parent's child on a linked computer, read through the link, where the descriptor reports `linkedThreadRead`. */ + readonly readThread: RpcUnaryMethod; }; /** * Moving a thread to a linked computer (docs/design/fleet.md, Part 3), on @@ -1467,6 +1469,8 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient { remove: (input) => transport.request((client) => client[WS_METHODS.linksRemove](input)), respondRequest: (input) => transport.request((client) => client[WS_METHODS.linksRespondRequest](input)), + readThread: (input) => + transport.request((client) => client[WS_METHODS.linksReadThread](input)), }, // Never replayed on a new socket: the user answers what is on screen, and // after a reconnect the fresh snapshot says what still waits. diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index a17cc3f86..2a9dd7737 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -90,11 +90,20 @@ These rules override anything in the sections below that disagrees with them. - Parent with working attached children: "Stop N working threads". - **Hover cards.** A child shows "Started by ". A parent shows "Threads: 3 · 1 needs you". - **Wrapped section.** A wrapped parent shows a fork icon and its attached child count. Its wrapped attached children live inside it. -- **Finished child of a live parent** (`hasLeftLiveFamily` in Sidebar.logic.ts). A wrapped child leaves its live parent's family for Wrapped, where it stands as its own row with a `↳` mark ("Started by "); otherwise finished children pile up under a parent still in use. One the user wrapped goes at once. One that wrapped itself (handed back, pull request landed, idle) stays until the user has seen what it finished, so coming back still shows "1 thread finished": a seen stamp (a real visit, never the device's first-load seed) in the child, or in the parent from a turn that ended after the child's answer reached it (`handedBackAt`), and at most two days (`INBOX_AUTO_DONE_AFTER_DAYS`). The child open in the chat stays where it is. A child the machine filter separates from its parent gets the same `↳` mark. Reopening it, or new work, brings it back; when the parent wraps, it folds back inside it. A wrapped child on a computer this app can't see leaves the same way and has no row until the parent wraps. +- **Finished child of a live parent** (`hasLeftLiveFamily` in Sidebar.logic.ts). A wrapped child leaves its live parent's family for Wrapped, where it stands as its own row with a `↳` mark ("Started by "); otherwise finished children pile up under a parent still in use. One the user wrapped goes at once. One that wrapped itself (handed back, pull request landed, idle) stays until the user has seen what it finished, so coming back still shows "1 thread finished": a seen stamp (a real visit, never the device's first-load seed) in the child, or in the parent from a turn that ended after the child's answer reached it (`handedBackAt`), and at most two days (`INBOX_AUTO_DONE_AFTER_DAYS`). The child open in the chat stays where it is. A child the machine filter separates from its parent gets the same `↳` mark. Reopening it, or new work, brings it back; when the parent wraps, it folds back inside it. A wrapped child on a computer this app can't see leaves the same way for a Wrapped row naming the parent, except while it is open in the chat (read through the link, below). - **Parent wrapped while a child is live.** That child renders as its own two-line row with `↳ ` in place of the project name. Once settled, it auto-wraps and joins its family. - **Separated child.** A normal row. Its lineage shows in the hover card. - **Mobile.** Uses the same components. Touch gets `pointer-coarse:` sizing on the summary line. +### Opening a child on a computer the app can't see + +A child on a linked computer that this app isn't connected to has no thread here, only its parent's record of it. Its family tab, its sidebar row (live or in Wrapped) and its line in the parent's "Started N threads" card open it read through the link instead (`LinkedThreadView`, route `/linked/$computerId/$linkedThreadId`): + +- The client asks the parent's computer (`links.readThread`, capability `linkedThreadRead`), which checks the parent holds that child and reads it from the child's computer over the link (`peer.thread.read`, which serves only threads that link started). The client needs no connection to the child's computer, and an older parent computer leaves the tab and row unclickable as before. +- It shows the newest 50 messages as `thread_read` returns them: what was asked and what each agent answered, each clipped at 4,000 characters with Show all, without tool steps and with no message box. A note says so and offers Connect. While the child works, the page reads it again every 4 seconds; otherwise when the parent hears it moved on. +- The family row stays, with the child's tab open. An open child keeps its tab and its sidebar row even after it has left the live family (`activeThreadKey`), as a child here does. +- Once the app connects to that computer, the page swaps to the real thread. + ### Chat - **Child header.** A "Started by " chip, built like the "Forked from" chip (chat/ChatHeader.tsx:225-246). diff --git a/docs/design/fleet.md b/docs/design/fleet.md index 61063a635..6df6f6b95 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -361,7 +361,7 @@ The environment descriptor's `capabilities` gains `computerLinks`, `scheduledTas ### Client -- The parent's child list (the option B family line) includes remote children. When the client is connected to B, the row is B's real thread and opens it. Otherwise it shows A's cached status. +- The parent's child list (the option B family line) includes remote children. When the client is connected to B, the row is B's real thread and opens it. Otherwise it shows A's cached status and opens the thread read through the link (docs/design/child-threads.md, "Opening a child on a computer the app can't see"). - Fleet draws cross-computer work on the line between the two computers. ### Filing a child on another computer (Oct 30) diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 840009f0c..86dd48660 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -68,6 +68,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ * then hide link UI for them. */ computerLinks: Schema.optionalKey(Schema.Boolean), + /** + * The server reads a thread one of its threads started on a linked computer + * for its clients (`links.readThread`), so a client that can't see that + * computer can still open it. Absent: such a child can't be opened. + */ + linkedThreadRead: Schema.optionalKey(Schema.Boolean), /** The server runs scheduled tasks. Absent until a server ships them. */ scheduledTasks: Schema.optionalKey(Schema.Boolean), /** The server keeps a theme library (`themes.*`, docs/design/custom-themes.md). */ diff --git a/packages/contracts/src/links.ts b/packages/contracts/src/links.ts index 5dd1b4604..1fe508ac0 100644 --- a/packages/contracts/src/links.ts +++ b/packages/contracts/src/links.ts @@ -256,3 +256,21 @@ export const LinksRespondRequestInput = Schema.Struct({ allow: Schema.Boolean, }); export type LinksRespondRequestInput = typeof LinksRespondRequestInput.Type; + +/** + * Reading a thread a parent here started on a linked computer, for a client + * that can't see that computer (`links.readThread`). This server asks the + * other one through the link (`peer.thread.read`), so only threads its link + * started can be read, and only for a parent that holds the child. + * `after`, `limit`, `messageId` and `offset` mean what they mean to thread_read. + */ +export const LinksReadThreadInput = Schema.Struct({ + parentThreadId: ThreadId, + environmentId: EnvironmentId, + threadId: ThreadId, + after: Schema.optional(Schema.Number), + limit: Schema.optional(Schema.Number), + messageId: Schema.optional(Schema.String), + offset: Schema.optional(Schema.Number), +}); +export type LinksReadThreadInput = typeof LinksReadThreadInput.Type; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 4fe926a9f..593c1273a 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -24,6 +24,7 @@ import { OutsideAgentsSnapshot, OutsideAgentUpdateInput, } from "./outsideAgents.ts"; +import { AgentThreadReadResult } from "./peerRpc.ts"; import { RelayAssistantCodeResult } from "./relayAssistants.ts"; import { ComputerLinkError, @@ -34,6 +35,7 @@ import { LinksCreateInviteInput, LinksRemoveInput, LinksRemoveResult, + LinksReadThreadInput, LinksRespondRequestInput, LinksSetAccessInput, OutboundComputerLink, @@ -801,6 +803,7 @@ export const WS_METHODS = { linksSetAccess: "links.setAccess", linksRemove: "links.remove", linksRespondRequest: "links.respondRequest", + linksReadThread: "links.readThread", // Scheduled tasks (docs/design/fleet.md, Part 6). Owner and client sessions alike. projectContextSubscribe: "projectContext.subscribe", @@ -2515,6 +2518,24 @@ export const WsMovesRpcGroup = RpcGroup.make( WsMovesRespondManyRpc, ); +/** + * A page of a thread a parent here started on a linked computer, read through + * the link for a client that can't see that computer (LinksReadThreadInput). + * Fails with the reason when that computer can't be reached. + */ +export const WsLinksReadThreadRpc = Rpc.make(WS_METHODS.linksReadThread, { + payload: LinksReadThreadInput, + success: AgentThreadReadResult, + error: ComputerLinkError, +}); + +/** + * Reading threads on linked computers. A group of its own, merged into + * WsRpcGroup, for the same reason as the outside agents' group: the main + * group sits near TypeScript's cap on type work per statement. + */ +export const WsLinkedThreadsRpcGroup = RpcGroup.make(WsLinksReadThreadRpc); + /** On the source computer: what another computer needs to copy this project. */ export const WsProjectSetupsSourceRpc = Rpc.make(WS_METHODS.projectSetupsSource, { payload: ProjectSetupSourceInput, @@ -3256,4 +3277,5 @@ export const WsRpcGroup = WsCoreRpcGroup.merge( WsMovesRpcGroup, WsThemeVsCodeRpcGroup, WsDeviceRpcGroup, + WsLinkedThreadsRpcGroup, );