Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 109 additions & 109 deletions docs/inventory/visible-controls.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions flybot_workspace/static/chat/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -3609,7 +3609,7 @@ body.app-workspace .mobile-inbox-heading h1 {
#chat-send.composer-send { background: var(--chat-action-fill) !important; }
#chat-send.composer-send:hover:not(:disabled) { filter: brightness(1.06); }
#chat-send.composer-send:disabled { opacity: .52; }
#group-bot-activity {
:is(#group-bot-activity, #private-computer-activity) {
box-sizing: border-box;
max-width: var(--chat-reading-width);
position: relative;
Expand All @@ -3620,8 +3620,8 @@ body.app-workspace .mobile-inbox-heading h1 {
line-height: 1.4;
overflow-wrap: anywhere;
}
#group-bot-activity:empty { display: none; }
#group-bot-activity:not(:empty)::before {
:is(#group-bot-activity, #private-computer-activity):empty { display: none; }
:is(#group-bot-activity, #private-computer-activity):not(:empty)::before {
content: '';
position: absolute;
inset-inline-start: .65rem;
Expand Down
68 changes: 64 additions & 4 deletions flybot_workspace/static/chat/computer.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
const endpoint = '/b/api/flybot-workspace/computer';
const asset = endpoint + '?op=asset&name=core%2Frfb.js';
const id = /^[a-f0-9]{32}$/;
const progressLabels = {
screenshot: ['正在截取桌面画面…', 'Taking a screenshot…', '已截取桌面画面', 'Screenshot taken'],
open: ['正在打开应用…', 'Opening an app…', '已启动应用', 'App launched'],
windows: ['正在查看窗口…', 'Looking for windows…', '已查看窗口列表', 'Window list checked'],
inspect: ['正在查看窗口内容…', 'Inspecting a window…', '已查看窗口内容', 'Window inspected'],
click: ['正在点击桌面…', 'Clicking on the desktop…', '已点击桌面', 'Desktop click completed'],
key: ['正在操作键盘…', 'Using the keyboard…', '已执行按键操作', 'Keystroke sent'],
type: ['正在输入内容…', 'Typing…', '已输入内容', 'Text entered'],
};

function connectChannel(url, onClose) {
const stop = new AbortController();
Expand Down Expand Up @@ -74,7 +83,10 @@ export function mountBotComputer(document, button, {fetcher = fetch, dock = null
if (!button) return noOp;
const en = () => document.documentElement.lang?.startsWith('en');
const copy = (zh, english) => en() ? english : zh;
const activity = document.getElementById('private-computer-activity');
const window = document.defaultView;
let target = null;
let statusWatch = null;
let view = null;
let panel, modal, heading, state, image, screen, take, handBack, close, retry, full, placeholder;
const path = (owner, op, extra = {}) => endpoint + '?' + new URLSearchParams({
Expand All @@ -87,6 +99,51 @@ export function mountBotComputer(document, button, {fetcher = fetch, dock = null
return response;
}

function showProgress(progress) {
if (!activity) return;
let text = '';
if (progress && Object.hasOwn(progressLabels, progress.action)) {
const [workingZh, workingEn, doneZh, doneEn] = progressLabels[progress.action];
if (progress.state === 'working') text = copy(workingZh, workingEn);
if (progress.state === 'done') text = copy(doneZh, doneEn);
if (progress.state === 'failed') text = copy('电脑操作遇到问题', 'Desktop action encountered a problem');
}
if (activity.textContent !== text) activity.textContent = text;
}

function stopStatus() {
const previous = statusWatch;
statusWatch = null;
previous?.abort.abort();
if (previous) window?.clearTimeout?.(previous.timer);
showProgress();
}

function watchStatus() {
stopStatus();
if (!target || document.visibilityState === 'hidden') return;
const watch = {target, abort:new AbortController(), timer:null};
statusWatch = watch;
async function refresh() {
let interval = 5000;
try {
const signal = AbortSignal.any([watch.abort.signal, AbortSignal.timeout(8000)]);
const response = await request(watch.target, 'status', {signal});
const status = await response.json();
if (statusWatch !== watch) return;
button.hidden = !status.available;
showProgress(status.available ? status.activity : undefined);
if (status.activity) interval = 3000;
} catch {
if (statusWatch !== watch) return;
showProgress();
interval = 15000;
}
if (activity) watch.timer = window?.setTimeout?.(() => void refresh(), interval);
}
void refresh();
}

function say(zh, english) { state.textContent = copy(zh, english); }

function setMode(mode) {
Expand Down Expand Up @@ -307,7 +364,12 @@ export function mountBotComputer(document, button, {fetcher = fetch, dock = null
}
void start();
});
document.defaultView?.addEventListener?.('pagehide', stopView);
window?.addEventListener?.('pagehide', stopView);
window?.addEventListener?.('pagehide', stopStatus);
window?.addEventListener?.('pageshow', () => {
if (!statusWatch) watchStatus();
});
document.addEventListener?.('visibilitychange', watchStatus);
return {
setTarget(agent) {
const next = agent && !agent.archived && !agent.native_deleted && id.test(agent.id) && id.test(agent.workspace_id)
Expand All @@ -316,9 +378,7 @@ export function mountBotComputer(document, button, {fetcher = fetch, dock = null
dismiss();
target = next;
button.hidden = true;
if (next) void request(next,'status').then(() => {
if (next === target) button.hidden = false;
}, () => {});
watchStatus();
},
close: dismiss,
};
Expand Down
1 change: 1 addition & 0 deletions flybot_workspace/static/chat/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,7 @@ <h2 id="conversation-agents-heading" class="visually-hidden" data-ui-text="chat.
<section id="private-action-cards" class="chat-action-cards" aria-label="私聊待处理卡片" data-ui-label="chat.cards.private" hidden></section>
<form id="chat-form" method="post" action="/v1/workspaces" novalidate>
<p id="group-bot-activity" role="status" aria-atomic="true"></p>
<p id="private-computer-activity" role="status" aria-atomic="true"></p>
<p id="chat-app-approvals" class="chat-approval-notice" role="status" aria-atomic="true" hidden>
<span data-ui-text="chat.approvals.pending">有应用调用待确认</span>
<a href="/settings/connectors#connected-tool-approvals" target="_blank" rel="noopener" data-ui-text="chat.approvals.review">在新标签页查看</a>
Expand Down
19 changes: 13 additions & 6 deletions runtime/flybot-image/plugin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,20 @@ export function apply(ctx, config = {}) {
},
},
async execute(args, exec) {
const bot = privateBot(exec.agent?.id)
const session = exec.agent?.id
const bot = privateBot(session)
if (!bot) throw new Error('Open this Bot’s private chat to use its computer.')
const result = await computers.botAction({id:bot.id,name:bot.name,cwd:rt.workDirOf({botId:bot.id})},args,exec.signal)
if (typeof result === 'string') return result
return JSON.stringify(await ctx.get('attachments').saveImage({
mediaType:'image/png',name:'Bot computer screenshot',data:result,
}))
const live = rt.live.get(session)
const turn = live?.turn
const isCurrent = () => turn !== undefined && rt.live.get(session) === live && live.turn === turn
&& livePrivateChat(rt,bot.id,session) === session
return computers.trackActivity(bot.id, args.action, isCurrent, async () => {
const result = await computers.botAction({id:bot.id,name:bot.name,cwd:rt.workDirOf({botId:bot.id})},args,exec.signal)
if (typeof result === 'string') return result
return JSON.stringify(await ctx.get('attachments').saveImage({
mediaType:'image/png',name:'Bot computer screenshot',data:result,
}))
})
},
})
ctx.effect(() => ctx.tools.register(desktop, {
Expand Down
26 changes: 25 additions & 1 deletion runtime/flybot-workspace-web/src/computer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const CAPACITY = 8
const IDLE = 30 * 60_000
const CONTROL_IDLE = 25_000
const CHUNK = 64 * 1024
const PROGRESS_ACTIONS = new Set(['screenshot','open','click','key','type','windows','inspect'])

function fault(status, message) {
return Object.assign(new Error(message), {status})
Expand Down Expand Up @@ -67,6 +68,7 @@ function touch(desktop, lease) {

export function createComputers(dataDir, {available = computerAvailable} = {}) {
const sessions = new Map()
const activity = new Map()
let nextDisplay = 80

function stop(desktop) {
Expand Down Expand Up @@ -246,6 +248,9 @@ export function createComputers(dataDir, {available = computerAvailable} = {}) {

const timer = setInterval(() => {
const now = Date.now()
for (const [id, entry] of activity) {
if (!entry.isCurrent()) activity.delete(id)
}
for (const desktop of sessions.values()) {
if (desktop.env && !desktop.lease && !desktop.bot && now - desktop.last > IDLE) stop(desktop)
}
Expand All @@ -256,8 +261,22 @@ export function createComputers(dataDir, {available = computerAvailable} = {}) {
available,
close() {
clearInterval(timer)
activity.clear()
for (const desktop of sessions.values()) stop(desktop)
},
async trackActivity(id, action, isCurrent, perform) {
if (!PROGRESS_ACTIONS.has(action) || !isCurrent()) return perform()
const entry = {action, state:'working', isCurrent}
activity.set(id, entry)
try {
const result = await perform()
entry.state = 'done'
return result
} catch (error) {
entry.state = 'failed'
throw error
}
},
async botAction(target, args, signal) {
signal?.throwIfAborted()
const desktop = await get(target)
Expand Down Expand Up @@ -346,7 +365,12 @@ export function createComputers(dataDir, {available = computerAvailable} = {}) {
if (!ID.test(workspace || '') || !ID.test(id || '')) throw fault(404,'Unknown Bot')
const target = await resolve(workspace,id)
if (!target || !/^[a-zA-Z0-9_-]{1,80}$/.test(target.id)) throw fault(404,'Unknown Bot')
if (method === 'GET' && op === 'status') return reply({available:true})
if (method === 'GET' && op === 'status') {
const entry = activity.get(target.id)
if (entry?.isCurrent()) return reply({available:true, activity:{action:entry.action, state:entry.state}})
activity.delete(target.id)
return reply({available:true})
}
if (method === 'POST' && op === 'start') {
await get(target)
return reply({started:true})
Expand Down
49 changes: 49 additions & 0 deletions runtime/flybot-workspace-web/test/computer-activity.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {COMPUTER_PATH, createComputers} from '../src/computer.js'

test('computer status exposes only the authorized Bot’s current desktop activity', async t => {
const computers = createComputers('/unused', {available:() => true})
t.after(() => computers.close())
const workspace = 'a'.repeat(32)
const agent = 'b'.repeat(32)
const otherAgent = 'c'.repeat(32)
const status = computers.handler((workspaceId, agentId) => {
if (workspaceId !== workspace) return null
if (agentId === agent) return {id:'chief'}
if (agentId === otherAgent) return {id:'other'}
return null
})
const get = (id = agent, from = workspace) => status(new Request(
'https://flybot.example' + COMPUTER_PATH + '?' + new URLSearchParams({op:'status',workspace:from,agent:id}),
))
const read = async id => (await get(id)).json()

let turn = 1
const first = Promise.withResolvers()
const running = computers.trackActivity('chief', 'type', () => turn === 1, () => first.promise)
const response = await get()
assert.equal(response.headers.get('cache-control'), 'private, no-store')
assert.deepEqual(await response.json(), {available:true,activity:{action:'type',state:'working'}})
assert.deepEqual(await read(otherAgent), {available:true})
assert.equal((await get(agent, 'd'.repeat(32))).status, 404)

first.resolve('sensitive desktop text')
assert.equal(await running, 'sensitive desktop text')
assert.deepEqual(await read(), {available:true,activity:{action:'type',state:'done'}})

const previous = Promise.withResolvers()
const interrupted = computers.trackActivity('chief', 'click', () => turn === 1, () => previous.promise)
turn = 2
assert.deepEqual(await read(), {available:true})
await computers.trackActivity('chief', 'inspect', () => turn === 2, async () => 'ready')
previous.resolve('late click result')
await interrupted
assert.deepEqual(await read(), {available:true,activity:{action:'inspect',state:'done'}})

const failure = new Error('sensitive desktop error')
await assert.rejects(computers.trackActivity('chief', 'open', () => turn === 2, async () => { throw failure }), failure)
assert.deepEqual(await read(), {available:true,activity:{action:'open',state:'failed'}})
turn = undefined
assert.deepEqual(await read(), {available:true})
})
Loading