import os from 'node:os' import { generateKeyPair, identityFingerprint } from '@dsh-remote/crypto' import MarkdownIt from 'markdown-it' import QRCode from 'qrcode' import WebSocket from 'ws' import * as vscode from 'vscode' import { RemoteConnection } from './remote.js' import { ServerApi } from './server-api.js' import type { ChatMessage, Credentials, DeviceIdentity, PendingApproval, RemoteHost, RemoteSession, RemoteWorkspace, SessionModels } from './types.js' const IDENTITY_KEY = 'dshRemote.identity.v1' const CREDENTIALS_KEY = 'dshRemote.credentials.v1' const TRUST_KEY = 'dshRemote.trustedHosts.v1' const markdown = new MarkdownIt({ html: false, linkify: true, breaks: true }) export async function activate(context: vscode.ExtensionContext): Promise { if (globalThis.WebSocket === undefined) Object.assign(globalThis, { WebSocket }) const controller = new Controller(context) const loginView = new LoginViewProvider(controller) context.subscriptions.push( vscode.window.registerTreeDataProvider('dshRemote.hosts', controller.explorerView), vscode.window.registerWebviewViewProvider('dshRemote.login', loginView), command('dshRemote.signIn', () => controller.signIn()), command('dshRemote.signOut', () => controller.signOut()), command('dshRemote.settings', () => controller.showSettings()), command('dshRemote.openSettings', () => controller.openSettings()), command('dshRemote.refresh', () => controller.refresh()), command('dshRemote.connect', (item?: HostItem) => controller.connect(item?.host)), command('dshRemote.disconnect', () => controller.disconnect()), command('dshRemote.addWorkspace', (item?: HostItem) => controller.addWorkspace(item?.host)), command('dshRemote.newSession', (item?: WorkspaceItem) => controller.newSession(item?.workspace)), command('dshRemote.openSession', (item?: SessionItem) => controller.openSession(item?.session)), { dispose: () => void controller.disconnect() }, ) await controller.restore() } export function deactivate(): void {} function command(id: string, run: (...args: any[]) => Promise): vscode.Disposable { return vscode.commands.registerCommand(id, (...args) => run(...args).catch(error => void vscode.window.showErrorMessage(error instanceof Error ? error.message : String(error)))) } export class Controller { readonly explorerView = new RemoteExplorerProvider(element => this.treeChildren(element)) private identity?: DeviceIdentity private credentials?: Credentials private hosts: RemoteHost[] = [] private sessions: RemoteSession[] = [] private workspaces: RemoteWorkspace[] = [] private sessionPanel?: SessionPanel private signInTask?: Promise private refreshTask?: Promise private authEpoch = 0 constructor( private readonly context: vscode.ExtensionContext, private readonly connection: RemoteConnection = new RemoteConnection(), ) { const timer = setInterval(() => { if (this.credentials !== undefined) void this.refresh().catch(() => undefined) }, 15_000) const unsubscribeClose = this.connection.onClose(() => { void this.clearConnectionState().catch(error => { void vscode.window.showErrorMessage(error instanceof Error ? error.message : String(error)) }) }) context.subscriptions.push( { dispose: () => clearInterval(timer) }, { dispose: unsubscribeClose }, ) } async restore(): Promise { this.identity = await this.loadIdentity() const raw = await this.context.secrets.get(CREDENTIALS_KEY) if (raw) this.credentials = JSON.parse(raw) as Credentials await vscode.commands.executeCommand('setContext', 'dshRemote.signedIn', this.credentials !== undefined) if (this.credentials) await this.refresh().catch(() => undefined) } async signIn(): Promise { const serverUrl = vscode.workspace.getConfiguration('dshRemote').get('serverUrl', '').trim() if (!serverUrl) { await this.openSettings() void vscode.window.showInformationMessage('Set the DS Harness Remote server URL, then sign in.') return } const method = await vscode.window.showQuickPick([ { label: '$(account) Scan QR code', description: 'Sign in with Zhihu', value: 'qr' as const }, { label: '$(mail) Account and password', description: 'Sign in with email', value: 'password' as const }, ], { title: 'Sign in to DS Harness Remote' }) if (!method) return const api = new ServerApi(serverUrl) const login = method.value === 'qr' ? await this.signInWithQr(api) : await this.signInWithPassword(api) if (!login) return await this.completeSignIn(api, login) } async signInWithCredentials(serverUrl: string, email: string, password: string): Promise { const api = new ServerApi(serverUrl) const login = await api.login(email, password) await this.completeSignIn(api, login) } async startInlineQr(serverUrl: string): Promise<{ api: ServerApi; qrId: string; scanUrl: string }> { const api = new ServerApi(serverUrl) const session = await api.startQrLogin() return { api, qrId: session.qrId, scanUrl: session.scanUrl } } async pollInlineQr(api: ServerApi, qrId: string): Promise<'pending' | 'expired' | 'complete'> { const result = await api.pollQrLogin(qrId) if (result.status !== 'complete') return result.status await this.completeSignIn(api, result) return 'complete' } configuredServerUrl(): string { return vscode.workspace.getConfiguration('dshRemote').get('serverUrl', '') } private async completeSignIn(api: ServerApi, login: { token: string; account: string }): Promise { if (this.signInTask !== undefined) return this.signInTask const task = this.runCompleteSignIn(api, login) this.signInTask = task try { await task } finally { if (this.signInTask === task) this.signInTask = undefined } } private async runCompleteSignIn(api: ServerApi, login: { token: string; account: string }): Promise { const authEpoch = ++this.authEpoch const identity = this.identity ?? await this.loadIdentity() this.identity = identity const credentials = await api.authorizeClient(identity, login.token, login.account) if (authEpoch !== this.authEpoch) { await new ServerApi(credentials.serverUrl, credentials.accessToken).removeSelf().catch(() => undefined) return } this.credentials = credentials await this.context.secrets.store(CREDENTIALS_KEY, JSON.stringify(credentials)) if (authEpoch !== this.authEpoch) return await vscode.workspace.getConfiguration('dshRemote').update('serverUrl', api.baseUrl, vscode.ConfigurationTarget.Global) if (authEpoch !== this.authEpoch) return await vscode.commands.executeCommand('setContext', 'dshRemote.signedIn', true) if (authEpoch !== this.authEpoch) return await this.refresh() if (authEpoch !== this.authEpoch) return void vscode.window.showInformationMessage(`Signed in as ${login.account}.`) } private async signInWithPassword(api: ServerApi): Promise<{ token: string; account: string } | undefined> { const email = await vscode.window.showInputBox({ title: 'Account and password', prompt: 'Account email', ignoreFocusOut: true }) if (!email) return const password = await vscode.window.showInputBox({ title: 'Account and password', prompt: 'Password', password: true, ignoreFocusOut: true }) if (!password) return return vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Signing in to DS Harness Remote…' }, () => api.login(email, password)) } private async signInWithQr(api: ServerApi): Promise<{ token: string; account: string } | undefined> { const session = await api.startQrLogin() const svg = await QRCode.toString(session.scanUrl, { type: 'svg', width: 220, margin: 1, errorCorrectionLevel: 'L' }) const panel = vscode.window.createWebviewPanel('dshRemote.qrLogin', 'Scan to sign in', vscode.ViewColumn.Active, { enableScripts: false }) panel.webview.html = `

Scan with Zhihu

${svg}

Complete authorization on your phone. This page will close automatically.

` return new Promise((resolve, reject) => { let settled = false let polling = false const finish = (value?: { token: string; account: string }, error?: unknown): void => { if (settled) return settled = true clearInterval(timer) panel.dispose() error === undefined ? resolve(value) : reject(error) } const poll = async (): Promise => { if (settled || polling) return polling = true try { const result = await api.pollQrLogin(session.qrId) if (result.status === 'complete') finish({ token: result.token, account: result.account }) else if (result.status === 'expired') finish(undefined, new Error('The QR code expired. Please try again.')) } catch (error) { finish(undefined, error) } finally { polling = false } } const timer = setInterval(() => void poll(), 1_500) panel.onDidDispose(() => finish()) void poll() }) } async signOut(): Promise { const credentials = this.credentials const signInTask = this.signInTask const refreshTask = this.refreshTask this.authEpoch += 1 this.credentials = undefined await this.disconnect().catch(() => undefined) await signInTask?.catch(() => undefined) const refreshed = await refreshTask?.catch(() => undefined) if (refreshed !== undefined) { await new ServerApi(refreshed.serverUrl, refreshed.accessToken).removeSelf().catch(() => undefined) } else if (credentials !== undefined) { await this.revokeDevice(credentials).catch(() => undefined) } this.identity = undefined; this.hosts = []; this.sessions = []; this.workspaces = [] await this.context.secrets.delete(CREDENTIALS_KEY) await this.context.secrets.delete(IDENTITY_KEY) await vscode.commands.executeCommand('setContext', 'dshRemote.signedIn', false) this.fireViews() } async showSettings(): Promise { if (this.credentials === undefined) { await this.openSettings() return } const actions = [ { label: '$(gear) Open Settings', description: 'Configure the server and connection', action: 'settings' as const }, { label: '$(sign-out) Sign Out', description: this.credentials.account, action: 'signOut' as const }, ] const picked = await vscode.window.showQuickPick(actions, { title: 'DS Harness Remote' }) if (picked?.action === 'settings') await this.openSettings() if (picked?.action === 'signOut') { const confirmed = await vscode.window.showWarningMessage(`Sign out ${this.credentials?.account ?? ''}?`, { modal: true }, 'Sign Out') if (confirmed === 'Sign Out') await this.signOut() } } async openSettings(): Promise { await vscode.commands.executeCommand('workbench.action.openSettings', '@ext:deepseek-harness-remote.deepseek-harness-remote-vscode') } async refresh(): Promise { if (this.refreshTask !== undefined) { await this.refreshTask; return } const task = this.runRefresh() this.refreshTask = task try { await task } finally { if (this.refreshTask === task) this.refreshTask = undefined } } private async runRefresh(): Promise { const authEpoch = this.authEpoch let refreshed: Credentials | undefined let credentials = this.credentials if (!credentials) { this.fireViews(); return undefined } if (credentials.accessTokenExpiresAt <= Date.now() + 30_000) { credentials = await new ServerApi(credentials.serverUrl).refresh(credentials.deviceId, credentials.refreshToken, credentials.account) refreshed = credentials if (authEpoch !== this.authEpoch) return refreshed this.credentials = credentials await this.context.secrets.store(CREDENTIALS_KEY, JSON.stringify(credentials)) if (authEpoch !== this.authEpoch) return refreshed } const hosts = await vscode.window.withProgress({ location: { viewId: 'dshRemote.hosts' } }, () => new ServerApi(credentials.serverUrl, credentials.accessToken).hosts()) if (authEpoch !== this.authEpoch) return refreshed this.hosts = hosts if (this.connection.connectedHost) await this.loadHostContent() if (authEpoch !== this.authEpoch) return refreshed this.fireViews() return refreshed } async connect(host?: RemoteHost): Promise { if (!this.credentials || !this.identity) throw new Error('Sign in first.') if (!host) { const picked = await vscode.window.showQuickPick(this.hosts.map(item => ({ label: item.name, description: item.online ? 'online' : 'offline', host: item })), { title: 'Connect to Host' }) host = picked?.host } if (!host) return const trusted = this.context.globalState.get>(TRUST_KEY, {}) if (trusted[host.deviceId] !== host.identityKey) { const fingerprint = identityFingerprint(host.identityKey).match(/.{1,4}/g)?.join(' ') ?? identityFingerprint(host.identityKey) const choice = await vscode.window.showWarningMessage(`Trust “${host.name}”? Verify its identity fingerprint: ${fingerprint}`, { modal: true }, 'Trust and Connect') if (choice !== 'Trust and Connect') return await this.context.globalState.update(TRUST_KEY, { ...trusted, [host.deviceId]: host.identityKey }) } if (this.connection.connectedHost) await this.disconnect() await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Connecting to ${host.name}…` }, () => this.connection.connect(this.credentials!.serverUrl, this.identity!, host!, this.credentials!.accessToken, vscode.workspace.getConfiguration('dshRemote').get('forceRelay', false))) await this.loadHostContent() await vscode.commands.executeCommand('setContext', 'dshRemote.connected', true) this.fireViews() } async disconnect(): Promise { try { await this.connection.close() } finally { await this.clearConnectionState() } } async newSession(workspace?: RemoteWorkspace): Promise { if (!this.connection.connectedHost) throw new Error('Connect to a host first.') const cwd = workspace?.path ?? vscode.workspace.workspaceFolders?.[0]?.uri.fsPath const created = await this.connection.createSession(workspace ? { workspaceId: workspace.workspaceId } : { cwd }) await this.loadHostContent(); this.fireViews() const session = this.sessions.find(item => item.sessionId === created.sessionId) await this.openSession(session ?? { sessionId: created.sessionId, updatedAt: Date.now(), running: false, blank: true, cwd }) } async addWorkspace(host?: RemoteHost): Promise { if (host && this.connection.connectedHost?.deviceId !== host.deviceId) await this.connect(host) if (!this.connection.connectedHost) throw new Error('Connect to a host first.') let path: string | undefined while (true) { const directory = await this.connection.listDirectory(path) const choice = await vscode.window.showQuickPick([ { label: '$(check) Use this folder', description: directory.path, action: 'select' as const, path: directory.path }, ...directory.crumbs.slice(0, -1).reverse().slice(0, 1).map(item => ({ label: '$(arrow-up) Parent folder', description: item.path, action: 'browse' as const, path: item.path })), ...directory.entries.map(item => ({ label: `$(folder) ${item.name}`, description: item.path, action: 'browse' as const, path: item.path })), ], { title: 'Add remote workspace', placeHolder: directory.truncated ? 'Choose a folder (list truncated by Host)' : 'Choose a folder' }) if (!choice) return if (choice.action === 'browse') { path = choice.path; continue } await this.connection.createWorkspace(choice.path) await this.loadHostContent() this.fireViews() return } } async openSession(session?: RemoteSession): Promise { if (!session) return if (this.sessionPanel === undefined) { const panel = new SessionPanel(session, this.connection, () => this.loadHostContent().then(() => this.fireViews())) this.sessionPanel = panel panel.onDispose(() => { if (this.sessionPanel === panel) this.sessionPanel = undefined }) } await this.sessionPanel.open(session) } private async treeChildren(element?: RemoteTreeItem): Promise { if (!element) return this.hosts.map(host => new HostItem(host, this.connection.connectedHost?.deviceId === host.deviceId)) if (element instanceof HostItem) { if (this.connection.connectedHost?.deviceId !== element.host.deviceId) await this.connect(element.host) return this.workspaces.map(workspace => new WorkspaceItem(workspace)) } if (element instanceof WorkspaceItem) { const ids = new Set(element.workspace.sessionIds) return this.sessions.filter(session => ids.has(session.sessionId)).sort((a, b) => b.updatedAt - a.updatedAt).map(session => new SessionItem(session)) } return [] } private async loadHostContent(): Promise { [this.workspaces, this.sessions] = await Promise.all([this.connection.workspaces(), this.connection.sessions()]) } private async clearConnectionState(): Promise { this.sessions = [] this.workspaces = [] const panel = this.sessionPanel this.sessionPanel = undefined panel?.dispose() try { await vscode.commands.executeCommand('setContext', 'dshRemote.connected', false) } finally { this.fireViews() } } private async loadIdentity(): Promise { const stored = await this.context.secrets.get(IDENTITY_KEY) if (stored) return JSON.parse(stored) as DeviceIdentity const keys = generateKeyPair() const identity: DeviceIdentity = { deviceId: crypto.randomUUID(), name: `VS Code on ${os.hostname()}`, platform: 'vscode', ...keys } await this.context.secrets.store(IDENTITY_KEY, JSON.stringify(identity)) return identity } private async revokeDevice(credentials: Credentials): Promise { let accessToken = credentials.accessToken if (credentials.accessTokenExpiresAt <= Date.now() + 30_000) { const refreshed = await new ServerApi(credentials.serverUrl).refresh(credentials.deviceId, credentials.refreshToken, credentials.account) accessToken = refreshed.accessToken } await new ServerApi(credentials.serverUrl, accessToken).removeSelf() } private fireViews(): void { this.explorerView.fire() } } class LoginViewProvider implements vscode.WebviewViewProvider { private view?: vscode.WebviewView private qrRun = 0 private busy = false private error?: string private qrSvg?: string private activeTab: 'qr' | 'password' = 'qr' constructor(private readonly controller: Controller) {} resolveWebviewView(view: vscode.WebviewView): void { this.view = view view.webview.options = { enableScripts: true } view.webview.onDidReceiveMessage(message => { if (!isRecord(message)) return if (message.type === 'password' && typeof message.serverUrl === 'string' && typeof message.email === 'string' && typeof message.password === 'string') { void this.passwordLogin(message.serverUrl, message.email, message.password) } if (message.type === 'qr' && typeof message.serverUrl === 'string') void this.qrLogin(message.serverUrl) if (message.type === 'settings') void this.controller.openSettings() if (message.type === 'github') void vscode.env.openExternal(vscode.Uri.parse('https://github.com/liguobao/ds-harness-remote')) if (message.type === 'npm') void vscode.env.openExternal(vscode.Uri.parse('https://www.npmjs.com/package/ds-harness-remote')) if (message.type === 'tab' && (message.value === 'qr' || message.value === 'password')) this.activeTab = message.value }) view.onDidDispose(() => { this.qrRun += 1; this.view = undefined }) this.render() const serverUrl = this.controller.configuredServerUrl().trim() if (serverUrl.length > 0) void this.qrLogin(serverUrl) } private async passwordLogin(serverUrl: string, email: string, password: string): Promise { if (this.busy) return this.activeTab = 'password' this.busy = true; this.error = undefined; this.render() try { await this.controller.signInWithCredentials(serverUrl, email, password) } catch (error) { this.error = error instanceof Error ? error.message : String(error) } finally { this.busy = false; this.render() } } private async qrLogin(serverUrl: string): Promise { if (this.busy) return this.activeTab = 'qr' const run = ++this.qrRun this.busy = true; this.error = undefined; this.qrSvg = undefined; this.render() try { const session = await this.controller.startInlineQr(serverUrl) if (run !== this.qrRun) return this.qrSvg = await QRCode.toString(session.scanUrl, { type: 'svg', width: 188, margin: 1, errorCorrectionLevel: 'L' }) this.busy = false; this.render() while (run === this.qrRun) { await new Promise(resolve => setTimeout(resolve, 1_500)) if (run !== this.qrRun) return const status = await this.controller.pollInlineQr(session.api, session.qrId) if (status === 'complete') return if (status === 'expired') throw new Error('The QR code expired. Generate a new one.') } } catch (error) { if (run === this.qrRun) this.error = error instanceof Error ? error.message : String(error) } finally { if (run === this.qrRun) { this.busy = false; this.render() } } } private render(): void { const webview = this.view?.webview if (webview === undefined) return const nonce = crypto.randomUUID().replaceAll('-', '') const serverUrl = escapeHtml(this.controller.configuredServerUrl()) const passwordTab = this.activeTab === 'password' const copy = loginCopy() const status = this.error === undefined ? '' : `` const qr = this.qrSvg === undefined ? `` : `
${this.qrSvg}

${escapeHtml(copy.scanHint)}

` webview.html = `
DS Harness Remote

${escapeHtml(copy.overview)}

${escapeHtml(copy.requirementBefore)} ds-harness-remote ${escapeHtml(copy.requirementAfter)}


${qr}

${escapeHtml(copy.passwordHint)}

${status}` } } class SessionPanel { private readonly panel: vscode.WebviewPanel private readonly disposed = new vscode.EventEmitter() private busy = false private running: boolean private cancelling = false private approvals: PendingApproval[] = [] private readonly unsubscribeFrames: () => void private loaded = false private modelLabel = 'Model' private modelCatalog?: SessionModels private projectionValues: Record private closed = false constructor( private session: RemoteSession, private readonly connection: RemoteConnection, private readonly onChanged: () => Promise, ) { this.running = session.running this.projectionValues = { ...session.projections?.values } this.panel = vscode.window.createWebviewPanel( 'dshRemote.session', sessionTitle(session), { viewColumn: vscode.ViewColumn.Beside, preserveFocus: false }, { enableScripts: true, retainContextWhenHidden: true }, ) this.unsubscribeFrames = connection.onFrame(frame => { const payload = frame.payload if (payload.sessionId !== this.session.sessionId) return if (payload.type === 'session/event' && isRecord(payload.event)) { if (payload.event.type === 'turn/start') { this.running = true this.cancelling = false void this.show() } else if (payload.event.type === 'turn/end') { this.running = false this.cancelling = false void this.show() } } else if (payload.type === 'session/projection' && typeof payload.key === 'string') { this.projectionValues = { ...this.projectionValues, [payload.key]: payload.value } void this.show() } else if (payload.type === 'approval/requested' && typeof payload.approvalId === 'string') { this.approvals.push({ frameRpcId: frame.rpcId, sessionId: this.session.sessionId, approvalId: payload.approvalId, toolName: typeof payload.toolName === 'string' ? payload.toolName : 'Harness tool', ...(typeof payload.reason === 'string' ? { reason: payload.reason } : {}) }) void this.show() } else if (payload.type === 'approval/resolved' && typeof payload.approvalId === 'string') { this.approvals = this.approvals.filter(item => item.approvalId !== payload.approvalId) void this.show() } }) this.panel.onDidDispose(() => { this.closed = true this.unsubscribeFrames() this.disposed.fire() this.disposed.dispose() }) this.panel.webview.onDidReceiveMessage(message => { if (!isRecord(message)) return if (message.type === 'send' && typeof message.text === 'string') void this.send(message.text) if (message.type === 'stop') void this.stop() if (message.type === 'refresh') void this.show() if (message.type === 'modelSelect' && typeof message.provider === 'string' && typeof message.model === 'string') void this.selectModel(message.provider, message.model, typeof message.reasoningEffort === 'string' ? message.reasoningEffort : undefined) if (message.type === 'permissionSelect' && typeof message.preset === 'string') void this.selectPermission(message.preset) if (message.type === 'approval' && typeof message.id === 'string' && (message.outcome === 'allowed-once' || message.outcome === 'rejected')) void this.answerApproval(message.id, message.outcome) }) } onDispose(handler: () => void): void { this.disposed.event(handler) } dispose(): void { this.panel.dispose() } async open(session: RemoteSession): Promise { if (session.sessionId !== this.session.sessionId) { this.session = session this.approvals = [] this.projectionValues = { ...session.projections?.values } this.modelCatalog = undefined this.modelLabel = 'Model' this.loaded = false this.running = session.running this.cancelling = false this.panel.title = sessionTitle(session) } else { this.session = session this.projectionValues = { ...this.projectionValues, ...session.projections?.values } } await this.show() } async show(): Promise { const session = this.session if (this.closed) return this.panel.reveal(vscode.ViewColumn.Beside, false) if (!this.loaded) this.panel.webview.html = renderLoadingSession(this.panel.webview, session) let messages: ChatMessage[] let catalog: SessionModels | undefined try { [messages, catalog] = await Promise.all([ this.connection.history(session.sessionId), this.connection.models(session.sessionId).catch(() => undefined), ]) } catch (error) { if (this.closed) return throw error } if (this.closed || session.sessionId !== this.session.sessionId) return if (catalog) { this.modelCatalog = catalog const selected = catalog.groups.flatMap(group => group.models).find(model => model.id === catalog.current.model) this.modelLabel = selected?.name ?? catalog.current.model } this.loaded = true this.panel.webview.html = renderSession(this.panel.webview, session, messages, this.approvals, this.busy, this.running, this.cancelling, this.modelLabel, this.modelCatalog, this.projectionValues) } private async send(value: string): Promise { const text = value.trim() if (!text || this.busy) return this.busy = true void this.show() try { await this.connection.prompt(this.session.sessionId, text) this.running = true await this.onChanged() } catch (error) { void vscode.window.showErrorMessage(error instanceof Error ? error.message : String(error)) } finally { this.busy = false await this.show().catch(() => undefined) } } private async stop(): Promise { if (!this.running || this.cancelling) return this.cancelling = true void this.show() try { await this.connection.cancelSession(this.session.sessionId) await this.onChanged() } catch (error) { this.cancelling = false void vscode.window.showErrorMessage(error instanceof Error ? error.message : String(error)) await this.show().catch(() => undefined) } } private async selectModel(provider: string, modelId: string, reasoningEffort?: string): Promise { const catalog = this.modelCatalog ?? await this.connection.models(this.session.sessionId) if (!catalog.routable) return const group = catalog.groups.find(item => item.id === provider) const model = group?.models.find(item => item.id === modelId) if (model === undefined) return if (reasoningEffort !== undefined && !model.reasoning?.efforts.some(item => item.id === reasoningEffort)) return await this.connection.selectModel(this.session.sessionId, { provider, model: modelId, ...(reasoningEffort ? { reasoningEffort } : {}) }) this.modelCatalog = { ...catalog, current: { provider, model: modelId, ...(reasoningEffort ? { reasoningEffort } : {}) } } this.modelLabel = model.name await this.show() } private async selectPermission(preset: string): Promise { const permissions = permissionSelect(this.projectionValues) if (permissions === undefined || !permissions.options.some(option => option.value === preset && option.value !== 'custom')) return const confirm = preset === 'danger-full-access' ? await vscode.window.showWarningMessage('Enable full access for this session? Harness may modify files and run commands without asking.', { modal: true }, 'Enable Full Access') : 'Enable Full Access' if (confirm !== 'Enable Full Access') return await this.connection.selectPermission(this.session.sessionId, preset) const value = this.projectionValues.permissions if (isRecord(value)) this.projectionValues = { ...this.projectionValues, permissions: { ...value, currentValue: preset } } await this.show() } private async answerApproval(approvalId: string, outcome: 'allowed-once' | 'rejected'): Promise { const approval = this.approvals.find(item => item.approvalId === approvalId) if (!approval) return await this.connection.respondApproval(approval.frameRpcId, approval.sessionId, approval.approvalId, outcome) this.approvals = this.approvals.filter(item => item !== approval) await this.show() } } function renderSession(webview: vscode.Webview, session: RemoteSession, messages: ChatMessage[], approvals: PendingApproval[], busy: boolean, running: boolean, cancelling: boolean, modelLabel: string, catalog: SessionModels | undefined, projections: Record): string { const nonce = crypto.randomUUID().replaceAll('-', '') const content = messages.length === 0 ? '
◡
What can I help you build?Send a message to start this remote Harness session.
' : messages.map(message => message.role === 'tool' ? renderToolMessage(message) : `
${message.role === 'assistant' ? `
${fishLogo()}
` : ''}
${message.role === 'user' ? 'You' : 'DeepSeek Harness'}
${message.role === 'assistant' ? markdown.render(message.text) : escapeHtml(message.text).replaceAll('\n', '
')}
`).join('') const approvalCards = approvals.map(item => `
Approval required${escapeHtml(item.toolName)}${item.reason ? ` · ${escapeHtml(item.reason)}` : ''}
`).join('') const permissions = permissionSelect(projections) const statistics = sessionStatistics(projections) const modelMenu = renderModelMenu(catalog) const permissionMenu = permissions === undefined ? '' : `` const actionButton = running ? `` : `` return `
${escapeHtml(session.cwd ?? session.sessionId)}
${content}
${approvalCards}${modelMenu}${permissionMenu}
${permissions === undefined ? '' : ``}
${actionButton}
${statistics}
` } function renderLoadingSession(webview: vscode.Webview, session: RemoteSession): string { const nonce = crypto.randomUUID().replaceAll('-', '') return `
${escapeHtml(session.cwd ?? session.sessionId)}
Loading history…
` } function escapeHtml(value: string): string { return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''') } function renderToolMessage(message: ChatMessage): string { const state = message.toolState ?? 'running' const detail = message.toolDetail ? `
${escapeHtml(message.toolDetail)}
` : '' return `
${toolIcon(message.toolKind)}
${escapeHtml(message.text)}${toolStateLabel(state)}
${detail}
` } function toolIcon(kind: string | undefined): string { const paths: Record = { read: '', edit: '', delete: '', move: '', search: '', execute: '', fetch: '', other: '', } return `` } function fishLogo(): string { return '' } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } function toolStateLabel(state: ChatMessage['toolState']): string { const zh = vscode.env.language.toLowerCase().startsWith('zh') if (state === 'failed') return zh ? '失败' : 'Failed' if (state === 'completed') return zh ? '已完成' : 'Completed' return zh ? '运行中' : 'Running' } function loginCopy() { if (vscode.env.language.toLowerCase().startsWith('zh')) return { overview: '安全连接远端 DeepSeek Harness Host,在 VS Code 中继续查看 Workspace 和对话。', requirementBefore: '使用前,远端电脑的 DeepSeek Harness 必须先安装并启用', requirementAfter: '插件,并与 VS Code 登录同一账号。', openSettings: '打开设置', qrLogin: '二维码登录', passwordLogin: '账号密码', generating: '正在生成…', generateQr: '生成二维码', regenerateQr: '重新生成二维码', scanHint: '使用知乎扫码授权当前设备。', email: '邮箱', password: '密码', signIn: '登录', signingIn: '正在登录…', passwordHint: '仅限邀请码或自建账号,非 DeepSeek 官方。', } return { overview: 'Securely connect to a remote DeepSeek Harness Host and continue its workspaces and conversations in VS Code.', requirementBefore: 'Before signing in, install and enable the', requirementAfter: 'plugin on the remote DeepSeek Harness computer, then use the same account on both devices.', openSettings: 'Open settings', qrLogin: 'QR Login', passwordLogin: 'Account & Password', generating: 'Generating…', generateQr: 'Generate QR Code', regenerateQr: 'Generate a new code', scanHint: 'Scan with Zhihu to authorize this device.', email: 'Email', password: 'Password', signIn: 'Sign In', signingIn: 'Signing in…', passwordHint: 'Invite or self-hosted accounts only; not DeepSeek official.', } } function renderModelMenu(catalog: SessionModels | undefined): string { if (catalog === undefined || !catalog.routable) return '' const groups = catalog.groups.map(group => { const options = group.models.map(model => { const efforts = model.reasoning?.efforts ?? [] if (efforts.length === 0) { const selected = catalog.current.provider === group.id && catalog.current.model === model.id return `` } return `${efforts.map(effort => { const selected = catalog.current.provider === group.id && catalog.current.model === model.id && catalog.current.reasoningEffort === effort.id return `` }).join('')}` }).join('') return `${options}` }).join('') return `` } function permissionSelect(values: Record): { currentName: string; currentValue: string; options: Array<{ value: string; name: string; description?: string }> } | undefined { const source = values.permissions if (!isRecord(source) || typeof source.currentValue !== 'string' || !Array.isArray(source.options)) return undefined const options = source.options.flatMap(option => { if (!isRecord(option) || typeof option.value !== 'string' || typeof option.name !== 'string') return [] return [{ value: option.value, name: option.name, ...(typeof option.description === 'string' ? { description: option.description } : {}) }] }) const current = options.find(option => option.value === source.currentValue) return { currentName: current?.name ?? source.currentValue, currentValue: source.currentValue, options } } function sessionStatistics(values: Record): string { const stats = isRecord(values.sessionStats) ? values.sessionStats : undefined const usage = isRecord(values.tokenUsage) ? values.tokenUsage : undefined if (stats === undefined && usage === undefined) return '' const turns = finiteNumber(stats?.turns) const steps = finiteNumber(stats?.steps) const llmMs = finiteNumber(stats?.llmMs) const toolMs = finiteNumber(stats?.toolMs) const ttftMs = finiteNumber(stats?.ttftMs) const ttftSteps = finiteNumber(stats?.ttftSteps) const decodeMs = finiteNumber(stats?.decodeMs) const decodeTokens = finiteNumber(stats?.decodeTokens) const uncachedInput = finiteNumber(usage?.uncachedInputTokens) const cacheRead = finiteNumber(usage?.cacheReadTokens) const cacheWrite = finiteNumber(usage?.cacheWriteTokens) const output = finiteNumber(usage?.outputTokens) const input = uncachedInput + cacheRead + cacheWrite const cacheRate = input > 0 ? cacheRead / input * 100 : 0 const ttft = ttftSteps > 0 ? ttftMs / ttftSteps / 1_000 : 0 const speed = decodeMs > 0 ? decodeTokens / (decodeMs / 1_000) : 0 const groups = [ `${formatInteger(turns)} 轮 · ${formatInteger(steps)} 步`, `LLM ${formatDuration(llmMs)} · 工具调用 ${formatDuration(toolMs)}`, `首 token 平均 ${formatSeconds(ttft)} · ${formatRate(speed)} tok/s`, `缓存命中 ${Math.round(cacheRate)}%`, `输入 ${formatTokens(input)} tok · 输出 ${formatTokens(output)} tok`, ] return `
${groups.map(group => `${escapeHtml(group)}`).join('')}
` } function finiteNumber(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0 } function formatInteger(value: number): string { return Math.round(value).toLocaleString('en-US') } function formatSeconds(value: number): string { return value < 10 ? `${value.toFixed(1)}s` : `${Math.round(value)}s` } function formatRate(value: number): string { return value < 10 ? value.toFixed(1) : Math.round(value).toString() } function formatDuration(ms: number): string { const seconds = Math.round(ms / 1_000) const minutes = Math.floor(seconds / 60) const rest = seconds % 60 return `${minutes > 0 ? `${minutes}m` : ''}${rest}s` } function formatTokens(value: number): string { if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M` if (value >= 1_000) return `${Math.round(value / 1_000)}K` return formatInteger(value) } type RemoteTreeItem = HostItem | WorkspaceItem | SessionItem class RemoteExplorerProvider implements vscode.TreeDataProvider { private readonly changed = new vscode.EventEmitter(); readonly onDidChangeTreeData = this.changed.event constructor(private readonly children: (element?: RemoteTreeItem) => Promise) {} fire(): void { this.changed.fire() } getTreeItem(item: RemoteTreeItem): vscode.TreeItem { return item } getChildren(element?: RemoteTreeItem): Promise { return this.children(element) } } class HostItem extends vscode.TreeItem { readonly contextValue = 'dshRemote.host' constructor(readonly host: RemoteHost, connected: boolean) { super(host.name, vscode.TreeItemCollapsibleState.Collapsed) this.description = connected ? 'Connected · Online' : host.online ? 'Online' : 'Offline' this.tooltip = `${host.name} · ${this.description} · ${host.platform}${host.harnessVersion ? ` · Harness ${host.harnessVersion}` : ''}` this.iconPath = new vscode.ThemeIcon( connected ? 'remote-explorer' : 'circle-filled', new vscode.ThemeColor(connected || host.online ? 'testing.iconPassed' : 'disabledForeground'), ) } } class WorkspaceItem extends vscode.TreeItem { readonly contextValue = 'dshRemote.workspace' constructor(readonly workspace: RemoteWorkspace) { super(workspace.title || workspace.path, vscode.TreeItemCollapsibleState.Collapsed); this.description = workspace.path; this.iconPath = new vscode.ThemeIcon('folder') } } class SessionItem extends vscode.TreeItem { readonly contextValue = 'dshRemote.session' constructor(readonly session: RemoteSession) { super(sessionTitle(session)); this.description = session.running ? 'running' : relativeTime(session.updatedAt); this.tooltip = session.cwd; this.iconPath = new vscode.ThemeIcon(session.running ? 'loading~spin' : 'comment-discussion'); this.command = { command: 'dshRemote.openSession', title: 'Open Session', arguments: [this] } } } function sessionTitle(session: RemoteSession): string { const values = session.projections?.values const metadata = isRecord(values?.sessionListMetadata) ? values.sessionListMetadata : undefined const candidates: unknown[] = [ metadata?.title, values?.title, values?.sessionTitle, values?.conversationTitle, isRecord(values?.summary) ? values.summary.title : undefined, isRecord(values?.metadata) ? values.metadata.title : undefined, session.title, ] for (const value of candidates) if (typeof value === 'string' && value.trim()) return value.trim() if (values) { for (const [key, value] of Object.entries(values)) if (/title/i.test(key) && typeof value === 'string' && value.trim()) return value.trim() } return session.parentSessionId ? 'Subtask session' : 'New session' } function relativeTime(value: number): string { const elapsed = Math.max(0, Date.now() - value) if (elapsed < 60_000) return 'now' if (elapsed < 3_600_000) return `${Math.floor(elapsed / 60_000)}m` if (elapsed < 86_400_000) return `${Math.floor(elapsed / 3_600_000)}h` return `${Math.floor(elapsed / 86_400_000)}d` }