diff --git a/docs/inventory/visible-controls.json b/docs/inventory/visible-controls.json index 8fb64157a..a668ef3a9 100644 --- a/docs/inventory/visible-controls.json +++ b/docs/inventory/visible-controls.json @@ -2398,44 +2398,44 @@ {"source": "flybot_workspace/static/chat/app.mjs", "line": 3182, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/chat/app.mjs", "line": 3321, "construction": "const configure = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/chat/app.mjs", "line": 3358, "construction": "const save = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 3747, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 3810, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 3835, "construction": "const pin = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 3912, "construction": "const chip = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 3923, "construction": "const add = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 3933, "construction": "const choice = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 3995, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 4166, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 4198, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 4235, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 4953, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5034, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5284, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5304, "construction": "const file = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5331, "construction": "const edit = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5333, "construction": "const retract = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5373, "construction": "const input = document.createElement('textarea'); input.value = item.body || '';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5375, "construction": "const save = document.createElement('button'); save.type = 'button'; save.textContent = '保存修改';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5383, "construction": "const confirm = document.createElement('button'); confirm.type = 'button'; confirm.textContent = '确认修改';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5384, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = '取消';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5390, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = '取消';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5398, "construction": "const confirm = document.createElement('button'); confirm.type = 'button'; confirm.textContent = '确认撤回';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5399, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = '取消';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5409, "construction": "const reply = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5418, "construction": "const copy = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5427, "construction": "const more = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 5697, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 6350, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 6447, "construction": "const toggle = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 7288, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 7352, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 7721, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 7729, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 8339, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 8685, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 8773, "construction": "const jump = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 9435, "construction": "const confirm = document.createElement('button'); confirm.type = 'button'; confirm.textContent = uiLabel('确认移除', 'Remove agent');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/chat/app.mjs", "line": 9436, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = uiLabel('取消', 'Cancel');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 3751, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 3814, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 3839, "construction": "const pin = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 3916, "construction": "const chip = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 3927, "construction": "const add = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 3937, "construction": "const choice = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 3999, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 4170, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 4202, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 4239, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 4957, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5038, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5288, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5308, "construction": "const file = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5335, "construction": "const edit = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5337, "construction": "const retract = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5377, "construction": "const input = document.createElement('textarea'); input.value = item.body || '';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5379, "construction": "const save = document.createElement('button'); save.type = 'button'; save.textContent = '保存修改';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5387, "construction": "const confirm = document.createElement('button'); confirm.type = 'button'; confirm.textContent = '确认修改';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5388, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = '取消';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5394, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = '取消';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5402, "construction": "const confirm = document.createElement('button'); confirm.type = 'button'; confirm.textContent = '确认撤回';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5403, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = '取消';", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5413, "construction": "const reply = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5422, "construction": "const copy = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5431, "construction": "const more = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 5701, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 6354, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 6451, "construction": "const toggle = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 7292, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 7356, "construction": "const box = document.createElement('input');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 7725, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 7733, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 8343, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 8689, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 8777, "construction": "const jump = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 9439, "construction": "const confirm = document.createElement('button'); confirm.type = 'button'; confirm.textContent = uiLabel('确认移除', 'Remove agent');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/chat/app.mjs", "line": 9440, "construction": "const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = uiLabel('取消', 'Cancel');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/chat/code-block.mjs", "line": 25, "construction": "const copy = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/chat/files.mjs", "line": 57, "construction": "const link = document.createElement('a');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/chat/files.mjs", "line": 102, "construction": "const button = document.createElement('button');", "execution_profile": "chat", "verification": "unverified dynamic construction site; conditional instances require execution"}, diff --git a/flybot_workspace/static/chat/app.mjs b/flybot_workspace/static/chat/app.mjs index 776be9923..8437c943b 100644 --- a/flybot_workspace/static/chat/app.mjs +++ b/flybot_workspace/static/chat/app.mjs @@ -3527,7 +3527,7 @@ export function mount(document, {fetcher = globalThis.fetch.bind(globalThis)} = async function settleReplyProgress(watch, {terminal = true} = {}) { watch.terminal ||= terminal; - if (replyWatch === watch) approvalNotice.stop(); + if (terminal && replyWatch === watch) approvalNotice.stop(); globalThis.clearTimeout(watch.receiptTimer); if (watch.posting) { if (!await acceptPostingReply(watch)) scheduleReplyProgress(watch, 1200); @@ -3548,11 +3548,15 @@ export function mount(document, {fetcher = globalThis.fetch.bind(globalThis)} = const snapshot = result?.status === 200 ? result.body : null; if (snapshot?.state === 'pending' || snapshot?.state === 'running') { watch.failures = 0; + const hasRevision = Number.isSafeInteger(snapshot.revision); + if (snapshot.state === 'running' && !hasRevision && snapshot.text === '' && watch.snapshot) { + // The saved reply can still be running while live progress is unavailable. + snapshot.text = watch.snapshot.text; + } observeReplyProgress(watch, snapshot); - const changed = Number.isSafeInteger(snapshot.revision) && snapshot.revision !== watch.revision; + const changed = hasRevision && snapshot.revision !== watch.revision; if (changed) watch.revision = snapshot.revision; - const unchangedDelay = Number.isSafeInteger(snapshot.revision) ? 100 : 400; - scheduleReplyProgress(watch, changed ? 50 : unchangedDelay); + scheduleReplyProgress(watch, changed ? 50 : 750); return; } if (['succeeded','failed','cancelled'].includes(snapshot?.state)) return settleReplyProgress(watch); diff --git a/runtime/flybot-image/ds-bot-bridge.mjs b/runtime/flybot-image/ds-bot-bridge.mjs index d53ebb0c1..a822a94b6 100644 --- a/runtime/flybot-image/ds-bot-bridge.mjs +++ b/runtime/flybot-image/ds-bot-bridge.mjs @@ -255,15 +255,16 @@ export async function prepareNativeChat(rt, botId, savedSessionId) { // Join progress to the native request echo and durable turn. The settled display // items remain the source of truth for the returned reply. -export function runTurn(rt, ctx, botId, text, requestId, timeoutMs = 170000, files = [], { onProgress, onPhase, sessionId, signal, managedGroup = false } = {}) { +export function runTurn(rt, ctx, botId, text, requestId, timeoutMs = 170000, files = [], { onProgress, onPhase, sessionId, signal, managedGroup = false, interactive = false } = {}) { if (signal?.aborted) return Promise.reject(signal.reason) if (typeof requestId !== 'string' || !requestId) return Promise.reject(new Error('DS-Bot request identifier is required')) if (sessionId !== undefined && !ownsLiveChat(rt, botId, sessionId)) return Promise.reject(new Error('Mapped native chat is no longer active')) sessionId ??= rt.chatOf(botId) + const admissionOnly = interactive && !managedGroup return new Promise((resolve, reject) => { const progress = turnProgress(onProgress) let observedTurn, observedSession, boundTurn, boundSession, attempt, lastAgent - let stopping + let stopping, stopDeadline, stopTimer let revision = 0 let phase = 'preparing' function emitPhase(next) { @@ -286,23 +287,36 @@ export function runTurn(rt, ctx, botId, text, requestId, timeoutMs = 170000, fil else listener?.dispose?.() } catch {} } - const complete = () => error ? reject(error) : resolve(value) - if (stopping) void stopping.then(complete, complete) + const complete = () => { + clearTimeout(stopTimer) + if (error) reject(error) + else resolve(value) + } + if (stopping) void (stopDeadline ? Promise.race([stopping, stopDeadline]) : stopping).then(complete, complete) else complete() } - const timer = setTimeout(() => finish(new Error('DS-Bot turn timed out')), timeoutMs) + const timer = setTimeout(() => finish(admissionOnly && signal?.aborted ? signal.reason : new Error('DS-Bot turn timed out')), timeoutMs) const emptyReply = () => Object.assign(new Error('DS-Bot turn ended without a reply'), {code:'agents/empty-reply'}) function cancelNative() { if (settled || stopping || !boundSession || boundTurn === undefined) return const session = boundSession, turn = boundTurn + if (admissionOnly) { + // Native cancellation should emit its terminal event. Bound cleanup if the + // runtime can no longer resolve or settle a turn that the user has stopped. + stopDeadline = new Promise(done => { stopTimer = setTimeout(done, 30_000) }) + void stopDeadline.then(() => finish(signal.reason)) + } stopping = Promise.resolve().then(() => rt.resolveAgent(sessionId)).then(agent => { // Do not stop another turn even if it now owns the same Bot or Session. if (settled || boundSession !== session || agent?.session !== session || boundTurn !== turn || - rt.live?.get(sessionId)?.turn !== turn || !ownsLiveChat(rt, botId, sessionId)) return + rt.live?.get(sessionId)?.turn !== turn || !ownsLiveChat(rt, botId, sessionId)) { + if (admissionOnly) finish(signal.reason) + return + } const children = rt.stopSubagents?.(sessionId) agent.cancel({kind:'user'}) return children - }).catch(() => {}) + }).catch(() => { if (admissionOnly) finish(signal.reason) }) } signal?.addEventListener('abort', cancelNative, {once:true}) function discardAttempt() { @@ -324,7 +338,10 @@ export function runTurn(rt, ctx, botId, text, requestId, timeoutMs = 170000, fil const turn = event.data?.turn if (event.type === 'turn/start' && Number.isSafeInteger(turn)) { if (session === observedSession && turn <= observedTurn) return - if (boundTurn !== undefined && turn !== boundTurn) resetTurn() + if (boundTurn !== undefined && turn !== boundTurn) { + if (admissionOnly) { finish(signal?.aborted ? signal.reason : emptyReply()); return } + resetTurn() + } observedTurn = turn observedSession = session return @@ -332,6 +349,7 @@ export function runTurn(rt, ctx, botId, text, requestId, timeoutMs = 170000, fil if (event.type === 'user/message' && event.data?.source?.rpcId === requestId) { boundSession = session boundTurn = session === observedSession ? observedTurn : undefined + if (admissionOnly && boundTurn !== undefined) clearTimeout(timer) if (signal?.aborted) cancelNative() return } @@ -358,7 +376,7 @@ export function runTurn(rt, ctx, botId, text, requestId, timeoutMs = 170000, fil if (signal?.aborted) { finish(signal.reason); return } const reason = event.data?.reason const disposed = reason?.kind === 'aborted' && reason.reason?.kind === 'disposed' - if (managedGroup && disposed) { finish(emptyReply()); return } + if ((managedGroup || admissionOnly) && disposed) { finish(emptyReply()); return } const reply = parts.join('\n\n').trim() if (reply) finish(null, { text: reply, sessionId, turnId: event.data?.turnId ?? event.turnId ?? null }) else if (event.data?.error || (managedGroup && reason && reason.kind !== 'completed')) finish(new Error('DS-Bot turn failed')) @@ -390,8 +408,10 @@ export function runTurn(rt, ctx, botId, text, requestId, timeoutMs = 170000, fil emitPhase('thinking') } }, { global: true })) + } + if (admissionOnly || progress || typeof onPhase === 'function') { listeners.push(ctx.on('agent/disposed', ({ agent }) => { - if (managedGroup && boundSession && agent?.id === sessionId && agent.session === boundSession && !settled) { + if ((managedGroup || admissionOnly) && boundSession && agent?.id === sessionId && agent.session === boundSession && !settled) { finish(signal?.aborted ? signal.reason : emptyReply()) } else if (agent === lastAgent && !settled) { resetTurn() diff --git a/runtime/flybot-image/native-ds-bot-overlay.mjs b/runtime/flybot-image/native-ds-bot-overlay.mjs index 55e2ddce2..2e6ef054f 100644 --- a/runtime/flybot-image/native-ds-bot-overlay.mjs +++ b/runtime/flybot-image/native-ds-bot-overlay.mjs @@ -15,7 +15,7 @@ const files = { ], 'src/host/tools.js': [ 'a5c743b7c75c96498775808f029a5f15c7e08dbe6eaf33089d29b3c2a9ffb382', - '852dafff886dd8625d98152afe85432b8a22648d3627df5b61eddba4cea8c510', + '73846995fff9590d7d059166c8c9de14b27dea5477cfd5b37099800a0e3b96b7', ], 'src/host/roster.js': [ '20461d2d4aeae6ca373e3431a5802317d1130468e1940d22032189134429f984', @@ -23,7 +23,7 @@ const files = { ], 'src/host/prompt.js': [ 'b15fd1dd8b046589533540b45388e6573e84fdf51bb09aa48a97e694c1e83c21', - 'ebf5a93da2ef5941e0417f4018635350cb251212c9eb9384671f2ef9a7bbc2b8', + '21d63cfed3a498fbb47661ee2d7b09dd947b7bd27a2e8ffc1e6b77587f08a2c5', ], 'client.js': [ '98713d86c6cbf85adab1d0a2d303140778d9ed85fb2220abdadfab377a5f539f', diff --git a/runtime/flybot-image/native-ds-bot.patch b/runtime/flybot-image/native-ds-bot.patch index dd9ec8509..45ef9e5ef 100644 --- a/runtime/flybot-image/native-ds-bot.patch +++ b/runtime/flybot-image/native-ds-bot.patch @@ -2064,9 +2064,10 @@ diff --git a/src/host/groups.js b/src/host/groups.js if (running !== undefined) { if (extra.failed !== undefined) { diff --git a/src/host/tools.js b/src/host/tools.js +index 0b9ee2b..b9e79a2 100644 --- a/src/host/tools.js +++ b/src/host/tools.js -@@ -477,7 +477,13 @@ +@@ -477,7 +477,13 @@ export function install(rt) { const served = new Set((await rt.catalog()).filter(entry => entry.needsKey !== true && rt.isLocalAgentRef?.(entry.ref) !== true).map(entry => entry.ref)) const fallback = [state.prefs.defaultBotModel, creator?.model].find(ref => ref && served.has(ref)) const model = args.model || fallback @@ -2081,7 +2082,7 @@ diff --git a/src/host/tools.js b/src/host/tools.js return `Created ${bot.name}${workDir ? `, working in ${workDir}` : ''}. It is greeting the user now.` } catch (error) { return `Could not create the Bot: ${error.message}` -@@ -631,9 +637,9 @@ +@@ -631,9 +637,9 @@ export function install(rt) { rt.teamTools.push(defineTool({ name: 'create_group', @@ -2093,7 +2094,7 @@ diff --git a/src/host/tools.js b/src/host/tools.js name: { type: 'string', description: 'Group name; defaults to the member names' }, notice: { type: 'string', description: 'Shared instructions every member reads before speaking in this group; at most 2000 characters' }, admin: { type: 'string', description: 'Member who leads the group; defaults to you' }, -@@ -647,6 +653,15 @@ +@@ -647,6 +653,15 @@ export function install(rt) { if (!rt.isMain(self)) return 'Only a Main Bot can create group chats. Ask a Main Bot instead.' const { bots, unknown } = resolveBots(args.members) if (unknown.length > 0) return `No Bot named ${unknown.join(', ')}. Team: ${teamNames()}` @@ -2109,16 +2110,22 @@ diff --git a/src/host/tools.js b/src/host/tools.js const admin = args.admin ? rt.findBot(args.admin) : rt.botOf(self) if (admin === undefined) return `No Bot named ${args.admin}. Team: ${teamNames()}` const members = [...new Set([self, ...bots.map(bot => bot.id), admin.id])] -@@ -1189,12 +1204,16 @@ +@@ -1189,12 +1204,20 @@ export function install(rt) { const filterBotAssembly = (agent, held) => { if (held.filtered === true || typeof agent.ctx?.on !== 'function') return const filterTools = agent.ctx.on('llm/stream', function filterBuiltinTools(options, next) { + // The LLM service waterfall is shared. A specialist's restrictions must + // never drop tools from the Chief's concurrent or following model call. + if (options.sessionId !== agent.session?.id) return next() ++ const offered = options.tools ++ if (!Array.isArray(offered)) return next() const hidden = rt.hiddenBuiltinTools(agent.session?.id) - if (!options.tools?.some(tool => hidden.has(tool.name))) return next() - return agent.ctx.llm.stream({ ...options, tools: options.tools.filter(tool => !hidden.has(tool.name)) }) +- if (!options.tools?.some(tool => hidden.has(tool.name))) return next() +- return agent.ctx.llm.stream({ ...options, tools: options.tools.filter(tool => !hidden.has(tool.name)) }) ++ const setup = rt.flybotWorkspaceTeam?.setupTools(agent.session?.id) ++ const canUseSetup = setup && [...setup].every(name => offered.some(tool => tool.name === name && !hidden.has(name))) ++ const tools = offered.filter(tool => !hidden.has(tool.name) && (!canUseSetup || setup.has(tool.name))) ++ return tools.length === offered.length ? next() : agent.ctx.llm.stream({ ...options, tools }) }) if (typeof filterTools === 'function') held.disposers.push(filterTools) - const dispose = agent.ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { @@ -2127,6 +2134,17 @@ diff --git a/src/host/tools.js b/src/host/tools.js const assembled = await next() const hidden = new Set([...HIDDEN_TOOLS, ...rt.hiddenBuiltinTools(agent.session?.id)]) // DSH 0.2.2 adds the tool list after this waterfall (#814), so only an +@@ -1362,6 +1385,10 @@ export function install(rt) { + // goal made there is blocked. + ctx.tools.guard((exec) => { + if (!rt.isBotSession(exec.agent?.id)) return undefined ++ const setup = rt.flybotWorkspaceTeam?.setupTools(exec.agent?.session?.id ?? exec.agent?.id) ++ if (setup && exec.name !== 'run_code' && !setup.has(exec.name)) { ++ return 'Finish the requested team setup first using list_bots, create_bot, and create_group. Use the native tools instead of inspecting files or settings.' ++ } + if (exec.name === BLOCKING_QUESTION_TOOL) return `Bots cannot use ${BLOCKING_QUESTION_TOOL}. Ask with ask_user in your own chat, or ask in your reply.` + if (rt.taskOwners?.has(exec.agent?.id)) { + if (exec.name === 'browser_handoff') return 'Background tasks cannot hand the browser to the user. Report back to your own chat so it can ask the user to take over.' diff --git a/src/host/roster.js b/src/host/roster.js --- a/src/host/roster.js +++ b/src/host/roster.js @@ -2148,9 +2166,10 @@ diff --git a/src/host/roster.js b/src/host/roster.js if (main) state.mainBotIds.push(id) const creator = rt.botOf(createdBy) diff --git a/src/host/prompt.js b/src/host/prompt.js +index 0c42154..cde287f 100644 --- a/src/host/prompt.js +++ b/src/host/prompt.js -@@ -51,12 +51,19 @@ +@@ -51,12 +51,20 @@ export function install(rt) { const bot = rt.botOf(self) if (bot !== undefined) { const main = rt.isMainForTurn?.(id) ?? rt.isMain(self) @@ -2164,7 +2183,8 @@ diff --git a/src/host/prompt.js b/src/host/prompt.js + ...(workspace ? [ + '', + '## FlyBot personal workspace', -+ 'When the user asks you to create or assemble a team, use list_bots to reuse existing specialists, call create_bot for missing roles, and call create_group with their exact names. Use DS Bot tool discovery if these tools are not listed directly. You can do this from the current conversation.', ++ 'When the user asks to assemble a team, start by calling list_bots. Reuse suitable members, call create_bot for missing roles, then call create_group with their exact names. The tool list for this request is authoritative even if a previous reply said a tool was missing. Use DS Bot tool discovery only if the current request presents tools through run_code.', ++ ...(workspace.setupPending ? ['The current user explicitly requested team setup. Create the team before starting repository or project work. Use the native tools directly and report actual results from their calls.'] : []), + 'FlyBot shared groups include only the Bots you list. Include yourself only if the user asks. Supply the name and members, plus a notice if requested. Leave admin, reply mode, and section to group settings. After the tools confirm creation, name the actual Bots and link to the group using the returned link.', + ] : []), ].join('\n') diff --git a/runtime/flybot-image/plugin/index.js b/runtime/flybot-image/plugin/index.js index 437602b80..fc8e2f813 100644 --- a/runtime/flybot-image/plugin/index.js +++ b/runtime/flybot-image/plugin/index.js @@ -92,7 +92,7 @@ export function apply(ctx, config = {}) { bridge.requireModel(botId) const turn = () => runTurn(rt, ctx, botId, text, requestId, undefined, parts, { sessionId, onProgress: options.onProgress, onPhase: options.onPhase, signal: options.signal, - managedGroup: options.managedGroup, + managedGroup: options.managedGroup, interactive: options.interactive, }) return options.personalTeamScope && rt.flybotWorkspaceTeam ? rt.flybotWorkspaceTeam.run({botId,sessionId,requestId,scope:options.personalTeamScope}, turn) diff --git a/runtime/flybot-image/test/container-gateway-isolation.py b/runtime/flybot-image/test/container-gateway-isolation.py index 6e80028a1..17ef40881 100644 --- a/runtime/flybot-image/test/container-gateway-isolation.py +++ b/runtime/flybot-image/test/container-gateway-isolation.py @@ -11,8 +11,9 @@ inside *their* DS-Bot (instance marker + the real FlyBot chat page); * ``POST /b/api/flybot-workspace``, ``POST /b/api/bot`` and a private workspace-agent turn execute in their own DS-Bot; -* a Personal Agent chat turn creates native Bots and one shared group, with the - same participants and room identity across the FlyBot and DS-Bot routes; +* a Personal Agent can recover from a prior tool refusal in the same chat and + use native team tools to create Bots and a shared group, with the same + participants and room identity across the FlyBot and DS-Bot routes; * forged routing headers, a smuggled foreign DSH cookie, no session and a cross-site Origin never reach the other user's runtime; * a runtime's DSH cookie is useless against the other runtime; @@ -53,6 +54,9 @@ NGINX = os.environ.get('FLYBOT_WORKSPACE_GATEWAY_NGINX_IMAGE', 'nginx:1.27-alpine') COOKIE = 'ot_dev_session' SECRETS: list[str] = [] +TEAM_REQUEST = '你建一个Bot团队来开发ThinkFlowLab/FlyBot' +TEAM_REFUSAL_REQUEST = 'CI-TEAM-REFUSAL-REQUEST' +TEAM_REFUSAL_REPLY = 'CI-TEAM-REFUSAL: I cannot see create_bot or create_group in this conversation.' FAKE_MODEL_WRITE = r""" const fs = require('node:fs') @@ -60,36 +64,49 @@ fs.writeFileSync('/data/secrets/model-api.json', JSON.stringify({ provider: 'openai', api_key: 'ci-fake-model-key', base_url: 'http://127.0.0.1:18799/v1', model: 'fake-model' }), { mode: 0o600 }) """ -FAKE_MODEL_SERVER = r""" +FAKE_MODEL_SERVER = ( + f'const teamRequest = {json.dumps(TEAM_REQUEST, ensure_ascii=False)}\n' + f'const teamRefusalRequest = {json.dumps(TEAM_REFUSAL_REQUEST)}\n' + f'const teamRefusalReply = {json.dumps(TEAM_REFUSAL_REPLY)}\n' + + r""" const steps = [ + ['list_bots', {}], ['create_bot', { name: 'CI Team Builder', role: 'Dev', instructions: 'Build the fixture project.' }], ['create_bot', { name: 'CI Team Reviewer', role: 'QA', instructions: 'Review the fixture project.' }], ['create_group', { name: 'CI Shared Team', members: ['CI Team Builder', 'CI Team Reviewer'] }], ] +const teamTools = new Set(steps.map(([name]) => name)) function teamResponse(body) { const messages = body.messages ?? [] - const request = messages.findLastIndex(message => - message.role === 'user' && JSON.stringify(message.content).includes('CI-CREATE-SHARED-TEAM')) + const request = messages.findLastIndex(message => message.role === 'user' && + [teamRequest, teamRefusalRequest].some(marker => JSON.stringify(message.content)?.includes(marker))) if (request < 0) return {} + const content = JSON.stringify(messages[request].content) + if (content?.includes(teamRefusalRequest)) return { text: teamRefusalReply } + if (!content?.includes(teamRequest)) return {} + const priorRefusal = messages.slice(0, request).some(message => + message.role === 'assistant' && JSON.stringify(message.content)?.includes(teamRefusalReply)) + if (!priorRefusal) return { text: 'CI-TEAM-HISTORY-MISSING: previous refusal did not reach the model' } + const results = messages.slice(request + 1).filter(message => message.role === 'tool') + if (results.length && !JSON.stringify(results[0].content)?.includes('Bots:')) { + return { text: 'CI-TEAM-ROSTER-FAILED: list_bots did not return the native roster' } + } if (results.length >= steps.length) return { text: 'CI-TEAM-CREATED' } - const [name, args] = steps[results.length] const available = new Set((body.tools ?? []).map(tool => tool.function?.name).filter(Boolean)) - if (available.has(name)) return { call: { name, arguments: JSON.stringify(args) }, step: results.length } - if (available.has('run_code')) { - return { call: { name: 'run_code', arguments: JSON.stringify({ - description: 'Create the fixture team', - code: `return await tools.${name}(${JSON.stringify(args)})`, - }) }, step: results.length } + const missing = [...teamTools].filter(name => !available.has(name)) + const unexpected = [...available].filter(name => !teamTools.has(name)) + if (missing.length || unexpected.length) { + return { text: `CI-TEAM-TOOLS-INVALID: missing=[${missing.join(',')}] unexpected=[${unexpected.join(',')}]` } } - const guidance = messages.some(message => message.role === 'system' && - JSON.stringify(message.content).includes('## FlyBot personal workspace')) - return { text: `CI-TEAM-TOOL-MISSING: ${name} (guide=${guidance}, tools=${[...available].sort().join(',')})` } + const [name, args] = steps[results.length] + return { call: { name, arguments: JSON.stringify(args) }, step: results.length } } require('node:http').createServer((req, res) => { let raw = '' + req.setEncoding('utf8') req.on('data', (c) => { raw += c }) req.on('end', () => { if (req.method !== 'POST' || !req.url.startsWith('/v1/chat/completions')) { res.writeHead(404); res.end(); return } @@ -116,6 +133,7 @@ }) }).listen(18799, '127.0.0.1') """ +) FAKE_MODEL_PROBE = r""" const s = require('node:net').connect(18799, '127.0.0.1', () => { s.end(); process.exit(0) }) s.on('error', () => process.exit(1)) @@ -459,10 +477,20 @@ def plugin(token, endpoint, payload=None, kind='flybot-workspace'): chief_conversation = api(token_a, 'POST', chief_conversations, {'title': 'CI Chief team setup'}, expected=201)['conversation'] chief_chat = f'{chief_conversations}/{chief_conversation["id"]}' + refused = api(token_a, 'POST', f'{chief_chat}/messages', {'body': TEAM_REFUSAL_REQUEST}, + expected=201, timeout=150)['reply'] + assert refused['status'] == 'succeeded' and refused['body'] == TEAM_REFUSAL_REPLY, redact(refused.get('body')) + established = api(token_a, 'GET', chief_chat)['conversation'] + assert established['native_session_id'], 'prior refusal happened in a native Personal Agent session' acted = api(token_a, 'POST', f'{chief_chat}/messages', - {'body': 'CI-CREATE-SHARED-TEAM: Create a builder, a reviewer, and their shared group.'}, + {'body': TEAM_REQUEST}, expected=201, timeout=150)['reply'] assert acted['status'] == 'succeeded' and acted['body'] == 'CI-TEAM-CREATED', redact(acted.get('body')) + recovered = api(token_a, 'GET', chief_chat) + assert recovered['conversation']['native_session_id'] == established['native_session_id'] + assert [message['body'] for message in recovered['items']] == [ + TEAM_REFUSAL_REQUEST, TEAM_REFUSAL_REPLY, TEAM_REQUEST, 'CI-TEAM-CREATED', + ], 'native team actions complete after the prior refusal in the same chat' # Reload the actual pages and read the same backing API data as the UI. assert browse(token_a, 'GET', '/agents')[0] == 200 names_created = {'CI Team Builder', 'CI Team Reviewer'} diff --git a/runtime/flybot-workspace-web/features/agents/index.js b/runtime/flybot-workspace-web/features/agents/index.js index f70c4e78b..2f89a2fc2 100644 --- a/runtime/flybot-workspace-web/features/agents/index.js +++ b/runtime/flybot-workspace-web/features/agents/index.js @@ -1,7 +1,7 @@ import { loadPersonalAgentBootstrap } from '../../../flybot-image/agent-bootstrap.mjs' import { nativeAgents } from './native.js' import { nativeHistoryProjection } from './native-history-projection.js' -import { attachPersonalTeamCreation } from './team-creation.js' +import { asksToSetUpTeam, attachPersonalTeamCreation } from './team-creation.js' import { importPending } from '../../src/pending-import.js' // Workspace agents inside the user's own DS-Bot (batch B2; moved from // flybot_workspace/agents.py + the agent conversation dispatch in app.py). @@ -124,10 +124,10 @@ export function createAgents({ db, host }) { const all = (sql, ...a) => db.prepare(sql).all(...a) const run = (sql, ...a) => db.prepare(sql).run(...a) const personalBinding = () => one('SELECT workspace_id,agent_id FROM native_personal_binding WHERE singleton=1') - function personalTeamScope(agent) { + function personalTeamScope(agent, text) { const binding = personalBinding() if (binding?.agent_id === agent.id && binding.workspace_id === agent.workspace_id) { - return {workspaceId:agent.workspace_id,agentId:agent.id} + return {workspaceId:agent.workspace_id,agentId:agent.id,...(asksToSetUpTeam(text) ? {setupPending:true} : {})} } } const ws = (p) => { if (typeof p?.workspace_id !== 'string' || !ID.test(p.workspace_id)) fail('invalid', 'workspace_id required', 400); return p.workspace_id } @@ -485,7 +485,7 @@ export function createAgents({ db, host }) { } } - function runTextReply({agent, convo, userId, replyId, text, userMeta, replyMeta, attempt, extra, returnFailed}) { + function runTextReply({agent, convo, userId, replyId, text, userMeta, replyMeta, attempt, extra, returnFailed, interactive = false}) { const stop = replyMeta.clientKey ? new AbortController() : undefined const signal = stop?.signal return trackSend(convo.id, userId, replyId, async (onProgress, onPhase) => { @@ -494,7 +494,7 @@ export function createAgents({ db, host }) { const {context, refs, personalWorkspace, remember} = await privateContext(agent, convo, text, extra) const requestId = attempt === 1 ? `ot-agent:${userId}` : `ot-agent:${userId}:retry:${attempt}` const reply = await turn({agent_id:agent.id,key:convo.id,text,request_id:requestId,reply_language:userMeta.replyLanguage,context}, - {onProgress,onPhase,signal,personalTeamScope:personalTeamScope(agent)}) + {onProgress,onPhase,signal,interactive,personalTeamScope:personalTeamScope(agent,text)}) if (signal?.aborted) return sentPair(userId, replyId) run('UPDATE agent_messages SET meta=? WHERE id=?', JSON.stringify({...userMeta,session_id:reply.session_id}), userId) run('UPDATE agent_messages SET text=?, status=?, meta=? WHERE id=?', reply.text, 'succeeded', @@ -514,6 +514,7 @@ export function createAgents({ db, host }) { } async function sendWithAttachments(p, agent, convo, text, reference) { + const originalText = text const key = p.idempotency_key if (typeof key !== 'string' || !IDEM.test(key)) fail('invalid', 'Attachment send key required', 400) const stickerId = reference?.sticker_id @@ -594,7 +595,8 @@ export function createAgents({ db, host }) { reply_language:p.reply_language, context}, { files, onProgress,onPhase, - personalTeamScope:text ? personalTeamScope(agent) : undefined, + interactive:!!accepted, + personalTeamScope:originalText ? personalTeamScope(agent,originalText) : undefined, onStaged(value) { staged = value.map((file, index) => ({ ...file, ...(files[index]?.resource ? {resource:files[index].resource} : {}), ...(stickerId ? {sticker:true} : {}), @@ -1266,7 +1268,7 @@ export function createAgents({ db, host }) { db.exec('COMMIT') } catch (error) { db.exec('ROLLBACK'); throw error } - const sending = runTextReply({agent,convo,userId,replyId,text,userMeta,replyMeta,attempt:1,extra:p.context,returnFailed:p.return_failed === true}) + const sending = runTextReply({agent,convo,userId,replyId,text,userMeta,replyMeta,attempt:1,extra:p.context,returnFailed:p.return_failed === true,interactive:!!accepted}) accepted?.() return sending }, @@ -1309,7 +1311,7 @@ export function createAgents({ db, host }) { db.exec('COMMIT') } catch (error) { db.exec('ROLLBACK'); throw error } if (reused) return {status:200,...sentPair(userId, replyId)} - void runTextReply({agent,convo,userId,replyId,text:source.text,userMeta,replyMeta,attempt,returnFailed:true}) + void runTextReply({agent,convo,userId,replyId,text:source.text,userMeta,replyMeta,attempt,returnFailed:true,interactive:true}) .catch(error => host.log?.('private reply retry: ' + String(error?.code ?? error?.name ?? 'error'))) return {status:202,...sentPair(userId, replyId)} }, diff --git a/runtime/flybot-workspace-web/features/agents/team-creation.js b/runtime/flybot-workspace-web/features/agents/team-creation.js index 804f737bd..482fabb27 100644 --- a/runtime/flybot-workspace-web/features/agents/team-creation.js +++ b/runtime/flybot-workspace-web/features/agents/team-creation.js @@ -2,6 +2,15 @@ import { createHash } from 'node:crypto' import { livePrivateChat } from '../../lib/native-chat.js' import { sharedBotSocial } from '../../lib/c/bot-social.js' +const SETUP_TOOLS = new Set(['list_bots', 'create_bot', 'create_group']) + +export function asksToSetUpTeam(text) { + if (typeof text !== 'string') return false + const prompt = text.normalize('NFKC').trim() + return /^(?:(?:请|你|帮我|替我|给我|麻烦)\s*)*(?:新建|组建|创建|搭建|建立|建)[^,。!?\n]{0,24}(?:团队|小队|小组)(?!页面|网页|主页|网站|图标|文档|介绍|卡片)/u.test(prompt) || + /^(?:(?:please|can you|could you|help me)\s+)*(?:create|build|assemble|form|set up)\s+(?:[a-z-]+\s+){0,6}(?:team|squad)\b(?:\s*(?:[.!?,;:\n]|$)|\s+(?:to|for|of|with|named|called)\b)/i.test(prompt) +} + export function attachPersonalTeamCreation(rt, { host, binding, publishBot }) { if (rt.flybotWorkspaceTeam) return const active = new Map() @@ -11,6 +20,10 @@ export function attachPersonalTeamCreation(rt, { host, binding, publishBot }) { return rt.isMain(botId) && personal?.workspace_id === workspaceId && personal.agent_id === agentId && link?.workspace_id === workspaceId && link.agent_id === agentId } + const current = sessionId => { + const turn = active.get(rt.chatOwners.get(sessionId)) + return turn && allowed(turn) && livePrivateChat(rt,turn.botId,turn.sessionId) === sessionId ? turn : null + } const key = (requestId, ...parts) => createHash('sha256').update(JSON.stringify([requestId, ...parts])).digest('hex') const chatUrl = (workspaceId, target) => '/chat#' + new URLSearchParams({workspace:workspaceId,...target}) @@ -42,13 +55,17 @@ export function attachPersonalTeamCreation(rt, { host, binding, publishBot }) { if (!allowed(turn) || livePrivateChat(rt,botId,sessionId) !== sessionId) return runTurn() active.set(botId,turn) try { return await runTurn() } - finally { active.delete(botId) } + finally { if (active.get(botId) === turn) active.delete(botId) } + }, + setupTools(sessionId) { + return current(sessionId)?.setupPending ? SETUP_TOOLS : null }, scope(sessionId) { - const turn = active.get(rt.chatOwners.get(sessionId)) - if (!turn || !allowed(turn) || livePrivateChat(rt,turn.botId,turn.sessionId) !== sessionId) return null + const turn = current(sessionId) + if (!turn) return null const {workspaceId,requestId} = turn return { + setupPending:turn.setupPending === true, async createBot({name,role,instructions}, createNativeBot) { const agent = await publishBot({workspace_id:workspaceId, name, summary:role, instructions, idempotency_key:key(requestId,'bot',name.toLowerCase())}, createNativeBot) @@ -67,6 +84,7 @@ export function attachPersonalTeamCreation(rt, { host, binding, publishBot }) { const social = sharedBotSocial(host) const group = await social.createNativeGroup({workspace_id:workspaceId,title,bot_ids:botIds, request_key:key(requestId,'group',title,...botIds.slice().sort())}) + turn.setupPending = false let noticeSaved = true if (announcement) { const path = '/v1/ot/conversations/' + group.conversation_id + '/announcement' diff --git a/runtime/flybot-workspace-web/test/agents.test.js b/runtime/flybot-workspace-web/test/agents.test.js index cdef55cc6..d0847e601 100644 --- a/runtime/flybot-workspace-web/test/agents.test.js +++ b/runtime/flybot-workspace-web/test/agents.test.js @@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url' import { DatabaseSync } from 'node:sqlite' import { createAgents, composePrompt, CATEGORIES } from '../features/agents/index.js' import { loadFeatures } from '../src/features.js' +import { asksToSetUpTeam } from '../features/agents/team-creation.js' import { nativeAgentFixture } from './native-agent-fixture.js' const HERE = dirname(fileURLToPath(import.meta.url)) @@ -231,6 +232,15 @@ test('existing Personal Agent binds Chief without replacing native IDs, private assert.equal((await e.messages(scope)).items.length,4) }) +test('only direct team setup requests trigger the focused Chief workflow', () => { + for (const prompt of ['你建一个Bot团队来开发ThinkFlowLab/FlyBot', '请帮我组建软件开发小队', 'Please create a team for release testing']) { + assert.equal(asksToSetUpTeam(prompt), true, prompt) + } + for (const prompt of ['不要创建团队', '建一个团队网站', 'create a team page', 'Explain how to create a team', '他说:“创建团队”']) { + assert.equal(asksToSetUpTeam(prompt), false, prompt) + } +}) + test('a Personal Agent chat can publish its actual native Bot id once', async () => { const {e, db, services, attachTeam, bots} = fixture() const {rt} = services @@ -256,6 +266,8 @@ test('a Personal Agent chat can publish its actual native Bot id once', async () return rt.flybotWorkspaceTeam.run({botId,sessionId,requestId,scope:options.personalTeamScope},async () => { const tools = rt.flybotWorkspaceTeam.scope(sessionId) assert.ok(tools) + assert.deepEqual([...rt.flybotWorkspaceTeam.setupTools(sessionId)], ['list_bots','create_bot','create_group']) + assert.equal(rt.flybotWorkspaceTeam.setupTools('unowned-session'), null) const profile = {name:'Test Engineer',role:'QA',instructions:'Review the release.'} const build = link => { builds++ @@ -267,8 +279,9 @@ test('a Personal Agent chat can publish its actual native Bot id once', async () return out() }) } - await e.send({...address,conversation_id:conversation.id,text:'Create a test engineer',idempotency_key:'native-team-direct-send'}) + await e.send({...address,conversation_id:conversation.id,text:'你建一个Bot团队来开发ThinkFlowLab/FlyBot',idempotency_key:'native-team-direct-send'}) assert.equal(rt.flybotWorkspaceTeam.scope(managedSession),null) + assert.equal(rt.flybotWorkspaceTeam.setupTools(managedSession),null) await e.turn({agent_id:personal.id,key:conversation.id,text:'External call'}) const roster = (await e.list({workspace_id:W})).items.filter(row => row.name === 'Test Engineer') assert.equal(roster.length,1) diff --git a/runtime/flybot-workspace-web/test/native-chat-threads.test.js b/runtime/flybot-workspace-web/test/native-chat-threads.test.js index 7e30499fa..cfe2f91f7 100644 --- a/runtime/flybot-workspace-web/test/native-chat-threads.test.js +++ b/runtime/flybot-workspace-web/test/native-chat-threads.test.js @@ -141,7 +141,8 @@ test('native bootstrap installs the authenticated provider before selecting Chie assert.equal(bot.model, 'flybot-workspace/flybot-workspace-model') }) -test('cancellation stays bound to the selected live Session and a later turn can resume there', async () => { +test('cancellation stays bound to the selected live Session and a later turn can resume there', async t => { + t.mock.timers.enable({apis:['setTimeout']}) const {rt, bot} = fixture() addPrivateChat(rt, bot, {sessionId: 'private-head', segments: [{sessionId: 'private-root'}]}) const events = new EventEmitter() @@ -170,7 +171,8 @@ test('cancellation stays bound to the selected live Session and a later turn can const sessionId = livePrivateChat(rt, bot.id, 'private-root') const controller = new AbortController() const reason = new Error('stopped by user') - const cancelled = runTurn(rt, ctx, bot.id, 'first', 'stop', undefined, [], {sessionId, signal: controller.signal}) + const cancelled = runTurn(rt, ctx, bot.id, 'first', 'stop', 100, [], {sessionId, signal:controller.signal, interactive:true}) + t.mock.timers.tick(150) controller.abort(reason) await assert.rejects(cancelled, error => error === reason) const resumed = await runTurn(rt, ctx, bot.id, 'second', 'resume', undefined, [], {sessionId}) @@ -178,3 +180,108 @@ test('cancellation stays bound to the selected live Session and a later turn can assert.deepEqual(selected, [['send', sessionId, 'stop'], ['cancel', sessionId], ['send', sessionId, 'resume']]) assert.equal(bot.sessionId, 'foreground') }) + +function bridgedTurn(options = {}) { + const {rt, bot} = fixture() + const events = new EventEmitter() + const ctx = {on(name, fn) { events.on(name, fn); return () => events.off(name, fn) }} + const session = {id:bot.sessionId} + const sessionEvent = (type, data, target = session) => events.emit('session/event', target, {type,data}) + const echo = (rpcId = 'my-request', target = session) => sessionEvent('user/message', {source:{rpcId}}, target) + rt.displayItems = (_, [event]) => event.type === 'assistant/message' ? [{kind:'bot',text:event.data.text}] : [] + rt.sendUser = async () => { + rt.live.set(session.id, {turn:1}) + sessionEvent('turn/start', {turn:1}) + } + const reply = runTurn(rt, ctx, bot.id, 'first', 'my-request', 100, [], {sessionId:session.id, ...options}) + return {rt, events, session, sessionEvent, echo, reply} +} + +test('an interactive reply can stream and finish after the admission deadline', async t => { + t.mock.timers.enable({apis:['setTimeout']}) + const phases = [] + const {echo, events, session, sessionEvent, reply} = bridgedTurn({interactive:true, onPhase:phase => phases.push(phase)}) + echo() + t.mock.timers.tick(101) + const agent = {id:session.id, session} + events.emit('agent/assistant-stream', {agent, frame:{type:'start', turn:1, attemptId:'draft', step:1, revision:1}}) + events.emit('agent/assistant-stream', {agent, frame:{type:'chunk', attemptId:'draft', revision:2, chunk:{type:'text-delta', text:'working'}}}) + t.mock.timers.tick(200) + sessionEvent('assistant/message', {turn:1, text:'completed reply'}) + sessionEvent('turn/end', {turn:1, turnId:'finished'}) + assert.deepEqual(phases, ['writing']) + assert.deepEqual(await reply, {text:'completed reply', sessionId:session.id, turnId:'finished'}) + assert.equal(events.eventNames().length, 0) +}) + +test('only an exact native echo can clear the interactive admission deadline', async t => { + t.mock.timers.enable({apis:['setTimeout']}) + const {echo, session, reply} = bridgedTurn({interactive:true}) + const timedOut = assert.rejects(reply, /turn timed out/) + echo('other-request') + echo('my-request', {id:'other-session'}) + echo('my-request', {id:session.id}) + t.mock.timers.tick(100) + await timedOut +}) + +test('fixed turn deadlines still apply to background and managed group calls after native echo', async t => { + t.mock.timers.enable({apis:['setTimeout']}) + for (const options of [{}, {interactive:true, managedGroup:true}]) { + const {echo, events, reply} = bridgedTurn(options) + const timedOut = assert.rejects(reply, /turn timed out/) + echo() + t.mock.timers.tick(100) + await timedOut + assert.equal(events.eventNames().length, 0) + } +}) + +test('disposal settles only the exact admitted Session without requiring a stream frame', async t => { + t.mock.timers.enable({apis:['setTimeout']}) + const {echo, events, session, reply} = bridgedTurn({interactive:true}) + echo() + t.mock.timers.tick(150) + let rejected = false + const expectDisposal = assert.rejects(reply, {code:'agents/empty-reply'}).then(() => { rejected = true }) + events.emit('agent/disposed', {agent:{id:session.id, session:{id:session.id}}}) + await Promise.resolve() + assert.equal(rejected, false) + assert.equal(events.listenerCount('agent/disposed'), 1) + events.emit('agent/disposed', {agent:{id:session.id, session}}) + await expectDisposal + assert.equal(events.eventNames().length, 0) +}) + +test('stopping an admitted reply does not cancel a later native turn', async t => { + t.mock.timers.enable({apis:['setTimeout']}) + const controller = new AbortController() + const {rt, echo, events, session, reply} = bridgedTurn({interactive:true, signal:controller.signal}) + let cancelled = false + rt.resolveAgent = async () => ({session, cancel:() => { cancelled = true }}) + echo() + t.mock.timers.tick(150) + rt.live.set(session.id, {turn:2}) + const reason = new Error('stopped by user') + controller.abort(reason) + await assert.rejects(reply, error => error === reason) + assert.equal(cancelled, false) + assert.equal(events.eventNames().length, 0) +}) + +test('a stopped interactive reply settles if native cancellation produces no terminal event', async t => { + t.mock.timers.enable({apis:['setTimeout']}) + const controller = new AbortController() + const {rt, echo, events, session, reply} = bridgedTurn({interactive:true, signal:controller.signal}) + const attempted = Promise.withResolvers() + rt.resolveAgent = async () => ({session, cancel:attempted.resolve}) + echo() + t.mock.timers.tick(150) + const reason = new Error('stopped by user') + const stopped = assert.rejects(reply, error => error === reason) + controller.abort(reason) + await attempted.promise + t.mock.timers.tick(30_000) + await stopped + assert.equal(events.eventNames().length, 0) +}) diff --git a/tests/chat_page.test.mjs b/tests/chat_page.test.mjs index c7ea8aa18..e4a91255c 100644 --- a/tests/chat_page.test.mjs +++ b/tests/chat_page.test.mjs @@ -1357,10 +1357,10 @@ for (const deliveredBeforeAck of [false, true]) { }); } -test('a streaming reply can be stopped before a delayed send acknowledgment', async t => { +test('a long native reply keeps its partial text and Stop when the stream disconnects', async t => { t.mock.timers.enable({apis: ['setTimeout']}); const post = Promise.withResolvers(); - let sendKey, ack, historyReads = 0, receiptReads = 0; + let sendKey, ack, historyReads = 0, receiptReads = 0, fallbackReads = 0; const stopped = []; const {doc, el, restore, fetcher} = nativeReplyChat((path, opts, scope) => { if (path === '?limit=50') { @@ -1380,6 +1380,11 @@ test('a streaming reply can be stopped before a delayed send acknowledgment', as receiptReads++; return json(200, {...ack, state:'running'}); } + if (path === '/reply-progress?key=' + sendKey + '&after=1') { + fallbackReads++; + if (fallbackReads === 1) return json(200, {state:'running', text:''}); + return json(200, {state:'running', revision:2, phase:'writing', text:'已收到部分内容,继续工作中'}); + } if (path === '/reply-stop' && opts.method === 'POST') { stopped.push(JSON.parse(opts.body)); return json(200, {...ack, reply:{...ack.reply, status:'cancelled', can_stop:false}}); @@ -1392,7 +1397,7 @@ test('a streaming reply can be stopped before a delayed send acknowledgment', as constructor() { streams.push(this); } addEventListener(name, fn) { this.handlers.set(name, fn); } close() { this.closed = true; } - running(text) { this.handlers.get('message')({data:JSON.stringify({state:'running', phase:'writing', text})}); } + running(text) { this.handlers.get('message')({data:JSON.stringify({state:'running', revision:1, phase:'writing', text})}); } }}; try { await mount(doc, {fetcher}); @@ -1414,6 +1419,27 @@ test('a streaming reply can be stopped before a delayed send acknowledgment', as assert.equal(streams[0].closed, undefined); assert.deepEqual(list.children.map(row => row.dataset.messageId), [ack.message.id, ack.reply.id]); assert.equal(list.children.at(-1).children.at(-1).textContent, '已收到部分内容'); + for (let elapsed = 0; elapsed < 190_000; elapsed += 10_000) { + t.mock.timers.tick(10_000); + streams[0].handlers.get('heartbeat')(); + await settle(); + } + assert.equal(streams[0].closed, undefined); + assert.equal(fallbackReads, 0); + streams[0].handlers.get('error')(); + t.mock.timers.tick(0); + await settle(); + assert.equal(fallbackReads, 1); + assert.equal(list.children.at(-1).children.at(-1).textContent, '已收到部分内容'); + assert.equal(stop.hidden, false); + t.mock.timers.tick(749); + await settle(); + assert.equal(fallbackReads, 1, 'unchanged fallback progress is paced'); + t.mock.timers.tick(120_000); + await settle(); + assert.equal(fallbackReads, 2); + assert.equal(list.children.at(-1).children.at(-1).textContent, '已收到部分内容,继续工作中'); + assert.equal(stop.hidden, false); await fire(stop, 'click'); assert.deepEqual(stopped, [{key:sendKey, attempt:1}]); assert.equal(stop.hidden, true);