diff --git a/.github/pr-screenshots/2500/add-dark.png b/.github/pr-screenshots/2500/add-dark.png new file mode 100644 index 0000000000..2097cf4300 Binary files /dev/null and b/.github/pr-screenshots/2500/add-dark.png differ diff --git a/.github/pr-screenshots/2500/add-light.png b/.github/pr-screenshots/2500/add-light.png new file mode 100644 index 0000000000..f595565ed7 Binary files /dev/null and b/.github/pr-screenshots/2500/add-light.png differ diff --git a/.github/pr-screenshots/2500/all-dark.png b/.github/pr-screenshots/2500/all-dark.png new file mode 100644 index 0000000000..5ea5246be1 Binary files /dev/null and b/.github/pr-screenshots/2500/all-dark.png differ diff --git a/.github/pr-screenshots/2500/all-light.png b/.github/pr-screenshots/2500/all-light.png new file mode 100644 index 0000000000..caeb535eaf Binary files /dev/null and b/.github/pr-screenshots/2500/all-light.png differ diff --git a/.github/pr-screenshots/2500/before-dark.png b/.github/pr-screenshots/2500/before-dark.png new file mode 100644 index 0000000000..bcf1d4aad6 Binary files /dev/null and b/.github/pr-screenshots/2500/before-dark.png differ diff --git a/.github/pr-screenshots/2500/before-light.png b/.github/pr-screenshots/2500/before-light.png new file mode 100644 index 0000000000..54f0799ca7 Binary files /dev/null and b/.github/pr-screenshots/2500/before-light.png differ diff --git a/.github/pr-screenshots/2500/chat-dark.png b/.github/pr-screenshots/2500/chat-dark.png new file mode 100644 index 0000000000..988a019011 Binary files /dev/null and b/.github/pr-screenshots/2500/chat-dark.png differ diff --git a/.github/pr-screenshots/2500/chat-light.png b/.github/pr-screenshots/2500/chat-light.png new file mode 100644 index 0000000000..7d617e10ab Binary files /dev/null and b/.github/pr-screenshots/2500/chat-light.png differ diff --git a/.github/pr-screenshots/2500/tab-dark.png b/.github/pr-screenshots/2500/tab-dark.png new file mode 100644 index 0000000000..8ea0583656 Binary files /dev/null and b/.github/pr-screenshots/2500/tab-dark.png differ diff --git a/.github/pr-screenshots/2500/tab-light.png b/.github/pr-screenshots/2500/tab-light.png new file mode 100644 index 0000000000..ce41e3ef24 Binary files /dev/null and b/.github/pr-screenshots/2500/tab-light.png differ diff --git a/changes/2500-computer-tabs.md b/changes/2500-computer-tabs.md new file mode 100644 index 0000000000..9e5337d396 --- /dev/null +++ b/changes/2500-computer-tabs.md @@ -0,0 +1,11 @@ +--- +section: Added +--- + +## en + +- The channel list has Computer tabs: **All** (the default), **This computer**, and one tab per other Computer. **Add computer** takes the pairing link from another Computer's Settings → Devices → Pair a phone, so a browser can list, open and answer that Computer's chats over Tailscale. Right-click a Computer's tab to remove it ([#2500](https://github.com/BotHarness/DeepSeekBot/issues/2500)). + +## zh + +- 频道列表加了电脑 tabs:**全部**(默认)、**这台电脑**,以及每台其他电脑各一个。**添加电脑**里粘贴另一台电脑「设置 → 设备 → 配对手机」的配对链接,浏览器就能通过 Tailscale 列出、打开并回复那台电脑的聊天。右键电脑的 tab 可以移除它([#2500](https://github.com/BotHarness/DeepSeekBot/issues/2500))。 diff --git a/docs/adr/0242-a-browser-pairs-other-computers-through-their-device-gateway.md b/docs/adr/0242-a-browser-pairs-other-computers-through-their-device-gateway.md new file mode 100644 index 0000000000..2ad0157215 --- /dev/null +++ b/docs/adr/0242-a-browser-pairs-other-computers-through-their-device-gateway.md @@ -0,0 +1,25 @@ +--- +Status: Accepted +Date: 2026-10-21 +Issues: [#2500](https://github.com/BotHarness/DeepSeekBot/issues/2500), [#2180](https://github.com/BotHarness/DeepSeekBot/issues/2180), [#2178](https://github.com/BotHarness/DeepSeekBot/issues/2178) +--- + +# A browser pairs other Computers through their device gateway + +The Web Client serves exactly one Host. The Human wants its channel list to work like the phone's (#2194): **All** by default, then one tab per Computer, with chats from another Computer on the tailnet listed, opened and answered in the same browser. Spec #2178 already fixes the authority split: each Computer owns its conversations, and a client's connections belong to that client (browser profile plus origin), never to a Host setting. + +We decided that **the browser pairs another Computer exactly like a phone does, and talks to it directly with that per-device credential.** The other Host admits the cross-origin calls on its device gateway (ADR-0199); the serving Host never relays or stores the credential. + +## Decision + +- **Same pairing, same credential.** The Human copies the pairing link from the other Computer's Settings → Devices → Pair a phone and pastes it into **Add computer** in the channel list. The browser redeems the offer at `/botharness-device/pair` and keeps the returned device record in `localStorage` of the serving origin. The other Computer lists it as one more paired device ("Browser on …") and can revoke it there. +- **CORS only for header-authenticated paths.** The gateway answers cross-origin `pair`, `unpair`, `stream-ticket` and unary `/botharness-device/api/*` requests, including the preflight, only when the `Origin` is itself a Host-shaped address (loopback, Tailscale HTTPS or the Connect domain, the same check as phone routes) and the request carries no cookie. The cookie-authenticated full Web Client (`/botharness-device/web/`) stays same-origin. Responses echo that origin with `Vary: Origin` and never allow credentials, so a page needs the device secret itself; ambient cookies never authorize a cross-origin call. +- **Stream tickets.** Browsers cannot put an `Authorization` header on a WebSocket. The browser first `POST`s `/botharness-device/stream-ticket` with its credential and opens `/botharness-device/api/remote.mux?ticket=…`. A ticket is random, stored only as a hash, bound to the device, valid for 30 seconds and spent on first use; the device is checked again when it is used, so revocation still closes streams and refuses new ones. Phones keep the header form. +- **One client implementation.** The Web Client reuses the phone's Host client, pairing and conversation modules (`apps/mobile/src/host/`) behind a browser carrier, so wire handling, reconnects, drafts and sends stay one code path. +- **Source-scoped state.** Conversations are keyed by Computer and conversation, so the same Bot slug or Channel ID on two Computers never shares a draft, history or send. Removing a Computer revokes this browser there and drops its cached conversations. + +## Consequences + +- The first slice shows each other Computer as its own section under All and as its own tab; it does not merge them into one recency-sorted list, show images or cards, or sync read state. Those follow in later #2180 slices. +- The Computer look (icon and colour) is still stored per phone, so the Web Client uses a generic computer icon. +- DSH Desktop is not qualified by this slice; its storage and origin rules are verified separately (#2180). diff --git a/packages/client/src/client/bot-sidebar.tsx b/packages/client/src/client/bot-sidebar.tsx index 24d5bc556c..6e90768196 100644 --- a/packages/client/src/client/bot-sidebar.tsx +++ b/packages/client/src/client/bot-sidebar.tsx @@ -1,4 +1,12 @@ import { Menu } from './appearance-primitives.js'; +import { ALL_COMPUTERS, computerSources } from './computer-sources.js'; +import { useChannelDockActive } from './channel-dock.js'; +import { + ComputerSourceMark, + ComputerTabs, + RemoteComputerRows, + useComputerSources, +} from './computer-tabs.js'; import { plainMarkdown } from '../../../core/src/channels/message-preview.js'; import { PointerMenu } from './ds/pointer-menu.js'; import { PanelEmptyState } from './ds/empty-state.js'; @@ -592,6 +600,7 @@ function BotRow({ onMenu, onPinDragStart, onPinDragEnd, + source = false, t, }: { bot: BotSummary; @@ -609,6 +618,7 @@ function BotRow({ onMenu: (request: ChannelMenuRequest) => void; onPinDragStart: (channelId: string) => void; onPinDragEnd: () => void; + source?: boolean; t: BotHarnessTranslate; }): ReactElement { const now = useMinuteNow(); @@ -694,6 +704,7 @@ function BotRow({ {bot.displayName} + {source ? : null} {muted ? : null} @@ -726,6 +737,7 @@ function ChannelRow({ onMenu, onPinDragStart, onPinDragEnd, + source = false, t, }: { channel: ChannelSummary; @@ -742,6 +754,7 @@ function ChannelRow({ onMenu: (request: ChannelMenuRequest) => void; onPinDragStart?: ((channelId: string) => void) | undefined; onPinDragEnd?: (() => void) | undefined; + source?: boolean; t: BotHarnessTranslate; }): ReactElement { const now = useMinuteNow(); @@ -824,6 +837,7 @@ function ChannelRow({ {channel.name} + {source ? : null} {muted ? : null} @@ -1008,6 +1022,9 @@ export function BotSidebar({ t, }: SidebarProps): ReactElement { const state = useClientStore(keepClientState, rosterInputs); + const computerTabs = useChannelDockActive(); + const computers = useComputerSources(); + const remoteOpen = computerTabs && computers.open !== undefined; const channelUnread = state.humanInbox.channelUnread; const mutedChannelSet = new Set(state.roster.muted); const prefs = useBotModePrefs((value) => value); @@ -1316,9 +1333,13 @@ export function BotSidebar({ ? visibleChannelIds : [...railPinnedChannels, ...railChannels].map((channel) => channel.id); const shortcutIdsRef = useRef(shortcutIds); - const openConversationRef = useRef(onOpenConversation); + const openLocalConversation = (): void => { + computerSources().close(); + onOpenConversation?.(); + }; + const openConversationRef = useRef(openLocalConversation); shortcutIdsRef.current = shortcutIds; - openConversationRef.current = onOpenConversation; + openConversationRef.current = openLocalConversation; const navigationIdsRef = useRef([]); navigationIdsRef.current = [...railPinnedChannels, ...railChannels].map((channel) => channel.id); const dragActiveRef = useRef(false); @@ -1466,9 +1487,10 @@ export function BotSidebar({ }); const visibleCount = pinnedChannels.length + flatBlocks.reduce((total, block) => total + block.channels.length, 0); - const selectedBot = state.selection?.kind === 'bot' ? state.selection.slug : undefined; + const selectedBot = + !remoteOpen && state.selection?.kind === 'bot' ? state.selection.slug : undefined; const selectedChannel = - state.selection?.kind === 'channel' ? state.selection.channelId : undefined; + !remoteOpen && state.selection?.kind === 'channel' ? state.selection.channelId : undefined; const contextSection = state.roster.sections.find( (section) => section.id === sectionContextMenu?.sectionId, ); @@ -1823,7 +1845,7 @@ export function BotSidebar({ ), ); if (gesture !== 'plain') return; - onOpenConversation?.(); + openLocalConversation(); void (channel.botSlug === undefined ? actions.openChannel(channel.id) : actions.openBot(channel.botSlug)); @@ -1831,7 +1853,7 @@ export function BotSidebar({ const openQuickSwitcherEntry = ({ channel }: QuickSwitcherEntry): void => { setQuickSwitcherOpen(false); - onOpenConversation?.(); + openLocalConversation(); setChannelSelection((current) => selectChannels( reconcileChannelSelection(current, visibleChannelIds), @@ -1917,6 +1939,8 @@ export function BotSidebar({ useSectionDrag(commitSectionDrag); dragActiveRef.current = channelDragActive || sectionDragActive; + const showSource = + computerTabs && computers.tab === ALL_COMPUTERS && computers.computers.length > 0; const renderChannelRow = (channel: ChannelSummary, scopeId: ScopeId): ReactElement => { const drag = channelDragProps(scopeId, channel.id); const bot = channel.botSlug === undefined ? undefined : botBySlug.get(channel.botSlug); @@ -1941,12 +1965,14 @@ export function BotSidebar({ onMenu={openChannelMenu} onPinDragStart={(channelId) => startPinDrag(channelId, 'roster')} onPinDragEnd={endPinDrag} + source={showSource} /> ); } return ( ); + const remoteTab = computerTabs + ? computers.computers.find((computer) => computer.host.hostId === computers.tab) + : undefined; + if (remoteTab !== undefined) + return ( +
+ {headerTarget + ? createPortal({header}, headerTarget) + : header} + +
+ +
+
+ ); return (
{header}, headerTarget) : header} + {computerTabs ? : null} {state.status === 'loading' && state.bots.length === 0 ? ( ) : null} @@ -2811,6 +2859,18 @@ export function BotSidebar({
); })} + {computerTabs && computers.tab === ALL_COMPUTERS + ? computers.computers.map((computer) => ( + + )) + : null} {createRequest?.kind === 'bot' && createRequest.source === 'zip' ? ( { setHiddenManagerOpen(false); - onOpenConversation?.(); + openLocalConversation(); void actions.openChannel(channelId); }} onClose={() => { diff --git a/packages/client/src/client/channel-dock.tsx b/packages/client/src/client/channel-dock.tsx index 3c893e6da7..fa0385aeb6 100644 --- a/packages/client/src/client/channel-dock.tsx +++ b/packages/client/src/client/channel-dock.tsx @@ -1,4 +1,6 @@ import { mountWorkspaceChrome, updateWorkspaceChrome } from './workspace-chrome.js'; +import { useComputerSources } from './computer-tabs.js'; +import { RemoteConversationView } from './remote-conversation-view.js'; import { AppearancePanelHeader } from './appearance-panel-header.js'; import { AppearanceContext } from './appearance-context.js'; import { PanelAppearanceSettings } from './appearance-panel-settings.js'; @@ -325,6 +327,8 @@ function workspaceState(dock: DockContextValue, id: string): SubpanelState | und function ChannelBodyPanel(): ReactElement { const dock = useDock(); + const remote = useComputerSources().open; + if (remote !== undefined) return ; const panels: Record = { [MESSAGE_LEAF]: { label: dock.t('workspace.messages'), content: }, }; diff --git a/packages/client/src/client/computer-sources.ts b/packages/client/src/client/computer-sources.ts new file mode 100644 index 0000000000..1d95109206 --- /dev/null +++ b/packages/client/src/client/computer-sources.ts @@ -0,0 +1,301 @@ +import type { HostCarrier } from '../../../../apps/mobile/src/host/carrier.js'; +import { + createHostClient, + type HostClient, + type HostSnapshot, +} from '../../../../apps/mobile/src/host/client.js'; +import { + createConversation, + type Conversation, +} from '../../../../apps/mobile/src/host/conversation.js'; +import { parseSavedHost, type SavedHost } from '../../../../apps/mobile/src/host/hosts.js'; +import { + DEVICE_PREFIX, + parsePairingLink, + redeemPairing, + revokePairing, + type PairingRefusal, +} from '../../../../apps/mobile/src/host/pairing.js'; +import { store } from './store.js'; + +export const COMPUTERS_STORAGE_KEY = 'botharness.computers.v1'; +export const COMPUTER_TAB_STORAGE_KEY = 'botharness.computers.tab.v1'; +export const ALL_COMPUTERS = 'all'; +export const THIS_COMPUTER = 'local'; + +export interface RemoteConversationTarget { + hostId: string; + title: string; + botSlug?: string; + channelId?: string; +} + +export interface RemoteComputer { + host: SavedHost; + snapshot: HostSnapshot; +} + +export interface ComputerSourcesSnapshot { + computers: readonly RemoteComputer[]; + tab: string; + open?: RemoteConversationTarget; +} + +export type ComputerPairResult = + | { ok: true; host: SavedHost } + | { ok: false; code: PairingRefusal | 'already-paired' | 'this-computer' }; + +export interface ComputerSources { + getSnapshot(): ComputerSourcesSnapshot; + subscribe(listener: () => void): () => void; + pair(link: string, deviceName: string, localHostId?: string): Promise; + remove(hostId: string): Promise; + select(tab: string): void; + open(target: RemoteConversationTarget): void; + close(): void; + conversation(target: RemoteConversationTarget): Conversation | undefined; +} + +export interface ComputerStorage { + getItem(key: string): string | null; + setItem(key: string, value: string): void; + removeItem(key: string): void; +} + +export function conversationKey(target: RemoteConversationTarget): string { + return JSON.stringify([ + target.hostId, + target.channelId === undefined ? 'bot' : 'channel', + target.channelId ?? target.botSlug ?? '', + ]); +} + +function readHosts(storage: ComputerStorage | undefined): SavedHost[] { + try { + const value = JSON.parse(storage?.getItem(COMPUTERS_STORAGE_KEY) ?? '[]') as unknown; + return Array.isArray(value) ? value.flatMap((entry) => parseSavedHost(entry) ?? []) : []; + } catch { + return []; + } +} + +function readTab(storage: ComputerStorage | undefined): string { + try { + return storage?.getItem(COMPUTER_TAB_STORAGE_KEY) ?? ALL_COMPUTERS; + } catch { + return ALL_COMPUTERS; + } +} + +export function createComputerSources(options: { + storage?: ComputerStorage | undefined; + carrier: HostCarrier; +}): ComputerSources { + const { storage, carrier } = options; + const listeners = new Set<() => void>(); + const clients = new Map void }>(); + const conversations = new Map(); + let tab = readTab(storage); + let open: RemoteConversationTarget | undefined; + let snapshot: ComputerSourcesSnapshot = { computers: [], tab }; + + const publish = (): void => { + const computers = [...clients.values()].map(({ host, client }) => ({ + host, + snapshot: client.getSnapshot(), + })); + const known = tab === ALL_COMPUTERS || tab === THIS_COMPUTER || clients.has(tab); + snapshot = { + computers, + tab: known ? tab : ALL_COMPUTERS, + ...(open === undefined ? {} : { open }), + }; + for (const listener of listeners) listener(); + }; + + const save = (): void => { + try { + const hosts = [...clients.values()].map(({ host }) => host); + if (hosts.length === 0) storage?.removeItem(COMPUTERS_STORAGE_KEY); + else storage?.setItem(COMPUTERS_STORAGE_KEY, JSON.stringify(hosts)); + } catch {} + }; + + const attach = (host: SavedHost): void => { + const client = createHostClient({ routes: host.routes, credential: host.credential, carrier }); + const release = client.subscribe(publish); + clients.set(host.hostId, { host, client, release }); + if (listeners.size > 0) client.start(); + }; + + for (const host of readHosts(storage)) attach(host); + publish(); + + const forget = (hostId: string): void => { + const entry = clients.get(hostId); + if (entry === undefined) return; + entry.release(); + entry.client.stop(); + clients.delete(hostId); + for (const [key, conversation] of conversations) + if ((JSON.parse(key) as string[])[0] === hostId) { + conversation.stop(); + conversations.delete(key); + } + if (open?.hostId === hostId) open = undefined; + save(); + publish(); + }; + + return { + getSnapshot: () => snapshot, + subscribe(listener) { + if (listeners.size === 0) for (const { client } of clients.values()) client.start(); + listeners.add(listener); + return () => { + listeners.delete(listener); + if (listeners.size > 0) return; + for (const { client } of clients.values()) client.stop(); + }; + }, + async pair(link, deviceName, localHostId) { + const parsed = parsePairingLink(link); + if (!parsed.ok) return parsed; + if (parsed.payload.host.id === localHostId) return { ok: false, code: 'this-computer' }; + if (clients.has(parsed.payload.host.id)) return { ok: false, code: 'already-paired' }; + const redeemed = await redeemPairing({ payload: parsed.payload, deviceName, carrier }); + if (!redeemed.ok) return redeemed; + attach(redeemed.host); + save(); + tab = redeemed.host.hostId; + try { + storage?.setItem(COMPUTER_TAB_STORAGE_KEY, tab); + } catch {} + publish(); + return redeemed; + }, + async remove(hostId) { + const entry = clients.get(hostId); + if (entry === undefined) return; + forget(hostId); + await revokePairing({ host: entry.host, carrier }); + }, + select(next) { + tab = next; + try { + storage?.setItem(COMPUTER_TAB_STORAGE_KEY, next); + } catch {} + publish(); + }, + open(target) { + open = target; + publish(); + }, + close() { + if (open === undefined) return; + open = undefined; + publish(); + }, + conversation(target) { + const entry = clients.get(target.hostId); + if (entry === undefined) return undefined; + const key = conversationKey(target); + let conversation = conversations.get(key); + if (conversation === undefined) { + conversation = createConversation({ + host: entry.client, + displayName: target.title, + ...(target.botSlug === undefined ? {} : { botSlug: target.botSlug }), + ...(target.channelId === undefined ? {} : { channelId: target.channelId }), + }); + conversations.set(key, conversation); + } + return conversation; + }, + }; +} + +export function browserCarrier(): HostCarrier { + return { + async request(url, init) { + const response = await fetch(url, { + method: init.method, + signal: init.signal, + credentials: 'omit', + mode: 'cors', + headers: { + ...(typeof init.body === 'string' ? { 'content-type': 'application/json' } : {}), + ...init.headers, + }, + ...(init.body === undefined ? {} : { body: init.body }), + }); + return { status: response.status, text: () => response.text() }; + }, + openSocket(url, events, headers = {}) { + const controller = new AbortController(); + let socket: WebSocket | undefined; + let done = false; + const closed = (reason: string): void => { + if (done) return; + done = true; + events.closed(reason); + }; + void (async () => { + let ticket: unknown; + try { + const origin = new URL(url.replace(/^ws/u, 'http')).origin; + const response = await fetch(`${origin}${DEVICE_PREFIX}/stream-ticket`, { + method: 'POST', + credentials: 'omit', + mode: 'cors', + headers, + signal: controller.signal, + }); + ticket = ((await response.json()) as { ticket?: unknown }).ticket; + } catch { + return closed('The live connection could not start.'); + } + if (controller.signal.aborted) return closed('closed'); + if (typeof ticket !== 'string') return closed('The computer refused the live connection.'); + socket = new WebSocket(`${url}?ticket=${encodeURIComponent(ticket)}`); + socket.onopen = () => events.open(); + socket.onmessage = (event) => events.message(String(event.data)); + socket.onerror = () => closed('socket error'); + socket.onclose = (event) => closed(event.reason); + })(); + return { + send: (text) => socket?.send(text), + close: () => { + controller.abort(); + if (socket === undefined) closed('closed'); + else socket.close(); + }, + }; + }, + }; +} + +let shared: ComputerSources | undefined; + +export function computerSources(): ComputerSources { + if (shared !== undefined) return shared; + shared = createComputerSources({ + storage: (() => { + try { + return globalThis.localStorage; + } catch { + return undefined; + } + })(), + carrier: browserCarrier(), + }); + const sources = shared; + let selection = store.getSnapshot().selection; + store.subscribe(() => { + const next = store.getSnapshot().selection; + if (next === selection) return; + selection = next; + sources.close(); + }); + return sources; +} diff --git a/packages/client/src/client/computer-tabs.tsx b/packages/client/src/client/computer-tabs.tsx new file mode 100644 index 0000000000..e37cbae047 --- /dev/null +++ b/packages/client/src/client/computer-tabs.tsx @@ -0,0 +1,410 @@ +import { useState, useSyncExternalStore, type ReactElement } from 'react'; +import * as stylex from '@stylexjs/stylex'; + +import type { RemoteComputer, RemoteConversationTarget } from './computer-sources.js'; +import { ALL_COMPUTERS, computerSources, THIS_COMPUTER } from './computer-sources.js'; +import { ChannelSidebarIcon } from './channel-sidebar-icon.js'; +import { ConfirmDialog, FormDialog } from './ds/form-dialog.js'; +import { IconButton } from './ds/icon-button.js'; +import { TextField } from './ds/field.js'; +import { Tooltip } from './ds/tooltip.js'; +import { border, color, radius, size, space, text } from './ds/tokens.stylex.js'; +import type { BotHarnessKey, BotHarnessTranslate } from './locale.js'; + +const focusRing = { default: 'none', ':focus-visible': `${border.focus} solid ${color.accent}` }; + +const styles = stylex.create({ + strip: { + display: 'flex', + alignItems: 'center', + gap: space.x2, + minWidth: 0, + paddingBlock: space.x2, + paddingInline: space.x3, + }, + tabs: { + display: 'flex', + alignItems: 'center', + gap: space.x1, + flexGrow: 1, + minWidth: 0, + overflowX: 'auto', + scrollbarWidth: 'none', + }, + tab: { + display: 'inline-flex', + alignItems: 'center', + gap: space.x2, + flexShrink: 1, + minWidth: 0, + maxWidth: '160px', + height: size.icon, + paddingBlock: 0, + paddingInline: space.x3, + borderWidth: 0, + borderStyle: 'none', + borderRadius: radius.sm, + backgroundColor: { default: 'transparent', ':hover': color.hover }, + color: { default: color.subtle, ':hover': color.fg }, + fontFamily: 'inherit', + fontSize: text.bodySize, + lineHeight: text.bodyLine, + whiteSpace: 'nowrap', + cursor: 'pointer', + outline: focusRing, + outlineOffset: '-2px', + }, + selected: { + backgroundColor: { default: color.selected, ':hover': color.selected }, + color: { default: color.fg, ':hover': color.fg }, + }, + fixed: { flexShrink: 0 }, + offline: { opacity: 0.6 }, + icon: { display: 'inline-flex', flexShrink: 0 }, + label: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }, + status: { + margin: 0, + paddingBlock: space.x2, + paddingInline: space.x3, + color: color.subtle, + fontSize: text.metaSize, + lineHeight: text.metaLine, + }, +}); + +interface LocalComputer { + id?: string; + name?: string; +} + +let local: LocalComputer = {}; +let localRequested = false; +const localListeners = new Set<() => void>(); + +function subscribeLocal(listener: () => void): () => void { + localListeners.add(listener); + if (!localRequested) { + localRequested = true; + void fetch('./api/botharness/devices') + .then((response) => (response.ok ? response.json() : undefined)) + .then((value: { host?: { id?: unknown; name?: unknown } } | undefined) => { + const host = value?.host; + local = { + ...(typeof host?.id === 'string' ? { id: host.id } : {}), + ...(typeof host?.name === 'string' ? { name: host.name } : {}), + }; + for (const notify of localListeners) notify(); + }) + .catch(() => { + localRequested = false; + }); + } + return () => { + localListeners.delete(listener); + }; +} + +export function useLocalComputer(): LocalComputer { + return useSyncExternalStore( + subscribeLocal, + () => local, + () => local, + ); +} + +export function useComputerSources() { + const sources = computerSources(); + return useSyncExternalStore(sources.subscribe, sources.getSnapshot, sources.getSnapshot); +} + +export function ComputerSourceMark(): ReactElement { + return ( + + ); +} + +function online(computer: RemoteComputer): boolean { + return computer.snapshot.connection.status === 'connected'; +} + +export function ComputerTabs({ t }: { t: BotHarnessTranslate }): ReactElement { + const sources = computerSources(); + const snapshot = useComputerSources(); + const localComputer = useLocalComputer(); + const [adding, setAdding] = useState(false); + const [removing, setRemoving] = useState(undefined); + const tabs: { id: string; label: string; icon: string; offline?: boolean }[] = [ + { id: ALL_COMPUTERS, label: t('computers.all'), icon: 'messages-square' }, + { id: THIS_COMPUTER, label: localComputer.name ?? t('computers.this'), icon: 'monitor' }, + ...snapshot.computers.map((computer) => ({ + id: computer.host.hostId, + label: computer.host.hostName, + icon: 'monitor', + offline: !online(computer), + })), + ]; + const selectedRemote = snapshot.computers.find( + (computer) => computer.host.hostId === snapshot.tab, + ); + return ( + <> +
+
+ {tabs.map((tab) => { + const selected = tab.id === snapshot.tab; + return ( + + ); + })} +
+ + setAdding(true)} + > + + + +
+ {selectedRemote !== undefined && !online(selectedRemote) ? ( +

+ {selectedRemote.snapshot.connection.status === 'refused' + ? t('computers.refused', { name: selectedRemote.host.hostName }) + : t('computers.offline', { name: selectedRemote.host.hostName })} +

+ ) : null} + {adding ? ( + setAdding(false)} + t={t} + /> + ) : null} + {removing === undefined ? null : ( + setRemoving(undefined)} + onConfirm={() => { + void sources.remove(removing.host.hostId); + setRemoving(undefined); + }} + /> + )} + + ); +} + +const PAIR_ERRORS: Partial> = { + 'link-invalid': 'computers.error.link-invalid', + 'link-expired': 'computers.error.link-expired', + 'offer-invalid': 'computers.error.offer-invalid', + 'offer-expired': 'computers.error.offer-expired', + 'no-route': 'computers.error.no-route', + 'already-paired': 'computers.error.already-paired', + 'this-computer': 'computers.error.this-computer', +}; + +function AddComputerDialog({ + localId, + localName, + onClose, + t, +}: { + localId: string | undefined; + localName: string | undefined; + onClose: () => void; + t: BotHarnessTranslate; +}): ReactElement { + const [link, setLink] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(undefined); + const submit = (): void => { + setBusy(true); + setError(undefined); + void computerSources() + .pair(link, t('computers.deviceName', { name: localName ?? t('computers.this') }), localId) + .then((result) => { + setBusy(false); + if (result.ok) onClose(); + else setError(t(PAIR_ERRORS[result.code] ?? 'computers.error.unreachable')); + }); + }; + return ( + + + + ); +} + +function rows(computer: RemoteComputer): (RemoteConversationTarget & { + key: string; + icon: string; + preview?: string; + previewAt?: string; +})[] { + const roster = computer.snapshot.roster; + if (roster === undefined) return []; + const hostId = computer.host.hostId; + return [ + ...roster.bots.map((bot) => ({ + key: `bot:${bot.slug}`, + hostId, + title: bot.displayName, + botSlug: bot.slug, + icon: 'bot', + ...(bot.preview === undefined ? {} : { preview: bot.preview }), + ...(bot.previewAt === undefined ? {} : { previewAt: bot.previewAt }), + })), + ...roster.channels.map((channel) => ({ + key: `channel:${channel.id}`, + hostId, + title: channel.name, + channelId: channel.id, + icon: 'users', + ...(channel.preview === undefined ? {} : { preview: channel.preview }), + ...(channel.previewAt === undefined ? {} : { previewAt: channel.previewAt }), + })), + ].sort((a, b) => (b.previewAt ?? '').localeCompare(a.previewAt ?? '')); +} + +function sameTarget( + open: RemoteConversationTarget | undefined, + row: RemoteConversationTarget, +): boolean { + return ( + open !== undefined && + open.hostId === row.hostId && + open.botSlug === row.botSlug && + open.channelId === row.channelId + ); +} + +export function RemoteComputerRows({ + computer, + query, + showSource, + onOpen, + t, +}: { + computer: RemoteComputer; + query: string; + showSource: boolean; + onOpen?: (() => void) | undefined; + t: BotHarnessTranslate; +}): ReactElement | null { + const sources = computerSources(); + const open = useComputerSources().open; + const needle = query.trim().toLocaleLowerCase(); + const visible = rows(computer).filter( + (row) => needle.length === 0 || row.title.toLocaleLowerCase().includes(needle), + ); + if (visible.length === 0 && showSource) return null; + const list = ( +
+ {visible.map((row) => ( + + ))} +
+ ); + if (!showSource) return list; + return ( +
+
+ {computer.host.hostName} + {visible.length} +
+ {list} +
+ ); +} diff --git a/packages/client/src/client/locale.ts b/packages/client/src/client/locale.ts index b5037c97d1..1d493b717a 100644 --- a/packages/client/src/client/locale.ts +++ b/packages/client/src/client/locale.ts @@ -3907,6 +3907,35 @@ export const zh = { 'telemetry.notice.done': '知道了', 'telemetry.notice.close': '关闭', 'botSettings.section.devices': '设备', + 'computers.tabs': '电脑', + 'computers.all': '全部', + 'computers.this': '这台电脑', + 'computers.add': '添加电脑', + 'computers.add.description': + '在另一台电脑的「设置 → 设备 → 配对手机」里复制配对链接,粘贴到这里。两台电脑需要在同一个 Tailscale 网络里。', + 'computers.add.link': '配对链接', + 'computers.add.hint': '链接 10 分钟内有效,只能用一次。', + 'computers.add.submit': '添加', + 'computers.deviceName': '{name} 的浏览器', + 'computers.offline': '{name} 现在连不上', + 'computers.refused': '{name} 已移除这个浏览器,请重新添加', + 'computers.interrupted': '连接中断,正在重连', + 'computers.remove.title': '移除 {name}?', + 'computers.remove.description': '这个浏览器会断开这台电脑,它的聊天不再显示。之后可以重新添加。', + 'computers.remove.confirm': '移除', + 'computers.rowLabel': '{name},来自 {computer}', + 'computers.system': '系统', + 'computers.sendFailed': '没发出去', + 'computers.composer': '发消息给 {name}', + 'computers.send': '发送', + 'computers.error.link-invalid': '这不是有效的配对链接', + 'computers.error.link-expired': '链接已过期,请在那台电脑上重新生成', + 'computers.error.offer-invalid': '链接已用过或无效,请重新生成', + 'computers.error.offer-expired': '链接已过期,请在那台电脑上重新生成', + 'computers.error.no-route': '链接里没有能访问的地址', + 'computers.error.unreachable': '连不上那台电脑,请确认它开着并在同一个 Tailscale 网络里', + 'computers.error.already-paired': '这台电脑已经添加过了', + 'computers.error.this-computer': '这是当前这台电脑的链接', 'devices.pair.title': '配对手机', 'devices.pair.description': '用 DeepSeekBot App 扫码。二维码只能用一次,10 分钟后失效。', 'devices.pair.open': '配对手机', @@ -8213,6 +8242,37 @@ My relationship with you, established lore and topics to avoid: [fill in]. 'telemetry.notice.done': 'Got it', 'telemetry.notice.close': 'Close', 'botSettings.section.devices': 'Devices', + 'computers.tabs': 'Computers', + 'computers.all': 'All', + 'computers.this': 'This computer', + 'computers.add': 'Add computer', + 'computers.add.description': + 'On the other computer, copy the link from Settings → Devices → Pair a phone and paste it here. Both computers must be on the same Tailscale network.', + 'computers.add.link': 'Pairing link', + 'computers.add.hint': 'The link works once, for 10 minutes.', + 'computers.add.submit': 'Add', + 'computers.deviceName': 'Browser on {name}', + 'computers.offline': "Can't reach {name} right now", + 'computers.refused': '{name} removed this browser. Add it again.', + 'computers.interrupted': 'Connection lost. Reconnecting.', + 'computers.remove.title': 'Remove {name}?', + 'computers.remove.description': + 'This browser disconnects from that computer and its chats no longer show here. You can add it again later.', + 'computers.remove.confirm': 'Remove', + 'computers.rowLabel': '{name}, on {computer}', + 'computers.system': 'System', + 'computers.sendFailed': 'Not sent', + 'computers.composer': 'Message {name}', + 'computers.send': 'Send', + 'computers.error.link-invalid': "This isn't a pairing link", + 'computers.error.link-expired': 'The link expired. Make a new one on that computer.', + 'computers.error.offer-invalid': 'The link was already used. Make a new one.', + 'computers.error.offer-expired': 'The link expired. Make a new one on that computer.', + 'computers.error.no-route': 'The link has no address this browser can reach.', + 'computers.error.unreachable': + "Can't reach that computer. Check that it's on and on the same Tailscale network.", + 'computers.error.already-paired': 'That computer is already added.', + 'computers.error.this-computer': 'That link is for this computer.', 'devices.pair.title': 'Pair a phone', 'devices.pair.description': 'Scan a QR code with the DeepSeekBot app. The code works once and expires after 10 minutes.', diff --git a/packages/client/src/client/remote-conversation-view.tsx b/packages/client/src/client/remote-conversation-view.tsx new file mode 100644 index 0000000000..49f10daeca --- /dev/null +++ b/packages/client/src/client/remote-conversation-view.tsx @@ -0,0 +1,287 @@ +import { useMemo, useState, useSyncExternalStore, type ReactElement } from 'react'; +import * as stylex from '@stylexjs/stylex'; +import { Button, MarkdownText, type MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives'; + +import { + shownInChat, + type Conversation, + type ConversationMessage, + type ConversationSnapshot, +} from '../../../../apps/mobile/src/host/conversation.js'; +import { computerSources, type RemoteConversationTarget } from './computer-sources.js'; +import { useComputerSources } from './computer-tabs.js'; +import { ChannelSidebarIcon } from './channel-sidebar-icon.js'; +import { IconButton } from './ds/icon-button.js'; +import { border, color, radius, space, text } from './ds/tokens.stylex.js'; +import type { BotHarnessTranslate } from './locale.js'; + +const styles = stylex.create({ + root: { + display: 'flex', + flexDirection: 'column', + height: '100%', + minHeight: 0, + backgroundColor: color.base, + color: color.fg, + }, + header: { + display: 'flex', + alignItems: 'center', + gap: space.x3, + minHeight: 'var(--bh-channel-header-height, 48px)', + paddingInline: space.x4, + borderBottomWidth: border.hairline, + borderBottomStyle: 'solid', + borderBottomColor: color.divider, + }, + title: { + minWidth: 0, + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + fontSize: text.titleSize, + lineHeight: text.titleLine, + fontWeight: text.strong, + }, + source: { + display: 'inline-flex', + alignItems: 'center', + gap: space.x2, + flexShrink: 0, + color: color.subtle, + fontSize: text.metaSize, + lineHeight: text.metaLine, + }, + spacer: { flexGrow: 1 }, + timeline: { + display: 'flex', + flexDirection: 'column-reverse', + gap: space.x4, + flexGrow: 1, + minHeight: 0, + overflowY: 'auto', + paddingBlock: space.x5, + paddingInline: space.x5, + }, + message: { display: 'flex', flexDirection: 'column', gap: space.x1, minWidth: 0 }, + human: { alignItems: 'flex-end' }, + author: { color: color.subtle, fontSize: text.metaSize, lineHeight: text.metaLine }, + bubble: { + maxWidth: 'min(720px, 100%)', + paddingBlock: space.x3, + paddingInline: space.x4, + borderRadius: radius.md, + backgroundColor: color.elevated, + fontSize: text.bodySize, + lineHeight: text.bodyLine, + overflowWrap: 'anywhere', + }, + humanBubble: { backgroundColor: color.accentTint }, + failed: { color: color.danger, fontSize: text.metaSize, lineHeight: text.metaLine }, + status: { + margin: 0, + paddingInline: space.x5, + paddingBlock: space.x2, + color: color.subtle, + fontSize: text.metaSize, + lineHeight: text.metaLine, + }, + composer: { + display: 'flex', + alignItems: 'flex-end', + gap: space.x3, + paddingBlock: space.x4, + paddingInline: space.x5, + borderTopWidth: border.hairline, + borderTopStyle: 'solid', + borderTopColor: color.divider, + }, + input: { + flexGrow: 1, + minWidth: 0, + minHeight: '40px', + maxHeight: '200px', + resize: 'vertical', + boxSizing: 'border-box', + paddingBlock: space.x3, + paddingInline: space.x4, + borderWidth: border.hairline, + borderStyle: 'solid', + borderColor: color.border, + borderRadius: radius.md, + backgroundColor: color.surface, + color: color.fg, + fontFamily: 'inherit', + fontSize: text.bodySize, + lineHeight: text.bodyLine, + outline: { default: 'none', ':focus-visible': `${border.focus} solid ${color.accent}` }, + }, +}); + +const idle: ConversationSnapshot = { + status: 'opening', + messages: [], + drafts: [], + hasOlder: false, + loadingOlder: false, + fromCache: false, +}; + +function useConversation(conversation: Conversation | undefined): ConversationSnapshot { + const subscribe = useMemo( + () => + (listener: () => void): (() => void) => { + if (conversation === undefined) return () => {}; + const release = conversation.subscribe(listener); + conversation.start(); + return () => { + release(); + conversation.stop(); + }; + }, + [conversation], + ); + const read = (): ConversationSnapshot => conversation?.getSnapshot() ?? idle; + return useSyncExternalStore(subscribe, read, read); +} + +function authorName( + message: ConversationMessage, + bots: ReadonlyMap, + t: BotHarnessTranslate, +): string { + if (message.author === 'human') return t('rail.you'); + if (message.author === 'bot') return bots.get(message.bot ?? '') ?? message.bot ?? ''; + return t('computers.system'); +} + +export function RemoteConversationView({ + target, + t, +}: { + target: RemoteConversationTarget; + t: BotHarnessTranslate; +}): ReactElement { + const sources = computerSources(); + const computer = useComputerSources().computers.find( + (candidate) => candidate.host.hostId === target.hostId, + ); + const conversation = useMemo( + () => sources.conversation(target), + [sources, target.hostId, target.botSlug, target.channelId], + ); + const snapshot = useConversation(conversation); + const [draft, setDraft] = useState(''); + const labels = useMemo( + () => ({ + code: { copyLabel: t('message.code.copy'), copiedLabel: t('message.code.copied') }, + footnotes: t('message.footnotes'), + }), + [t], + ); + const bots = new Map( + (computer?.snapshot.roster?.bots ?? []).map((bot) => [bot.slug, bot.displayName]), + ); + const reachable = computer?.snapshot.connection.status === 'connected'; + const send = (): void => { + const body = draft.trim(); + if (body.length === 0 || conversation === undefined || !reachable) return; + conversation.send(body); + setDraft(''); + }; + const shown = snapshot.messages.filter(shownInChat); + return ( +
+
+ {target.title} + + + {computer?.host.hostName ?? ''} + + + sources.close()}> + + +
+ {!reachable ? ( +

+ {t('computers.offline', { name: computer?.host.hostName ?? '' })} +

+ ) : snapshot.status === 'interrupted' || snapshot.status === 'refused' ? ( +

+ {snapshot.reason ?? t('computers.interrupted')} +

+ ) : null} +
+ {snapshot.drafts.map((entry) => ( +
+ {bots.get(entry.botSlug) ?? entry.botSlug} +
+ +
+
+ ))} + {[...shown].reverse().map((message) => ( +
+ {authorName(message, bots, t)} +
+ attachment.name).join(', ') + } + streaming={false} + labels={labels} + /> +
+ {message.delivery === 'failed' ? ( + + {message.error ?? t('computers.sendFailed')} + + ) : null} +
+ ))} +
+
{ + event.preventDefault(); + send(); + }} + > +