diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 2868abf3d885d..be9ff3a0f0820 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -72,6 +72,7 @@ import { ThreadPullRequestsSheet } from "./features/threads/ThreadPullRequestsSh import { ThreadAgentsSheet } from "./features/threads/ThreadAgentsSheet"; import { LinkedThreadSheet } from "./features/threads/LinkedThreadSheet"; import { ThreadGuestShareSheet } from "./features/threads/ThreadGuestShareSheet"; +import { ThreadHandoffSheet } from "./features/threads/ThreadHandoffSheet"; import { ThreadBackgroundWorkSheet } from "./features/threads/ThreadBackgroundWorkSheet"; import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl"; import { @@ -825,6 +826,10 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: ThreadGuestShareSheet, options: sheetRoute({ detent: 0.5 }), }), + ThreadHandoff: createNativeStackScreen({ + screen: ThreadHandoffSheet, + options: sheetRoute({ detent: 0.5, androidMaxDetent: 0.9 }), + }), GitOverview: createNativeStackScreen({ screen: GitOverviewSheet, linking: `${THREAD_LINKING_PREFIX}/git`, diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx index df8e5fc93acc0..8da638f2fc0bd 100644 --- a/apps/mobile/src/features/keyboard/CommandPalette.tsx +++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx @@ -55,6 +55,9 @@ import { import { useThreadSearch } from "../../state/queries"; import { requestThreadMessageJump } from "../threads/threadMessageJump"; import { useCanShareWithGuest } from "../threads/useCanShareWithGuest"; +import { useCanMoveThreads } from "../../state/threadHandoff"; +import { threadCanStartHandoff } from "@t3tools/client-runtime/state/peerLinks"; +import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; import { serverEnvironment } from "../../state/server"; @@ -294,6 +297,7 @@ export function CommandPalette(props: { triageEnvironmentId !== null && serverConfigs.get(triageEnvironmentId)?.environment.capabilities.triage === true; const canShareWithGuest = useCanShareWithGuest(activeThreadRef?.environmentId ?? null); + const canMoveThreads = useCanMoveThreads(activeThreadRef?.environmentId ?? null); const contentMatchByKey = new Map( search.matches .filter((match) => match.source === "user" || match.source === "assistant") @@ -424,6 +428,20 @@ export function CommandPalette(props: { run: () => navigation.navigate("ThreadGuestShare", activeThreadRef), }); } + if ( + canMoveThreads && + activeThread != null && + threadCanStartHandoff(activeThread.handoff) && + threadRuntimeCanArchive(activeThread.runtime) + ) { + actions.push({ + key: "continueElsewhere", + kind: "action", + title: gt("Continue on another machine"), + searchTerms: ["continue", "move", "hand off", "handoff", "machine", "environment"], + run: () => navigation.navigate("ThreadHandoff", activeThreadRef), + }); + } } const projectItems: CommandPaletteItem[] = sidebarOrderedProjects .filter((project) => project.archivedAt == null) @@ -500,6 +518,7 @@ export function CommandPalette(props: { environments.length, canTriage, canShareWithGuest, + canMoveThreads, navigation, projects, sidebarOrderedProjects, diff --git a/apps/mobile/src/features/layout/workspace-overlay-routes.ts b/apps/mobile/src/features/layout/workspace-overlay-routes.ts index c4ebbb03a6654..671e4a6dc5b4a 100644 --- a/apps/mobile/src/features/layout/workspace-overlay-routes.ts +++ b/apps/mobile/src/features/layout/workspace-overlay-routes.ts @@ -31,6 +31,7 @@ const LISTED_OVERLAY_ROUTES: ReadonlySet = new Set([ "ThreadAgents", "ThreadBackgroundWork", "ThreadGuestShare", + "ThreadHandoff", "ThreadPullRequests", "ThreadQueue", "ThreadReviewComment", diff --git a/apps/mobile/src/features/threads/HandoffRequestCard.tsx b/apps/mobile/src/features/threads/HandoffRequestCard.tsx new file mode 100644 index 0000000000000..204042c6af3db --- /dev/null +++ b/apps/mobile/src/features/threads/HandoffRequestCard.tsx @@ -0,0 +1,297 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + HANDOFF_LINK_DEFAULT_ACCESS, + handoffLinkCandidates, + handoffRequestDisplay, + type HandoffRequestItem, + handoffRequestTarget, +} from "@t3tools/client-runtime/handoff-request"; +import { + linkRequestFailureMessage, + type LinkableMachine, +} from "@t3tools/client-runtime/link-request"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { + AuthAccessWriteScope, + type AuthMcpClientAccess, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, +} from "@t3tools/contracts"; +import * as Result from "effect/Result"; +import { T, msg, useGT, useMessages } from "gt-react-native"; +import { useRef, useState } from "react"; +import { View, type ColorValue } from "react-native"; + +import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; +import { scopedThreadKey } from "../../lib/scopedEntities"; +import { SettingsSection } from "../settings/components/SettingsSection"; +import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks"; +import { mintPairingCodeOn } from "../../state/peerPairingCode"; +import { useEnvironmentQuery } from "../../state/query"; +import { useEnvironmentScope } from "../../state/session"; +import { threadHandoffEnvironment, useCanMoveThreads } from "../../state/threadHandoff"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { threadHasQueuedMessages, useQueuedThreadKeys } from "../../state/use-thread-outbox"; +import { LINK_ACCESS_CHOICES } from "./LinkRequestCard"; + +const TITLE = msg("Move this thread"); +const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" }; + +/** An agent's ask to move its thread: the user picks the machine and moves it, or declines. */ +export function HandoffRequestCard(props: { + readonly environmentId: EnvironmentId; + readonly projectedItem: OrchestrationV2ProjectedTurnItem; + readonly iconColor: ColorValue; +}) { + const m = useMessages(); + const { item, visibility } = props.projectedItem; + if (item.type !== "handoff_request") return null; + const display = handoffRequestDisplay(item, visibility, m); + if (display.kind === "pending") { + return ; + } + const icon: AppSymbolName = + display.kind === "pending-elsewhere" ? LOCK_SYMBOL : display.accepted ? "checkmark" : "minus"; + return ( + + + + {m(TITLE)} · {display.label} + + + ); +} + +function PendingHandoffRequest(props: { + readonly environmentId: EnvironmentId; + readonly item: HandoffRequestItem; +}) { + const gt = useGT(); + const m = useMessages(); + const { item } = props; + const canMove = useCanMoveThreads(props.environmentId); + const targets = useEnvironmentQuery( + threadHandoffEnvironment.options({ + environmentId: props.environmentId, + input: { threadId: item.threadId }, + }), + ); + const start = useAtomCommand(threadHandoffEnvironment.start, { reportFailure: false }); + const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false }); + const link = useAtomCommand(peerLinkEnvironment.link, { + // The failure cause holds the request, and with it the code; keep it out of the logs. + reportFailure: false, + reportDefect: false, + }); + const [picked, setPicked] = useState(null); + const [access, setAccess] = useState(HANDOFF_LINK_DEFAULT_ACCESS); + const [busy, setBusy] = useState<"move" | "decline" | null>(null); + const [error, setError] = useState(null); + // Two taps can land before a re-render; this guard is synchronous. + const inFlight = useRef(false); + // A message in the outbox exists only on this device, and a moved thread refuses it. + const outboxWaiting = useQueuedThreadKeys().has( + scopedThreadKey(props.environmentId, item.threadId), + ); + const options = targets.data?.options ?? []; + // Machines this client is connected to that the thread's environment has no link to yet. + // Linking is changed on this thread's machine too, which this session may not be allowed to. + const mayLinkHere = useAtomValue(peerLinkEnvironment.link.permissionAtom(props.environmentId)); + const linkable = handoffLinkCandidates(useLinkableMachines(props.environmentId, true)).filter( + (machine) => + mayLinkHere && !options.some((option) => option.environmentId === machine.environmentId), + ); + const pickedLinkable = linkable.find((machine) => machine.environmentId === picked); + // This device creates the link's code there, which its session must be allowed to. + const mayLink = useEnvironmentScope(pickedLinkable?.environmentId ?? null, AuthAccessWriteScope); + const toLink = mayLink ? pickedLinkable : undefined; + const chosen = + pickedLinkable === undefined + ? handoffRequestTarget(options, picked ?? item.environmentId) + : undefined; + const move = (environmentId: EnvironmentId) => + start({ + environmentId: props.environmentId, + input: { threadId: item.threadId, environmentId, turnItemId: item.id }, + }); + + const answer = async ( + key: "move" | "decline", + send: () => ReturnType | ReturnType, + ) => { + if (inFlight.current) return; + inFlight.current = true; + setBusy(key); + setError(null); + const result = await send().finally(() => { + inFlight.current = false; + setBusy(null); + }); + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + const failure = squashAtomCommandFailure(result); + setError(failure instanceof Error ? failure.message : gt("The thread could not be moved.")); + }; + + /** Links the thread's environment to `machine`; resolves to what went wrong, or null. */ + const linkTo = async (machine: LinkableMachine): Promise => { + const [url, ...alternateUrls] = machine.urls; + if (url === undefined) return "interrupted"; + const code = await mintPairingCodeOn(machine.environmentId, access); + if (Result.isFailure(code)) return code.failure; + const linked = await link({ + environmentId: props.environmentId, + input: { + url, + ...(alternateUrls.length === 0 ? {} : { alternateUrls }), + pairingCode: code.success, + access, + expectedEnvironmentId: machine.environmentId, + expectedLabel: machine.label, + }, + }); + if (linked._tag !== "Failure") return null; + return isAtomCommandInterrupted(linked) ? "interrupted" : squashAtomCommandFailure(linked); + }; + + /** Links to a machine this client is connected to, then moves the thread there. */ + const linkAndMove = async (machine: LinkableMachine) => { + if (inFlight.current) return; + inFlight.current = true; + setBusy("move"); + setError(null); + const failure = await linkTo(machine); + inFlight.current = false; + setBusy(null); + if (failure !== null) { + if (failure !== "interrupted") setError(linkRequestFailureMessage(failure, m)); + return; + } + // Linking took a while; a message queued here meanwhile would be stranded by the move. + if (threadHasQueuedMessages(scopedThreadKey(props.environmentId, item.threadId))) return; + targets.refresh(); + await answer("move", () => move(machine.environmentId)); + }; + + return ( + + + + Move this thread to another machine? + + + {outboxWaiting + ? gt("A message is still waiting to send from this device. Send or discard it first.") + : targets.data === null + ? (targets.error ?? gt("Asking linked machines…")) + : options.length === 0 && linkable.length === 0 + ? gt("This machine has no linked machines.") + : gt( + "It moves with its conversation and its code, uncommitted changes included. This copy becomes read-only.", + )} + + + {error !== null ? ( + + {error} + + ) : !canMove ? ( + + Only someone who can run agents on this machine can move it or decline. + + ) : null} + {options.length > 0 || linkable.length > 0 ? ( + + {options.map((option, index) => ( + 0} + disabled={busy !== null || option.reason !== null || !canMove} + onPress={() => setPicked(option.environmentId)} + /> + ))} + {linkable.map((machine, index) => ( + 0} + disabled={busy !== null || !canMove} + onPress={() => setPicked(machine.environmentId)} + /> + ))} + + ) : null} + {pickedLinkable !== undefined && !mayLink ? ( + + {gt( + "This device may not create a link on {machine}. Link it from Settings on a device that can.", + { machine: pickedLinkable.label }, + )} + + ) : null} + {toLink !== undefined ? ( + <> + + {gt( + "This machine is not linked to {machine} yet. Moving the thread links them first, with a code this device creates there. Choose what agents here may do there.", + { machine: toLink.label }, + )} + + + {LINK_ACCESS_CHOICES.map((choice, index) => ( + 0} + disabled={busy !== null} + onPress={() => setAccess(choice.access)} + /> + ))} + + + ) : null} + + + + + ); +} diff --git a/apps/web/src/components/chat/LinkedThreadPage.tsx b/apps/web/src/components/chat/LinkedThreadPage.tsx index 0749f199083ee..e47b97b667d8e 100644 --- a/apps/web/src/components/chat/LinkedThreadPage.tsx +++ b/apps/web/src/components/chat/LinkedThreadPage.tsx @@ -21,6 +21,8 @@ export function LinkedThreadPage(props: { readonly viaEnvironmentId: EnvironmentId; readonly environmentId: EnvironmentId; readonly threadId: ThreadId; + /** Pair with the thread's environment at once instead of waiting for "Connect to interact". */ + readonly autoConnect?: boolean; }) { const { viaEnvironmentId, environmentId, threadId } = props; const gt = useGT(); @@ -52,6 +54,7 @@ export function LinkedThreadPage(props: { panelRef={null} surface={surface} visible + autoConnect={props.autoConnect === true} renderHeader={(title) => ( diff --git a/apps/web/src/components/chat/LinkedThreadPane.tsx b/apps/web/src/components/chat/LinkedThreadPane.tsx index 798ef2c80e405..1347d239907bf 100644 --- a/apps/web/src/components/chat/LinkedThreadPane.tsx +++ b/apps/web/src/components/chat/LinkedThreadPane.tsx @@ -2,7 +2,7 @@ import { isLinkedThreadWorking, linkedThreadFailure } from "@t3tools/client-runt import type { ScopedThreadRef } from "@t3tools/contracts"; import { T, useGT, useMessages, Var } from "gt-react"; import { EyeIcon, PlugIcon } from "lucide-react"; -import { useState, type ReactNode } from "react"; +import { useEffect, useEffectEvent, useState, type ReactNode } from "react"; import { useStableCallback } from "../../hooks/useStableCallback"; import { type LinkedThreadSurface, linkedThreadTitle } from "../../linkedThreadSurface"; @@ -67,6 +67,9 @@ function LinkedThreadComposer(props: { ); } +/** Environments an unasked connect was tried for; a failed one waits for the button after that. */ +const autoConnectTried = new Set(); + const NO_ATTACHMENT_URLS: ReadonlyMap = new Map(); const noAttachmentUrls = () => NO_ATTACHMENT_URLS; const ignore = () => {}; @@ -84,6 +87,8 @@ export function LinkedThread(props: { readonly visible: boolean; /** What sits above the timeline on the main screen; a tab already names the thread. */ readonly renderHeader?: (title: string) => ReactNode; + /** Connect once without being asked; what it cannot do alone is left to the button. */ + readonly autoConnect?: boolean; }) { const { surface, panelRef } = props; const gt = useGT(); @@ -96,6 +101,13 @@ export function LinkedThread(props: { const connection = useConnectLinkedEnvironment(panelRef, surface); const connectState = connection.state; const connecting = connectState.phase === "connecting"; + const autoConnect = useEffectEvent(() => { + if (props.autoConnect !== true || autoConnectTried.has(surface.environmentId)) return; + autoConnectTried.add(surface.environmentId); + void connection.connect({ unasked: true }); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pairing starts a network exchange with another machine, once when a moved thread opens + useEffect(() => autoConnect(), []); const connect = async () => { const outcome = await connection.connect(); if (outcome.type === "connected") { diff --git a/apps/web/src/components/chat/ThreadHandoffBanner.tsx b/apps/web/src/components/chat/ThreadHandoffBanner.tsx new file mode 100644 index 0000000000000..ec258d47ca582 --- /dev/null +++ b/apps/web/src/components/chat/ThreadHandoffBanner.tsx @@ -0,0 +1,249 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + threadAwaitsAdoption, + threadHandoffClosesComposer, +} from "@t3tools/client-runtime/state/peerLinks"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { Navigate, useNavigate } from "@tanstack/react-router"; +import { msg, useGT } from "gt-react"; +import { ArrowUpRightIcon, MonitorUpIcon, TriangleAlertIcon } from "lucide-react"; +import { useState } from "react"; + +import { m, type MessageResolver } from "~/i18n/messages"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { useConnectedEnvironmentIds } from "~/state/environments"; +import { + canMoveThreadsAtom, + dismissedThreadHandoffsAtom, + openThreadHandoffDialog, + threadHandoffEnvironment, +} from "~/state/threadHandoff"; +import { useAtomCommand } from "~/state/use-atom-command"; +import { linkedThreadRouteParams } from "../../linkedThreadSurface"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { Button } from "../ui/button"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import type { ComposerBannerStackItem } from "./ComposerBannerStack"; + +type HandoffShell = Pick & { + readonly linkOrigin?: EnvironmentThreadShell["linkOrigin"]; +}; + +/** Why the composer is closed while a thread moves away, or null when it is open. */ +export function threadHandoffSendBlockReason( + shell: Pick | null | undefined, + resolve: MessageResolver = m, +): string | null { + const handoff = shell?.handoff; + if (!threadHandoffClosesComposer(handoff)) return null; + return handoff.state === "departing" + ? resolve(msg("Moving to {machine}", { machine: handoff.label })) + : resolve(msg("Continues on {machine}", { machine: handoff.label })); +} + +/** + * Takes the client to where a moved thread continues, so the conversation reads as one thread: + * its own connection to that machine when it has one, else a view over the link that pairs + * with the machine by itself. + */ +export function ThreadHandoffFollower({ + shell, +}: { + readonly shell: HandoffShell | null | undefined; +}) { + const connected = useConnectedEnvironmentIds(); + const handoff = shell?.handoff; + if (shell == null || handoff?.state !== "departed") return null; + const there = scopeThreadRef(handoff.environmentId, handoff.threadId); + return connected.includes(handoff.environmentId) ? ( + + ) : ( + + ); +} + +/** + * The notice for a thread's move to a linked machine: waiting (with a way to keep it here), + * under way, moved (with a way to open it there), or failed (with a way to try again). + */ +export function useThreadHandoffBannerItem( + shell: HandoffShell | null | undefined, +): ComposerBannerStackItem | null { + const gt = useGT(); + const navigate = useNavigate(); + const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false }); + const adopt = useAtomCommand(threadHandoffEnvironment.adopt, { reportFailure: false }); + const [adopting, setAdopting] = useState(false); + const [cancelling, setCancelling] = useState(false); + const connected = useConnectedEnvironmentIds(); + const dismissed = useAtomValue(dismissedThreadHandoffsAtom); + const canMove = useAtomValue( + canMoveThreadsAtom(shell?.environmentId ?? ("" as HandoffShell["environmentId"])), + ); + // Adopting is local to this machine, so it does not need linked environments switched on. + const canAdopt = useAtomValue( + threadHandoffEnvironment.adopt.permissionAtom(shell?.environmentId ?? null), + ); + const handoff = shell?.handoff ?? null; + if (shell != null && handoff === null && threadAwaitsAdoption(shell)) { + const origin = shell.linkOrigin?.label ?? ""; + return { + id: `thread-handoff:${shell.id}:adopt`, + variant: "info", + icon: , + title: gt("This thread was moved here over a limited link"), + description: gt( + "Its agent can change only what {origin} started here and cannot use this machine's links, until you make it a normal thread.", + { origin }, + ), + ...(canAdopt + ? { + actions: ( + + ), + } + : {}), + }; + } + if (shell == null || handoff === null) return null; + const id = `thread-handoff:${shell.id}:${handoff.handoffId}:${handoff.state}`; + const icon = ; + const machine = handoff.label; + switch (handoff.state) { + case "pending": + return { + id, + variant: "info", + icon, + title: gt("Moving to {machine} when this turn ends", { machine }), + description: gt("Sending a message keeps it here instead."), + actions: ( + + ), + }; + case "departing": + return { id, variant: "info", icon, title: gt("Moving to {machine}…", { machine }) }; + case "departed": { + const there = scopeThreadRef(handoff.environmentId, handoff.threadId); + return { + id, + variant: "info", + icon, + title: gt("This thread continues on {machine}", { machine }), + description: gt("This copy is read-only."), + actions: ( + + ), + }; + } + case "failed": + if (dismissed.has(handoff.handoffId)) return null; + return { + id, + variant: "error", + icon: , + title: gt("Could not move to {machine}", { machine }), + description: handoff.lastError, + ...(canMove + ? { + actions: ( + + ), + } + : {}), + dismissLabel: gt("Dismiss"), + onDismiss: () => + appAtomRegistry.set( + dismissedThreadHandoffsAtom, + new Set([...dismissed, handoff.handoffId]), + ), + }; + } +} diff --git a/apps/web/src/components/chat/ThreadHandoffDialog.tsx b/apps/web/src/components/chat/ThreadHandoffDialog.tsx new file mode 100644 index 0000000000000..d1f0cb7cff4a3 --- /dev/null +++ b/apps/web/src/components/chat/ThreadHandoffDialog.tsx @@ -0,0 +1,168 @@ +import { useAtomValue } from "@effect/atom-react"; +import { defaultHandoffTarget } from "@t3tools/client-runtime/state/peerLinks"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; +import { Link } from "@tanstack/react-router"; +import { T, useGT, Var } from "gt-react"; +import { useState } from "react"; + +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { useEnvironmentMachines } from "~/state/environments"; +import { useEnvironmentQuery } from "~/state/query"; +import { threadHandoffDialogThreadAtom, threadHandoffEnvironment } from "~/state/threadHandoff"; +import { useAtomCommand } from "~/state/use-atom-command"; +import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Radio, RadioGroup } from "../ui/radio-group"; +import { Spinner } from "../ui/spinner"; +import { stackedThreadToast, toastManager } from "../ui/toast"; + +export function ThreadHandoffDialogHost() { + const threadRef = useAtomValue(threadHandoffDialogThreadAtom); + if (threadRef === null) return null; + return ( + appAtomRegistry.set(threadHandoffDialogThreadAtom, null)} + /> + ); +} + +function ThreadHandoffDialog({ + threadRef, + onClose, +}: { + readonly threadRef: ScopedThreadRef; + readonly onClose: () => void; +}) { + const gt = useGT(); + const machines = useEnvironmentMachines(); + const targets = useEnvironmentQuery( + threadHandoffEnvironment.options({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }), + ); + const start = useAtomCommand(threadHandoffEnvironment.start, { reportFailure: false }); + const [picked, setPicked] = useState(null); + const options = targets.data?.options ?? []; + const chosen = defaultHandoffTarget(options, picked); + + // The move outlasts the dialog: the thread's own notice shows how it goes. + const move = () => { + if (chosen === undefined) return; + onClose(); + void start({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, environmentId: chosen.environmentId }, + }).then((result) => { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Could not move the thread to {machine}", { machine: chosen.label }), + ...(error instanceof Error ? { description: error.message } : {}), + }), + ); + }); + }; + + return ( + { + if (!open) onClose(); + }} + > + + + + Continue on another machine + + + + The thread moves with its conversation and its code, including commits you have not + pushed and uncommitted changes. This copy becomes read-only. + + + + + {targets.data === null && targets.error === null ? ( +

+ + Asking linked machines… +

+ ) : targets.data === null ? ( +

+ {targets.error} +

+ ) : options.length === 0 ? ( +

+ {gt("This machine has no linked machines.")}{" "} + + {gt("Link one in Settings")} + +

+ ) : ( + setPicked(value as EnvironmentId)} + > + {options.map((option) => ( + + ))} + + )} +
+ + + + +
+
+ ); +} diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 4ec0b9e898237..5285870e294ba 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -6,6 +6,7 @@ import { T, useGT, useMessages, Var } from "gt-react"; import { findRevealRef } from "./markdownFindContext"; import { type EnvironmentId, + isThreadMoveMessage, type MessageId, type ScheduledTaskId, type ServerProviderSkill, @@ -15,7 +16,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { Link } from "@tanstack/react-router"; import { useQuietThreadShell } from "../../state/entities"; -import { useEnvironment } from "../../state/environments"; +import { useEnvironment, useEnvironmentMachines } from "../../state/environments"; +import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; @@ -32,17 +34,20 @@ import { } from "../../types"; import ChatMarkdown from "../ChatMarkdown"; import { + ArrowRightIcon, CalendarClockIcon, ChevronDownIcon, DownloadIcon, EyeIcon, type LucideIcon, MessagesSquareIcon, + MonitorUpIcon, Redo2Icon, PencilIcon, LinkIcon, } from "lucide-react"; import { Button, InlineButton } from "../ui/button"; +import { TimelineSystemDivider } from "./TimelineSystemDivider"; import { FreshSessionRow, ModelSwitchRow } from "./V2LifecycleRow"; import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls"; import { AttachmentImage } from "../media/AttachmentImage"; @@ -289,6 +294,11 @@ function UserMessageContent({ row }: { row: Extract + ) : isThreadMoveMessage(row.message) ? ( + ) : resolveUserMessagePresentation(row.message).attribution === "automation" ? ( ) : ( @@ -296,6 +306,49 @@ function UserMessageContent({ row }: { row: Extract) => ( + + + {environment.label} + + ); + const arrives = to !== null && to.environmentId !== from?.environmentId ? to : null; + return ( + + {from === null ? gt("from another machine") : endpoint(from)} + {arrives !== null ? ( + <> +