${escapeHTML(a.name)}
${escapeHTML(exec?.name||a.executorId||'未选 CLI')}${a.model?` · ${escapeHTML(a.model)}`:''}${a.loop?.enabled?` · ${a.loop.maxIterations||1} 轮`:''}${escapeHTML(a.description||'尚未填写职责说明')}
diff --git a/e2e/tests/02-navigation.spec.js b/e2e/tests/02-navigation.spec.js
index 168de651..9214bdb6 100644
--- a/e2e/tests/02-navigation.spec.js
+++ b/e2e/tests/02-navigation.spec.js
@@ -1,16 +1,20 @@
const { test, expect } = require('@playwright/test');
-const { watchErrors, login } = require('./helpers');
+const { watchErrors, login, openView } = require('./helpers');
+
+const SIDEBAR = ['chat', 'rooms', 'issues', 'sops', 'agents', 'sandboxes', 'metrics', 'observability', 'knowledge', 'settings'];
+const SUBVIEWS = ['runs', 'approvals', 'flow', 'skills', 'mcp', 'rules', 'dockerfiles', 'environments', 'projects', 'runners', 'guide', 'businessDomains', 'businessDomainManagement', 'platform'];
test('every view renders without errors or failed requests', async ({ page }) => {
const errors = watchErrors(page);
await login(page);
- const views = await page.$$eval('[data-view]', els => [...new Set(els.map(e => e.dataset.view))]);
+ const plugins = await page.$$eval('#pluginNavGroup [data-view]', els => els.map(e => e.dataset.view));
+ const views = [...new Set([...SIDEBAR, ...SUBVIEWS, ...plugins])];
expect(views.length).toBeGreaterThanOrEqual(15);
for (const view of views) {
await test.step(view, async () => {
- const nav = page.locator(`[data-view="${view}"]:visible`).first();
- if (await nav.count()) await nav.click();
- else await page.evaluate(v => { location.hash = `#/${v}`; }, view);
+ const nav = page.locator(`.nav[data-view="${view}"]:visible`);
+ if (await nav.count()) await nav.first().click();
+ else await openView(page, view);
const container = ['rules', 'skills', 'dockerfiles', 'environments', 'sandboxes'].includes(view) ? 'assets' : view;
await expect(page.locator(`#${container}View`)).toBeVisible();
await page.waitForLoadState('networkidle');
@@ -21,7 +25,7 @@ test('every view renders without errors or failed requests', async ({ page }) =>
test('the MCP market lists public servers and GitHub is installed by default', async ({ page }) => {
await login(page);
- await page.evaluate(() => { location.hash = '#/mcp'; });
+ await openView(page, 'mcp');
await expect(page.locator('#mcpView')).toContainText('GitHub');
await expect(page.locator('#mcpView')).toContainText('Context7');
await expect(page.locator('#mcpView')).toContainText('已添加');
diff --git a/e2e/tests/06-extensions.spec.js b/e2e/tests/06-extensions.spec.js
index f558ce69..d4bc5b33 100644
--- a/e2e/tests/06-extensions.spec.js
+++ b/e2e/tests/06-extensions.spec.js
@@ -1,5 +1,5 @@
const { test, expect } = require('@playwright/test');
-const { watchErrors, login } = require('./helpers');
+const { watchErrors, login, openView } = require('./helpers');
// e2e/serve.sh loads everything under examples/extensions.
@@ -57,8 +57,7 @@ test('custom MCP market entries are listed and searchable', async ({ page }) =>
const market = await page.evaluate(() => fetch('/api/mcp-market?q=kb').then(r => r.json()));
expect(market.items.map(i => i.id)).toContain('team-knowledge');
- if (await page.locator('[data-nav-group="config"]').getAttribute('aria-expanded') !== 'true') await page.locator('[data-nav-group="config"]').click();
- await page.locator('.nav[data-view="mcp"]').click();
+ await openView(page, 'mcp');
await page.locator('#mcpMarketSearch').fill('Team knowledge');
const card = page.locator('.mcp-market-card').filter({ hasText: 'Team knowledge base (example)' });
await expect(card).toBeVisible();
diff --git a/e2e/tests/08-knowledge.spec.js b/e2e/tests/08-knowledge.spec.js
index 8717db1c..843c603d 100644
--- a/e2e/tests/08-knowledge.spec.js
+++ b/e2e/tests/08-knowledge.spec.js
@@ -8,7 +8,7 @@ test('an admin connects a knowledge base without the token appearing in the page
await page.locator('.nav[data-view="knowledge"]').click();
const view = page.locator('#knowledgeView');
await expect(view).toBeVisible();
- await expect(page.locator('#pageTitle')).toHaveText('知识中心');
+ await expect(page.locator('#pageTitle')).toHaveText('知识库');
await expect(view).toContainText('未接入');
for (const tab of ['接入配置', '节点使用', '知识沉淀', '检索试用']) {
await expect(view.locator(`[data-kb-tab]`).filter({ hasText: tab })).toBeVisible();
diff --git a/e2e/tests/09-sop-runs.spec.js b/e2e/tests/09-sop-runs.spec.js
index a297005a..9f5ee667 100644
--- a/e2e/tests/09-sop-runs.spec.js
+++ b/e2e/tests/09-sop-runs.spec.js
@@ -1,5 +1,5 @@
const { test, expect } = require('@playwright/test');
-const { watchErrors, login, visibleButton, api, waitForRun, closeDrawer, useScriptProject } = require('./helpers');
+const { watchErrors, login, visibleButton, api, waitForRun, closeDrawer, useScriptProject, openView } = require('./helpers');
async function createBlankSOP(page, name) {
await useScriptProject(page);
@@ -70,7 +70,7 @@ test('a shell SOP designed in the editor runs in the local sandbox and keeps its
expect(artifact).toContain('e2e-browser-marker');
await closeDrawer(page);
- await page.locator('.nav[data-view="runs"]').click();
+ await openView(page, 'runsDone');
await expect(page.locator('#runList')).toContainText('浏览器:脚本 SOP 真跑');
await page.locator('.run-card', { hasText: '浏览器:脚本 SOP 真跑' }).click();
await expect(page.locator('#runsDetailSection, #runDetail, .run-detail-main').first()).toBeVisible();
@@ -100,7 +100,7 @@ test('an approval gate stops a real run until 待我确认 lets it continue', as
const task = (await api(page, '/api/tasks')).find(item => item.issueId === issue.id);
await closeDrawer(page);
- await page.locator('.nav[data-view="approvals"]').click();
+ await openView(page, 'approvals');
const card = page.locator('#approvalList .ap-card', { hasText: '浏览器:审批后继续' });
await expect(card).toBeVisible();
await card.locator('button', { hasText: '确认通过,继续下游' }).click();
@@ -137,7 +137,7 @@ test('a script that exits non-zero fails the run and can be cancelled while slee
const task = (await api(page, '/api/tasks')).find(item => item.issueId === issue.id);
await waitForRun(page, task.runId, /running/);
await closeDrawer(page);
- await page.locator('.nav[data-view="runs"]').click();
+ await openView(page, 'runs');
await page.locator('.run-card', { hasText: '浏览器:取消睡眠' }).click();
await page.locator('[data-cancel-run]').click();
await page.locator('#confirmOkBtn').click();
diff --git a/e2e/tests/10-catalog.spec.js b/e2e/tests/10-catalog.spec.js
index e9841221..6b5b305c 100644
--- a/e2e/tests/10-catalog.spec.js
+++ b/e2e/tests/10-catalog.spec.js
@@ -58,7 +58,7 @@ test('a project, a custom MCP and the personal pages render their working contro
const errors = watchErrors(page);
await login(page);
- await page.locator('.nav[data-view="projects"]').click();
+ await openView(page, 'projects');
await page.locator('#newProject').click();
const project = page.locator('#projectAdminForm');
await project.locator('[name=id]').fill('browser-proj');
@@ -80,9 +80,9 @@ test('a project, a custom MCP and the personal pages render their working contro
await page.locator('.nav[data-view="settings"]').click();
await expect(page.locator('#settingsView .settings-tab.active')).toHaveText('模型 Key');
- await page.locator('.nav[data-view="runners"]').click();
+ await openView(page, 'runners');
await expect(page.locator('#bindToken')).not.toHaveText('生成中…', { timeout: 15_000 });
- await page.locator('.nav[data-view="guide"]').click();
+ await openView(page, 'guide');
await expect(page.locator('#guideView')).toBeVisible();
await page.locator('.nav[data-view="metrics"]').click();
await expect(page.locator('#metricsBody')).toBeVisible();
diff --git a/e2e/tests/11-rooms-schedule.spec.js b/e2e/tests/11-rooms-schedule.spec.js
index 02955ad4..83a66012 100644
--- a/e2e/tests/11-rooms-schedule.spec.js
+++ b/e2e/tests/11-rooms-schedule.spec.js
@@ -12,7 +12,7 @@ test('a room can chat and dispatch a published script SOP', async ({ page }) =>
expect(sop, 'script SOP from the designer test').toBeTruthy();
await page.locator('.nav[data-view="rooms"]').click();
- await expect(page.locator('#pageTitle')).toHaveText('协作群聊');
+ await expect(page.locator('#pageTitle')).toHaveText('群聊');
await page.locator('#newRoom').click();
await page.locator('#confirmPromptInput').fill('浏览器值班群');
await page.locator('#confirmOkBtn').click();
diff --git a/e2e/tests/12-workspace-features.spec.js b/e2e/tests/12-workspace-features.spec.js
index e549d04d..f6952ce7 100644
--- a/e2e/tests/12-workspace-features.spec.js
+++ b/e2e/tests/12-workspace-features.spec.js
@@ -1,5 +1,5 @@
const { test, expect } = require('@playwright/test');
-const { ADMIN, watchErrors, login, visibleButton, api, closeDrawer, useScriptProject } = require('./helpers');
+const { ADMIN, watchErrors, login, visibleButton, api, closeDrawer, useScriptProject, openView } = require('./helpers');
async function openIssue(page, title) {
await page.locator('.nav[data-view="issues"]').click();
@@ -54,7 +54,7 @@ test('first login tours the sidebar and ends on the settings page that still nee
await expect(page.locator('#onboarding')).toBeHidden();
await expect(page.locator('#setupWizard')).toHaveCount(0);
- await page.locator('.nav[data-view="guide"]').click();
+ await openView(page, 'guide');
await page.locator('#replayOnboarding').click();
await expect(page.locator('#onboardingKicker')).toHaveText('1 / 6');
await page.keyboard.press('Escape');
@@ -68,8 +68,8 @@ test('the chat page demo shows progress in the side panel', async ({ page }) =>
await login(page);
await page.locator('.nav[data-view="chat"]').click();
const home = page.locator('#homeChat');
- await expect(home.locator('.hc-key-hint')).toBeVisible();
- await home.locator('.hc-key-hint [data-chat-action="demo"]').click();
+ await expect(home.locator('.hc-key-line')).toBeVisible();
+ await home.locator('.hc-key-line [data-chat-action="demo"]').click();
await expect(home.locator('.hc-msg.is-bot').last()).toContainText('已按「演示交付流程」开跑', { timeout: 15_000 });
await expect(page.locator('#issueDetailDrawer')).toBeHidden();
@@ -97,7 +97,7 @@ test('the chat page demo shows progress in the side panel', async ({ page }) =>
test('the quick-start demo button runs the demo SOP end to end', async ({ page }) => {
const errors = watchErrors(page);
await login(page);
- await page.locator('.nav[data-view="guide"]').click();
+ await openView(page, 'guide');
const quickstart = page.locator('#quickstartCard');
await expect(quickstart).toBeVisible();
await expect(quickstart).toContainText('先体验一遍');
@@ -108,10 +108,14 @@ test('the quick-start demo button runs the demo SOP end to end', async ({ page }
await expect(visibleButton(page, '确认通过,继续下游')).toBeVisible({ timeout: 30_000 });
await visibleButton(page, '确认通过,继续下游').click();
await expect(drawer).toContainText('已完成', { timeout: 30_000 });
+ await expect.poll(async () => {
+ const runs = await api(page, '/api/runs');
+ return runs.some(run => run.status === 'succeeded' && (run.workflowId === 'demo-delivery' || run.workflowSnapshot?.id === 'demo-delivery'));
+ }, { timeout: 30_000 }).toBe(true);
await closeDrawer(page);
await page.locator('.nav[data-view="issues"]').click();
- await page.locator('.nav[data-view="guide"]').click();
+ await openView(page, 'guide');
await expect(quickstart.locator('.qs-demo .qs-step.is-done')).toHaveCount(2, { timeout: 15_000 });
expect(errors).toEqual([]);
});
@@ -166,7 +170,7 @@ test('a business domain is created, assigned to a project and reported', async (
await login(page);
await useProject(page, 'e2e-bd-ui', '业务域浏览器项目');
- await page.locator('.nav[data-view="businessDomainManagement"]').click();
+ await openView(page, 'businessDomainManagement');
await expect(page.locator('#pageTitle')).toHaveText('领域管理');
const form = page.locator('#businessDomainForm');
await expect(form).toBeVisible();
@@ -178,7 +182,7 @@ test('a business domain is created, assigned to a project and reported', async (
await expect(page.locator('#toastContainer')).toContainText('业务域已保存');
await expect(page.locator('[data-business-domain="e2e-ui-growth"]')).toBeVisible();
- await page.locator('.nav[data-view="projects"]').click();
+ await openView(page, 'projects');
const projectForm = page.locator('#projectAdminForm');
await expect(projectForm.locator('[name=id]')).toHaveValue('e2e-bd-ui');
await projectForm.locator('#projectBusinessDomainSelect').selectOption('e2e-ui-growth');
@@ -187,7 +191,7 @@ test('a business domain is created, assigned to a project and reported', async (
const history = await api(page, '/api/projects/e2e-bd-ui/business-domain/history');
expect(JSON.stringify(history)).toContain('e2e-ui-growth');
- await page.locator('.nav[data-view="businessDomains"]').click();
+ await openView(page, 'businessDomains');
await expect(page.locator('#pageTitle')).toHaveText('业务领域');
const filter = page.locator('#businessReportFilter');
await expect(filter.locator('select[name=scope] option[value="e2e-ui-growth"]')).toHaveCount(1);
@@ -204,7 +208,7 @@ test('usage analytics manages external sources and filters by execution origin',
await login(page);
await useProject(page, 'e2e-ext-ui', '外部数据源浏览器项目');
await page.locator('.nav[data-view="observability"]').click();
- await expect(page.locator('#pageTitle')).toHaveText('用量分析');
+ await expect(page.locator('#pageTitle')).toHaveText('成本');
await page.locator('#obsManageSources').click();
const dialog = page.locator('dialog.obs-source-dialog');
@@ -311,8 +315,10 @@ test('a room lists only SOPs and expands the remainder on demand', async ({ page
await page.locator('#confirmPromptInput').fill('浏览器 SOP 列表群');
await page.locator('#confirmOkBtn').click();
await expect(page.locator('#roomTitle')).toContainText('浏览器 SOP 列表群');
+ await page.locator('#toggleRoomInfo').click();
const list = page.locator('#roomSOPList');
+ await expect(list).toBeVisible();
await expect(list.locator('[data-room-pick]')).toHaveCount(4);
const expand = list.locator('[data-room-sop-expand="expand"]');
await expect(expand).toHaveText(/^展开其余 \d+ 条$/);
@@ -340,7 +346,7 @@ test('switching projects never shows the previous project metrics', async ({ pag
if (url.pathname === '/api/analytics' && url.searchParams.get('requirementsOnly') === '1') seen.push(url.searchParams.get('projectId'));
});
await page.locator('.nav[data-view="metrics"]').click();
- await expect(page.locator('#pageTitle')).toHaveText('研发效能');
+ await expect(page.locator('#pageTitle')).toHaveText('运行洞察');
await expect.poll(() => seen.includes('e2e-script')).toBe(true);
await page.locator('#projectSwitcher').selectOption('platform');
diff --git a/e2e/tests/13-pages-and-settings.spec.js b/e2e/tests/13-pages-and-settings.spec.js
index c84a34c9..ac9d1f16 100644
--- a/e2e/tests/13-pages-and-settings.spec.js
+++ b/e2e/tests/13-pages-and-settings.spec.js
@@ -7,16 +7,19 @@ test('the home page is the chat: no dashboard, attachments, @ mentions and no su
await expect(page.locator('#pageTitle')).toHaveText('首页');
await expect(page.locator('#dashboardView')).toHaveCount(0);
const home = page.locator('#homeChat');
- await expect(home.locator('.hc-brand')).toHaveText('LoopForge');
+ await expect(home.locator('.hc-headline')).toHaveText('今天想交付什么?');
await expect(page.locator('#homeChatInput')).toBeVisible();
await expect(home.locator('#hcRuns')).toContainText('正在运行');
await page.goto('/#/dashboard');
await expect(page.locator('#pageTitle')).toHaveText('首页');
- const cards = home.locator('[data-home-sop]');
- expect(await cards.count()).toBeGreaterThan(1);
- await cards.nth(1).click();
- await expect(home.locator('[data-home-sop]').nth(1)).toHaveClass(/is-selected/);
+ const sop = home.locator('#homeSopSelect');
+ await expect(sop.locator('option')).not.toHaveCount(0);
+ const nextSop = await sop.locator('option').nth(1).getAttribute('value');
+ if (nextSop) {
+ await sop.selectOption(nextSop);
+ await expect(sop).toHaveValue(nextSop);
+ }
// Attach a file through the picker; it uploads right away and shows in the tray.
await page.locator('#homeChatFile').setInputFiles({ name: 'notes.md', mimeType: 'text/markdown', buffer: Buffer.from('# 备注\n导出要带表头') });
@@ -44,7 +47,7 @@ test('the home page is the chat: no dashboard, attachments, @ mentions and no su
await expect(page.locator('#issueDetailDrawer')).toBeHidden();
await home.locator('#homeChatNew').click();
- await expect(home.locator('.hc-brand')).toBeVisible();
+ await expect(home.locator('.hc-headline')).toBeVisible();
await expect(page.locator('.nav[data-view="chat"]')).toHaveClass(/active/);
// The top-bar AI assistant button lands here too.
diff --git a/e2e/tests/14-phase1-surface.spec.js b/e2e/tests/14-phase1-surface.spec.js
new file mode 100644
index 00000000..f56b3c7f
--- /dev/null
+++ b/e2e/tests/14-phase1-surface.spec.js
@@ -0,0 +1,105 @@
+const { test, expect } = require('@playwright/test');
+const { watchErrors, login } = require('./helpers');
+
+test('phase 1 sidebar, command palette, destructive confirm and stream states', async ({ page }) => {
+ const errors = watchErrors(page);
+ await login(page);
+
+ const side = page.locator('.platform-sidebar');
+ await expect(side.locator('.nav-section', { hasText: '工作' })).toBeVisible();
+ await expect(side).toContainText('配置');
+ await expect(side).toContainText('洞察');
+ await expect(side.locator('.nav[data-view="issues"] .nav-label')).toHaveText('SOP 运行');
+ await expect(side.locator('.nav[data-view="rooms"] .nav-label')).toHaveText('群聊');
+ await expect(side.locator('.nav[data-view="agents"] .nav-label')).toHaveText('Bot');
+ await expect(side.locator('.nav[data-view="sandboxes"] .nav-label')).toHaveText('环境');
+ await expect(side.locator('.nav[data-view="metrics"] .nav-label')).toHaveText('运行洞察');
+ await expect(side.locator('.nav[data-view="observability"] .nav-label')).toHaveText('成本');
+ await expect(side.locator('#commandPaletteTrigger')).toContainText('搜索或跳转');
+ await expect(page.locator('#roomSaveSOP')).toHaveText('存为 SOP');
+
+ await page.locator('#commandPaletteTrigger').click();
+ await expect(page.locator('#commandPalette')).toBeVisible();
+ await expect(page.locator('.command-footer')).toContainText('筛选类型');
+ await page.keyboard.press('Escape');
+ await expect(page.locator('#commandPalette')).toBeHidden();
+
+ const confirmed = page.evaluate(() => afConfirm({
+ title: '删除知识库「竞品资料库」?',
+ message: '此操作不可撤销。',
+ confirmText: '删除知识库',
+ danger: true,
+ confirmName: '竞品资料库',
+ }));
+ const ok = page.locator('#confirmOkBtn');
+ await expect(ok).toBeDisabled();
+ await expect(ok).toHaveClass(/danger-outline/);
+ await expect(ok).not.toHaveCSS('background-color', 'rgb(225, 29, 72)');
+ await page.locator('#confirmNameInput').fill('别的名字');
+ await expect(ok).toBeDisabled();
+ await page.locator('#confirmNameInput').fill('竞品资料库');
+ await expect(ok).toBeEnabled();
+ await ok.click();
+ expect(await confirmed).toBe(true);
+
+ await page.locator('.nav[data-view="rooms"]').click();
+ await page.waitForLoadState('networkidle');
+ await page.evaluate(() => lfPreviewRoomStream({ phase: 'queue', name: '研究员' }));
+ await expect(page.locator('.rm-stream').last()).toContainText('排队中');
+ await page.evaluate(() => lfPreviewRoomStream({ phase: 'think', name: '研究员' }));
+ await expect(page.locator('.rm-stream').last()).toContainText('思考中');
+ await page.evaluate(() => lfPreviewRoomStream({ phase: 'slow', name: '研究员' }));
+ const slow = page.locator('.rm-stream.is-slow');
+ await expect(slow).toContainText('仍在处理');
+ await expect(slow.locator('[data-stream-stop]')).toBeVisible();
+ await expect(slow.locator('[data-stream-retry]')).toBeVisible();
+ await expect(page.locator('.workspace-spinner, .page-spinner')).toHaveCount(0);
+ await page.evaluate(() => lfPreviewRoomStream({ phase: 'error', error: '缺少 API Key', name: '研究员' }));
+ const card = page.locator('.rm-error-card');
+ await expect(card).toContainText('配置 Key');
+ await expect(card).toContainText('换个 Bot');
+ await expect(card).toContainText('重试');
+
+ const badge = await page.evaluate(() => {
+ const user = typeof userById === 'function' ? userById(state.currentUser?.id) : null;
+ if (user) {
+ user.codeBuddyApiKeyConfigured = false;
+ user.codexApiKeyConfigured = false;
+ user.claudeCodeApiKeyConfigured = false;
+ }
+ const host = document.createElement('div');
+ host.innerHTML = lfStatusBadge({ id: 'missing-key', name: '研究员' });
+ document.body.appendChild(host);
+ const badgeEl = host.querySelector('.lf-status');
+ const dot = host.querySelector('i');
+ const bg = getComputedStyle(dot).backgroundColor;
+ return { text: host.textContent, bg, off: badgeEl.className };
+ });
+ expect(badge.text).toContain('缺 Key');
+ expect(badge.off).toContain('lf-status-off');
+ expect(badge.bg).not.toBe('rgb(229, 72, 77)');
+ expect(badge.bg).not.toBe('rgb(242, 85, 90)');
+
+ const ia = await page.evaluate(() => {
+ const subs = (VIEW_TABSETS.find(set => set.nav === 'issues')?.tabs?.[0]?.subs || []).map(item => item[1]);
+ const mock = lfBotStatus({id: 'lf-demo-exec-probe', name: '演示执行器', executorId: 'mock'});
+ return {
+ zones: [...document.querySelectorAll('.room-zone-k, #roomSaveSOP')].map(el => el.textContent.trim()),
+ subs,
+ approvals: document.querySelector('#approvalsView h1')?.textContent.trim(),
+ mock: `${mock.label} ${mock.key}`,
+ };
+ });
+ expect(ia.zones).toEqual(['成员状态', '费用·进度', '存为 SOP']);
+ expect(ia.subs).toEqual(['进行中', '待确认', '已完成', '需求']);
+ expect(ia.approvals).toBe('待确认');
+ expect(ia.mock).toBe('可用 ok');
+
+ const dark = await page.evaluate(() => {
+ document.documentElement.dataset.theme = 'dark';
+ return getComputedStyle(document.documentElement).getPropertyValue('--lf-bg').trim();
+ });
+ expect(dark.toLowerCase()).toBe('#08090c');
+
+ expect(errors).toEqual([]);
+});
diff --git a/e2e/tests/15-phase2-stream.spec.js b/e2e/tests/15-phase2-stream.spec.js
new file mode 100644
index 00000000..12b84c44
--- /dev/null
+++ b/e2e/tests/15-phase2-stream.spec.js
@@ -0,0 +1,46 @@
+const { test, expect } = require('@playwright/test');
+const { watchErrors, login, api } = require('./helpers');
+
+test('room SSE shows a first token quickly and a stall strip with stop', async ({ page }) => {
+ test.setTimeout(40_000);
+ const errors = watchErrors(page, { allow: [/EventSource/, /net::ERR_/, /messages\/.*\/stream/] });
+ await login(page);
+ await page.locator('.nav[data-view="rooms"]').click();
+ await expect(page.locator('#pageTitle')).toHaveText('群聊');
+ await page.locator('#newRoom').click();
+ await page.locator('#confirmPromptInput').fill('流式验收群');
+ await page.locator('#confirmOkBtn').click();
+ await expect(page.locator('#roomTitle')).toContainText('流式验收群');
+
+ const roomId = await page.evaluate(() => roomState().activeId);
+ const fast = await api(page, '/api/rooms/' + roomId + '/messages', {
+ method: 'POST',
+ body: {
+ body: '@LoopForge 你好',
+ fakeModel: { text: '甲乙丙丁', firstTokenMs: 200, tokenMs: 30 },
+ },
+ });
+ expect(fast.id).toBeTruthy();
+ const started = Date.now();
+ await page.evaluate(() => refreshRoomMessages(true));
+ await expect(page.locator('#roomLog')).toContainText('甲', { timeout: 1500 });
+ expect(Date.now() - started).toBeLessThan(1500);
+ await expect(page.locator('#roomLog')).toContainText('甲乙丙丁');
+
+ await api(page, '/api/rooms/' + roomId + '/messages', {
+ method: 'POST',
+ body: {
+ body: '@LoopForge 什么进度',
+ fakeModel: { text: '戊己庚', firstTokenMs: 80, tokenMs: 20, stallAfter: 1, stallMs: 12000 },
+ },
+ });
+ await page.evaluate(() => refreshRoomMessages(true));
+ await expect(page.locator('#roomLog')).toContainText('戊');
+ const slow = page.locator('#roomLog .rm-stream.is-slow').last();
+ await expect(slow).toContainText('仍在处理,已用', { timeout: 12_000 });
+ await expect(slow.locator('[data-stream-stop]')).toBeVisible();
+ await expect(slow.locator('[data-stream-retry]')).toBeVisible();
+ await slow.locator('[data-stream-stop]').click();
+ await expect(slow).toBeHidden({ timeout: 3000 });
+ expect(errors).toEqual([]);
+});
diff --git a/e2e/tests/16-phase3-demo.spec.js b/e2e/tests/16-phase3-demo.spec.js
new file mode 100644
index 00000000..8b54497a
--- /dev/null
+++ b/e2e/tests/16-phase3-demo.spec.js
@@ -0,0 +1,60 @@
+const { test, expect } = require('@playwright/test');
+const { watchErrors, login, api } = require('./helpers');
+
+test('demo path: command palette, example crew, save SOP, fail-resume, stall', async ({ page }) => {
+ test.setTimeout(90_000);
+ const errors = watchErrors(page, { allow: [/EventSource/, /net::ERR_/, /messages\/.*\/stream/] });
+ await login(page);
+
+ await page.locator('#commandPaletteTrigger').click();
+ await expect(page.locator('#commandResults')).toContainText('最近');
+ await expect(page.locator('#commandResults')).toContainText('常用动作');
+ await page.locator('#commandSearch').fill('群聊');
+ await expect(page.locator('.command-kind', { hasText: '群聊' }).first()).toBeVisible();
+ await page.locator('#commandSearch').fill('组件');
+ await page.locator('#commandResults button', { hasText: '组件' }).first().click();
+ await expect(page.locator('#pageTitle')).toHaveText('组件');
+ const gallery = page.locator('#galleryView');
+ await expect(gallery.locator('.button.danger-outline')).toBeVisible();
+ await expect(gallery.locator('.lf-status-ok')).toContainText('可用');
+ await expect(gallery.locator('.lf-status-busy')).toContainText('忙');
+ await expect(gallery.locator('.lf-status-off')).toContainText('缺 Key');
+
+ await page.locator('.nav[data-view="chat"]').click();
+ await expect(page.locator('.hc-live-strip')).toContainText('进行中');
+ await page.locator('.hc-example', { hasText: '多 Bot 做登录页' }).click();
+ await expect(page.locator('#pageTitle')).toHaveText('群聊');
+ await expect(page.locator('#roomLog')).toContainText('结论', { timeout: 8000 });
+ await expect(page.locator('#roomLog')).toContainText('搞定了', { timeout: 15000 });
+ await page.locator('#roomSaveSOP').click();
+ await expect(page.locator('#roomLog')).toContainText('已沉淀成 SOP', { timeout: 8000 });
+
+ const roomId = await page.evaluate(() => roomState().activeId);
+ await api(page, '/api/rooms/' + roomId + '/messages', {
+ method: 'POST',
+ body: {
+ body: '@LoopForge 实现导出按钮',
+ fakeModel: { crewStep: true, failStep: 1, firstTokenMs: 40, tokenMs: 4 },
+ },
+ });
+ await page.evaluate(() => refreshRoomMessages(true));
+ const card = page.locator('#roomLog .rm-error-card').last();
+ await expect(card).toContainText('重试', { timeout: 8000 });
+ await card.locator('[data-err-act="retry"]').click();
+ await expect(page.locator('#roomLog')).toContainText('再试一次', { timeout: 8000 });
+
+ await api(page, '/api/rooms/' + roomId + '/messages', {
+ method: 'POST',
+ body: {
+ body: '@LoopForge 实现暂停条',
+ fakeModel: { crewStep: true, text: '甲乙丙丁', firstTokenMs: 80, tokenMs: 20, stallAfter: 1, stallMs: 12000 },
+ },
+ });
+ await page.evaluate(() => refreshRoomMessages(true));
+ await expect(page.locator('#roomLog')).toContainText('甲', { timeout: 1500 });
+ const slow = page.locator('#roomLog .rm-stream.is-slow').last();
+ await expect(slow).toContainText('仍在处理,已用', { timeout: 12_000 });
+ await slow.locator('[data-stream-stop]').click();
+ await expect(slow).toBeHidden({ timeout: 4000 });
+ expect(errors).toEqual([]);
+});
diff --git a/internal/domain/crew.go b/internal/domain/crew.go
index a4544e22..bf315cd5 100644
--- a/internal/domain/crew.go
+++ b/internal/domain/crew.go
@@ -36,20 +36,40 @@ type CrewMission struct {
// CrewTask is one bot's step. Status: pending, running, succeeded, failed,
// skipped.
type CrewTask struct {
- ID string `json:"id"`
- AgentID string `json:"agentId"`
- AgentName string `json:"agentName"`
- Title string `json:"title"`
- Instruction string `json:"instruction,omitempty"`
- Status string `json:"status"`
- AddedBy string `json:"addedBy,omitempty"`
- WorkflowID string `json:"workflowId,omitempty"`
- RunID string `json:"runId,omitempty"`
- Summary string `json:"summary,omitempty"`
- Output string `json:"output,omitempty"`
- Error string `json:"error,omitempty"`
- StartedAt time.Time `json:"startedAt,omitempty"`
- FinishedAt time.Time `json:"finishedAt,omitempty"`
+ ID string `json:"id"`
+ AgentID string `json:"agentId"`
+ AgentName string `json:"agentName"`
+ Title string `json:"title"`
+ Instruction string `json:"instruction,omitempty"`
+ Status string `json:"status"`
+ AddedBy string `json:"addedBy,omitempty"`
+ WorkflowID string `json:"workflowId,omitempty"`
+ RunID string `json:"runId,omitempty"`
+ // StreamPost is the room message that receives this step's tokens.
+ // A run id prefixed with "stream:" is that post, not an engine run.
+ StreamPost string `json:"streamPost,omitempty"`
+ // StreamGen increments every time the step's stream is restarted.
+ StreamGen int `json:"streamGen,omitempty"`
+ Summary string `json:"summary,omitempty"`
+ Output string `json:"output,omitempty"`
+ Error string `json:"error,omitempty"`
+ // Handoff is the only context the next bot receives from this step.
+ Handoff *CrewHandoff `json:"handoff,omitempty"`
+ // PlanReason is the captain's one-line explanation for choosing this bot.
+ PlanReason string `json:"planReason,omitempty"`
+ // ReassignedFrom names the bot that was skipped because it was unavailable.
+ ReassignedFrom string `json:"reassignedFrom,omitempty"`
+ ReassignedReason string `json:"reassignedReason,omitempty"`
+ StartedAt time.Time `json:"startedAt,omitempty"`
+ FinishedAt time.Time `json:"finishedAt,omitempty"`
+}
+
+// CrewHandoff is the structured packet passed between crew steps.
+// The next bot sees this, not the previous bot's full transcript.
+type CrewHandoff struct {
+ Conclusion string `json:"conclusion"`
+ Artifacts []string `json:"artifacts,omitempty"`
+ OpenQuestions []string `json:"openQuestions,omitempty"`
}
// CrewNote is something a person said in the room while the mission ran;
diff --git a/internal/domain/room.go b/internal/domain/room.go
index eb75646c..48d72240 100644
--- a/internal/domain/room.go
+++ b/internal/domain/room.go
@@ -86,8 +86,16 @@ type ChatMessage struct {
ReplyTo string `json:"replyTo,omitempty"`
ReplyAuthor string `json:"replyAuthor,omitempty"`
ReplyText string `json:"replyText,omitempty"`
+ // ParentID is the thread root the model may see. A thread reply carries
+ // only that chain, not the rest of the room timeline.
+ ParentID string `json:"parentId,omitempty"`
+ // ReassignNote is set when an @ of an unavailable bot was rewritten
+ // before the message was stored.
+ ReassignNote string `json:"reassignNote,omitempty"`
// Pending marks a bot reply that is still being written.
Pending bool `json:"pending,omitempty"`
+ // Error is the human reason a streamed bot post failed.
+ Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go
index 6a69aa2a..716dbe03 100644
--- a/internal/httpapi/assistant.go
+++ b/internal/httpapi/assistant.go
@@ -54,6 +54,9 @@ type assistantLaunch struct {
// work to the room's bots. The user can switch it on the card.
Mode string `json:"mode,omitempty"`
ModeReason string `json:"modeReason,omitempty"`
+ // Confidence is 0..1. Reasons are the short lines behind that pick.
+ Confidence float64 `json:"confidence,omitempty"`
+ Reasons []string `json:"reasons,omitempty"`
}
type assistantRequest struct {
ProjectID string `json:"projectId"`
diff --git a/internal/httpapi/assistant_home.go b/internal/httpapi/assistant_home.go
index b6d17981..2b980db8 100644
--- a/internal/httpapi/assistant_home.go
+++ b/internal/httpapi/assistant_home.go
@@ -15,7 +15,7 @@ const assistantSceneHome = "home"
const assistantHomeScenePrompt = `你现在是这个项目的 PM 助理,在平台首页和用户对话。用户在这里提需求、问进度、处理待确认,也让你帮忙画图、出文档。
- 用户提出新需求或改动时,先弄清楚再开跑:用只读工具查已有需求(避免重复)和代码(有 GitHub 工具时读相关文件),把用户必须拍板的点放进 questions(每轮最多 3 个,选择题给 2~4 个具体选项)。message 里先用一两句话说明你查到了什么、为什么要问。
- 需求说清后提供 launch:新需求给 title 和 description(description 写完整的澄清结论:目标、范围、验收标准、涉及文件),workflowId 从「可用 SOP」里选最合适的。不要用 drafts 去建需求或派发,开跑卡片由用户确认。
-- launch 还要给 mode,决定交给谁做:有严格流程、并且「可用 SOP」里有对得上的(标准交付、修 bug、发布等),mode 填 "sop" 并给 workflowId;没有固定流程的开放任务(调研、排查、出方案、做原型、跨角色临时协作),或者没有对得上的 SOP,mode 填 "crew",交给协作群里的 Bot 团队自由协作,不用给 workflowId。用 modeReason 一句话说明为什么这样选。
+- launch 还要给 mode,决定交给谁做:有严格流程、并且「可用 SOP」里有对得上的(标准交付、修 bug、发布等),mode 填 "sop" 并给 workflowId;没有固定流程的开放任务(调研、排查、出方案、做原型、跨 Bot 临时协作),或者没有对得上的 SOP,mode 填 "crew",交给协作群里的 Bot 团队自由协作,不用给 workflowId。用 modeReason 一句话说明为什么这样选,并给 confidence(0 到 1)和 reasons(1 到 3 条短句)。
- 用户 @ 了已有需求时,围绕那条需求回答;要跑它就在 launch 里填 issueId。
- 问进度、问运行结果时,用 runs_list / runs_get / issues_get 查真实数据后回答,说清卡在哪一步、需要用户做什么。
- 用户要图(流程图、架构图、时序图)时,在 files 里给 .svg 文件(完整 SVG 源码,中文用 sans-serif 字体,尺寸不超过 1200x900),或者在 message 里写 mermaid 代码块;要文档、表格时在 files 里给 .md / .csv。
@@ -179,6 +179,38 @@ func (h *assistantHandlers) resolveAssistantLaunch(projectID string, launch *ass
if utf8.RuneCountInString(launch.Title) > 200 {
launch.Title = string([]rune(launch.Title)[:200])
}
+ if launch.Confidence < 0 || launch.Confidence > 1 {
+ launch.Confidence = 0
+ }
+ if launch.Confidence == 0 {
+ if launch.Mode == "sop" && (launch.WorkflowID != "" || launch.IssueID != "") {
+ launch.Confidence = 0.72
+ } else {
+ launch.Confidence = 0.58
+ }
+ }
+ reasons := make([]string, 0, 3)
+ for _, reason := range launch.Reasons {
+ reason = strings.TrimSpace(reason)
+ if reason == "" {
+ continue
+ }
+ reasons = append(reasons, truncateRunes(reason, 80))
+ if len(reasons) == 3 {
+ break
+ }
+ }
+ if len(reasons) == 0 && strings.TrimSpace(launch.ModeReason) != "" {
+ reasons = append(reasons, truncateRunes(strings.TrimSpace(launch.ModeReason), 80))
+ }
+ if len(reasons) == 0 {
+ if launch.Mode == "crew" {
+ reasons = append(reasons, "没有对得上的固定流程,交给 Bot 团队分工。")
+ } else {
+ reasons = append(reasons, "有对得上的 SOP,按固定流程交付。")
+ }
+ }
+ launch.Reasons = reasons
return launch
}
diff --git a/internal/httpapi/bot_status.go b/internal/httpapi/bot_status.go
new file mode 100644
index 00000000..f8df1373
--- /dev/null
+++ b/internal/httpapi/bot_status.go
@@ -0,0 +1,164 @@
+package httpapi
+
+import (
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Tencent/LoopForge/internal/domain"
+ "github.com/gin-gonic/gin"
+)
+
+// botStatusView is the heartbeat-ish snapshot the room polls at most every 30s.
+// Status is online, busy (with queue), degraded, or unavailable (with a reason).
+type botStatusView struct {
+ AgentID string `json:"agentId"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Queue int `json:"queue"`
+ Reason string `json:"reason,omitempty"`
+ HeartbeatAt time.Time `json:"heartbeatAt"`
+}
+
+type botHealth struct {
+ mu sync.Mutex
+ fail map[string]string
+ failAt map[string]time.Time
+}
+
+func (h *roomsHandlers) health() *botHealth {
+ h.pulseOnce.Do(func() {
+ h.pulse = &botHealth{fail: map[string]string{}, failAt: map[string]time.Time{}}
+ })
+ return h.pulse
+}
+
+func (h *roomsHandlers) markBotDegraded(agentID, reason string) {
+ if agentID == "" {
+ return
+ }
+ p := h.health()
+ p.mu.Lock()
+ p.fail[agentID] = roomTrim(reason, 160)
+ p.failAt[agentID] = time.Now().UTC()
+ p.mu.Unlock()
+}
+
+func (h *roomsHandlers) clearBotDegraded(agentID string) {
+ p := h.health()
+ p.mu.Lock()
+ delete(p.fail, agentID)
+ delete(p.failAt, agentID)
+ p.mu.Unlock()
+}
+
+func (h *roomsHandlers) botStatus(c *gin.Context) {
+ projectID := strings.TrimSpace(c.Query("projectId"))
+ if projectID == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "projectId is required"})
+ return
+ }
+ if _, ok := h.repo.Project(projectID); !ok {
+ c.JSON(http.StatusNotFound, gin.H{"error": "project not found"})
+ return
+ }
+ if !h.roomAccess(c, projectID, false) {
+ return
+ }
+ userID, _ := h.roomActor(c)
+ c.JSON(http.StatusOK, h.botStatuses(projectID, userID))
+}
+
+func (h *roomsHandlers) botStatuses(projectID string, userID int64) []botStatusView {
+ now := time.Now().UTC()
+ hasKey := h.userHasModelKey(userID)
+ queue := h.botQueues()
+ p := h.health()
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ var out []botStatusView
+ for _, a := range h.repo.Agents() {
+ if !catalogVisible(a.ProjectID, a.Shared, projectID) {
+ continue
+ }
+ view := botStatusView{AgentID: a.ID, Name: crewAgentName(a), Queue: queue[a.ID], HeartbeatAt: now, Status: "online"}
+ switch {
+ case agentNeedsKey(a) && !hasKey:
+ view.Status = "unavailable"
+ view.Reason = "缺 Key"
+ case view.Queue > 0:
+ view.Status = "busy"
+ view.Reason = "排队"
+ default:
+ if reason := p.fail[a.ID]; reason != "" && now.Sub(p.failAt[a.ID]) < 30*time.Minute {
+ view.Status = "degraded"
+ view.Reason = reason
+ }
+ }
+ out = append(out, view)
+ }
+ if out == nil {
+ out = []botStatusView{}
+ }
+ return out
+}
+
+func (h *roomsHandlers) userHasModelKey(userID int64) bool {
+ user, ok := h.repo.User(userID)
+ if !ok {
+ return false
+ }
+ return strings.TrimSpace(user.CodeBuddyAPIKey) != "" || strings.TrimSpace(user.ClaudeCodeAPIKey) != "" || strings.TrimSpace(user.CodexAPIKey) != ""
+}
+
+func agentNeedsKey(a domain.AgentDefinition) bool {
+ return a.ExecutorID != "mock"
+}
+
+func (h *roomsHandlers) botQueues() map[string]int {
+ out := map[string]int{}
+ for _, msg := range h.repo.CrewMessages("") {
+ if msg.Crew == nil || msg.Crew.Status != "running" {
+ continue
+ }
+ for _, t := range msg.Crew.Tasks {
+ if t.AgentID != "" && (t.Status == "running" || t.Status == "pending") {
+ out[t.AgentID]++
+ }
+ }
+ }
+ return out
+}
+
+// rewriteRoomMentions rejects an @ of an unavailable bot when nobody else can
+// take it, and otherwise rewrites the mention onto the first bot that can.
+func (h *roomsHandlers) rewriteRoomMentions(projectID string, userID int64, body string) (string, string, error) {
+ statuses := h.botStatuses(projectID, userID)
+ var fallback *botStatusView
+ for i := range statuses {
+ switch statuses[i].Status {
+ case "online", "busy", "degraded":
+ if fallback == nil {
+ fb := statuses[i]
+ fallback = &fb
+ }
+ }
+ }
+ note := ""
+ for _, st := range statuses {
+ if st.Status != "unavailable" || st.Name == "" {
+ continue
+ }
+ token := "@" + st.Name
+ if !strings.Contains(body, token) {
+ continue
+ }
+ if fallback == nil {
+ return body, "", HTTPError{http.StatusConflict, st.Name + " 不可用:" + st.Reason}
+ }
+ body = strings.ReplaceAll(body, token, "@"+fallback.Name)
+ note = "已改由 " + fallback.Name + " 负责(" + st.Name + " " + st.Reason + ")"
+ }
+ return body, note, nil
+}
diff --git a/internal/httpapi/crew_stream.go b/internal/httpapi/crew_stream.go
new file mode 100644
index 00000000..1edd8496
--- /dev/null
+++ b/internal/httpapi/crew_stream.go
@@ -0,0 +1,449 @@
+package httpapi
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/Tencent/LoopForge/internal/domain"
+)
+
+const crewStreamPrefix = "stream:"
+
+func (h *roomsHandlers) rememberCrewSpec(id string, spec *fakeModelSpec) {
+ if id == "" || spec == nil || !fakeModelAllowed() {
+ return
+ }
+ cp := *spec
+ h.crewSpecMu.Lock()
+ defer h.crewSpecMu.Unlock()
+ if h.crewSpecs == nil {
+ h.crewSpecs = map[string]*fakeModelSpec{}
+ }
+ h.crewSpecs[id] = &cp
+}
+
+func (h *roomsHandlers) crewSpecFor(id string) *fakeModelSpec {
+ h.crewSpecMu.Lock()
+ defer h.crewSpecMu.Unlock()
+ if h.crewSpecs == nil {
+ return nil
+ }
+ return h.crewSpecs[id]
+}
+
+func (h *roomsHandlers) useCrewFakeStream(missionID string) bool {
+ if !fakeModelAllowed() {
+ return false
+ }
+ if envOn("LOOPFORGE_DEMO_MODE") {
+ return true
+ }
+ spec := h.crewSpecFor(missionID)
+ return spec != nil && spec.CrewStep
+}
+
+func (h *roomsHandlers) takeCrewFail(missionID string, step int) bool {
+ h.crewSpecMu.Lock()
+ defer h.crewSpecMu.Unlock()
+ spec := h.crewSpecs[missionID]
+ if spec == nil || spec.FailStep == 0 || spec.FailStep != step || spec.failUsed {
+ return false
+ }
+ spec.failUsed = true
+ return true
+}
+
+func crewTaskStep(tasks []domain.CrewTask, id string) int {
+ for i := range tasks {
+ if tasks[i].ID == id {
+ return i + 1
+ }
+ }
+ return 1
+}
+
+func crewDemoText(t domain.CrewTask) string {
+ id := t.ID
+ if id == "" {
+ id = "step"
+ }
+ return "结论:" + t.AgentName + " 已完成「" + t.Title + "」\n产物:" + id + ".md\n未决问题:无"
+}
+
+func (h *roomsHandlers) crewFakeSpec(mission *domain.CrewMission, t *domain.CrewTask) (fakeModelSpec, bool) {
+ step := crewTaskStep(mission.Tasks, t.ID)
+ local := fakeModelSpec{Text: crewDemoText(*t), FirstTokenMs: 120, TokenMs: 12}
+ spec := h.crewSpecFor(mission.ID)
+ if spec != nil {
+ if step == 1 && strings.TrimSpace(spec.Text) != "" {
+ local.Text = spec.Text
+ }
+ if spec.FirstTokenMs > 0 {
+ local.FirstTokenMs = spec.FirstTokenMs
+ }
+ if spec.TokenMs > 0 {
+ local.TokenMs = spec.TokenMs
+ }
+ if step == 1 {
+ local.StallAfter = spec.StallAfter
+ local.StallMs = spec.StallMs
+ local.DisconnectAfter = spec.DisconnectAfter
+ }
+ }
+ fail := h.takeCrewFail(mission.ID, step)
+ if fail && local.DisconnectAfter == 0 {
+ local.DisconnectAfter = 2
+ }
+ return local, fail
+}
+
+func (h *roomsHandlers) launchNextCrewStep(missionID string) {
+ h.crewMu.Lock()
+ defer h.crewMu.Unlock()
+ msg, ok := h.repo.Message(missionID)
+ if !ok || msg.Crew == nil || msg.Crew.Status != "running" {
+ return
+ }
+ for _, t := range msg.Crew.Tasks {
+ if t.Status == "running" {
+ return
+ }
+ }
+ next := crewNextPending(msg.Crew)
+ if next == nil {
+ msg.Crew.Status = "done"
+ h.saveCrew(msg)
+ h.crewSay(msg, crewCaptain, "", crewWrapUp(msg.Crew), "", "")
+ return
+ }
+ if err := h.startCrewTask(msg, next); err != nil {
+ next.Status, next.Error = "failed", roomTrim(err.Error(), 400)
+ msg.Crew.Status, msg.Crew.QuestionAgent = "waiting", next.AgentID
+ h.saveCrew(msg)
+ h.crewSay(msg, crewCaptain, "", next.AgentName+" 没能开工:"+next.Error+"\n回复「重试」「跳过」或「停止」。", "", "")
+ return
+ }
+ h.saveCrew(msg)
+}
+
+func (h *roomsHandlers) openCrewFakeStep(msg domain.ChatMessage, t *domain.CrewTask) error {
+ post := h.newCrewPost(msg, t)
+ spec, fail := h.crewFakeSpec(msg.Crew, t)
+ ctx, cancel := context.WithCancel(context.Background())
+ st := h.streamHub().open(post.ID, post.RoomID, "", post.UserID, &spec, cancel)
+ if err := h.repo.PutMessage(post); err != nil {
+ cancel()
+ return err
+ }
+ t.StreamGen++
+ t.Status, t.RunID, t.StreamPost = "running", crewStreamPrefix+post.ID, post.ID
+ t.StartedAt, t.Error = time.Now().UTC(), ""
+ go h.runCrewFake(ctx, cancel, st, msg.ID, t.ID, t.StreamGen, post, spec, fail)
+ return nil
+}
+
+func (h *roomsHandlers) newCrewPost(msg domain.ChatMessage, t *domain.CrewTask) domain.ChatMessage {
+ return domain.ChatMessage{
+ ID: newChatID("msg"), RoomID: msg.RoomID, Author: t.AgentName, AgentID: t.AgentID,
+ Kind: domain.ChatKindCrewPost, CrewID: msg.ID, Pending: true,
+ IssueID: msg.IssueID, IssueNumber: msg.IssueNumber, IssueTitle: msg.IssueTitle,
+ CreatedAt: time.Now().UTC(),
+ }
+}
+
+func (h *roomsHandlers) attachCrewRunStream(msg domain.ChatMessage, t *domain.CrewTask) {
+ post := h.newCrewPost(msg, t)
+ if err := h.repo.PutMessage(post); err != nil {
+ return
+ }
+ t.StreamGen++
+ t.StreamPost = post.ID
+ go h.watchCrewRun(msg.ID, t.ID, t.StreamGen, post, t.RunID)
+}
+
+func (h *roomsHandlers) restartCrewPost(post domain.ChatMessage) {
+ h.crewMu.Lock()
+ msg, ok := h.repo.Message(post.CrewID)
+ taskID := ""
+ if ok && msg.Crew != nil {
+ for i := range msg.Crew.Tasks {
+ t := &msg.Crew.Tasks[i]
+ if t.StreamPost != post.ID && strings.TrimPrefix(t.RunID, crewStreamPrefix) != post.ID {
+ continue
+ }
+ t.StreamGen++
+ t.Status, t.Error = "running", ""
+ taskID = t.ID
+ if msg.Crew.Status == "waiting" || msg.Crew.Status == "stopped" {
+ msg.Crew.Status, msg.Crew.Question, msg.Crew.QuestionAgent = "running", "", ""
+ }
+ }
+ if taskID != "" {
+ h.saveCrew(msg)
+ }
+ }
+ h.crewMu.Unlock()
+ if taskID == "" || msg.Crew == nil {
+ return
+ }
+ post.Body, post.Pending, post.NodeStatus, post.Error = "", true, "", ""
+ _ = h.repo.PutMessage(post)
+ var task domain.CrewTask
+ for _, t := range msg.Crew.Tasks {
+ if t.ID == taskID {
+ task = t
+ break
+ }
+ }
+ if strings.HasPrefix(task.RunID, crewStreamPrefix) || h.useCrewFakeStream(msg.ID) {
+ spec, fail := h.crewFakeSpec(msg.Crew, &task)
+ ctx, cancel := context.WithCancel(context.Background())
+ st := h.streamHub().open(post.ID, post.RoomID, "", post.UserID, &spec, cancel)
+ go h.runCrewFake(ctx, cancel, st, msg.ID, task.ID, task.StreamGen, post, spec, fail)
+ return
+ }
+ go h.watchCrewRun(msg.ID, task.ID, task.StreamGen, post, task.RunID)
+}
+
+func (h *roomsHandlers) crewStreamLive(missionID, taskID string, gen int) bool {
+ msg, ok := h.repo.Message(missionID)
+ if !ok || msg.Crew == nil {
+ return false
+ }
+ for i := range msg.Crew.Tasks {
+ if msg.Crew.Tasks[i].ID == taskID {
+ return msg.Crew.Tasks[i].StreamGen == gen
+ }
+ }
+ return false
+}
+
+func (h *roomsHandlers) runCrewFake(ctx context.Context, cancel context.CancelFunc, st *roomTokenStream, missionID, taskID string, gen int, post domain.ChatMessage, spec fakeModelSpec, fail bool) {
+ defer cancel()
+ body, err := h.writeStream(ctx, st, &post, func(emit func(string) bool) error {
+ return runFakeModel(ctx, spec, emit)
+ })
+ if !h.crewStreamLive(missionID, taskID, gen) {
+ st.finish(roomStreamEvent{Type: "stopped", Text: strings.TrimSpace(body)})
+ return
+ }
+ stopped := ctx.Err() != nil
+ if stopped {
+ err = nil
+ } else if fail && err != nil {
+ err = fmt.Errorf("这一步没有做成,点「重试」可以接着跑")
+ }
+ h.finishCrewPost(&post, body, stopped, err)
+ h.settleCrewStream(missionID, taskID, gen, post.ID, body, stopped, err)
+ h.finishStreamEvent(st, &post, stopped, err)
+}
+
+func (h *roomsHandlers) watchCrewRun(missionID, taskID string, gen int, post domain.ChatMessage, runID string) {
+ ctx, cancel := context.WithCancel(context.Background())
+ st := h.streamHub().open(post.ID, post.RoomID, "", post.UserID, nil, cancel)
+ defer cancel()
+ var emitted string
+ body, err := h.writeStream(ctx, st, &post, func(emit func(string) bool) error {
+ return h.followCrewRun(ctx, runID, emit, &emitted)
+ })
+ stopped := ctx.Err() != nil
+ if !h.crewStreamLive(missionID, taskID, gen) {
+ st.finish(roomStreamEvent{Type: "stopped", Text: strings.TrimSpace(body)})
+ return
+ }
+ if stopped && h.engine != nil && !strings.HasPrefix(runID, crewStreamPrefix) {
+ _ = h.engine.Cancel(runID)
+ err = nil
+ }
+ if body == "" {
+ body = emitted
+ }
+ h.finishCrewPost(&post, body, stopped, err)
+ h.settleCrewStream(missionID, taskID, gen, post.ID, body, stopped, err)
+ h.finishStreamEvent(st, &post, stopped, err)
+}
+
+func (h *roomsHandlers) followCrewRun(ctx context.Context, runID string, emit func(string) bool, emitted *string) error {
+ deadline := time.Now().Add(8 * time.Minute)
+ var sent string
+ for {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ if time.Now().After(deadline) {
+ return fmt.Errorf("这一步超过 8 分钟还没有结果")
+ }
+ run, ok := h.repo.Run(runID)
+ if ok {
+ text := crewLiveText(run)
+ if strings.HasPrefix(text, sent) && len(text) > len(sent) {
+ if !emit(text[len(sent):]) {
+ return ctx.Err()
+ }
+ sent = text
+ *emitted = sent
+ }
+ if roomRunTerminal(run.Status) {
+ if sent == "" {
+ if !emitRunesDone(ctx, text, emit) {
+ return ctx.Err()
+ }
+ *emitted = text
+ }
+ if run.Status == "succeeded" {
+ return nil
+ }
+ reason := run.Status
+ if node := run.Nodes["work"]; node != nil && strings.TrimSpace(node.Error) != "" {
+ reason = node.Error
+ }
+ return fmt.Errorf("%s", roomTrim(reason, 400))
+ }
+ }
+ if !waitCtx(ctx, 200*time.Millisecond) {
+ return ctx.Err()
+ }
+ }
+}
+
+func crewLiveText(run domain.Run) string {
+ var b strings.Builder
+ for _, ev := range run.Telemetry {
+ if ev.Name == "agent.output" && ev.Message != "" {
+ b.WriteString(ev.Message)
+ }
+ }
+ if b.Len() > 0 {
+ return b.String()
+ }
+ if node := run.Nodes["work"]; node != nil {
+ return node.Output
+ }
+ return ""
+}
+
+func emitRunesDone(ctx context.Context, text string, emit func(string) bool) bool {
+ return emitRunes(ctx, text, emit) == nil
+}
+
+func (h *roomsHandlers) writeStream(ctx context.Context, st *roomTokenStream, post *domain.ChatMessage, run func(func(string) bool) error) (string, error) {
+ var b strings.Builder
+ emit := func(tok string) bool {
+ if tok == "" {
+ return true
+ }
+ select {
+ case <-ctx.Done():
+ return false
+ default:
+ }
+ b.WriteString(tok)
+ st.publish(roomStreamEvent{Type: "token", Text: tok})
+ if b.Len()%24 == 0 {
+ post.Body = b.String()
+ _ = h.repo.PutMessage(*post)
+ }
+ return true
+ }
+ err := run(emit)
+ return b.String(), err
+}
+
+func (h *roomsHandlers) finishCrewPost(post *domain.ChatMessage, body string, stopped bool, err error) {
+ post.Body = strings.TrimSpace(body)
+ post.Pending = false
+ switch {
+ case stopped:
+ post.NodeStatus = "stopped"
+ case err != nil:
+ post.NodeStatus = "error"
+ post.Error = err.Error()
+ if post.Body == "" {
+ post.Body = err.Error()
+ }
+ default:
+ post.NodeStatus = ""
+ post.Error = ""
+ }
+ _ = h.repo.PutMessage(*post)
+}
+
+func (h *roomsHandlers) finishStreamEvent(st *roomTokenStream, post *domain.ChatMessage, stopped bool, err error) {
+ switch {
+ case stopped:
+ st.finish(roomStreamEvent{Type: "stopped", Text: post.Body})
+ case err != nil:
+ st.finish(roomStreamEvent{Type: "error", Text: err.Error()})
+ default:
+ st.finish(roomStreamEvent{Type: "done", Text: post.Body})
+ }
+}
+
+func (h *roomsHandlers) settleCrewStream(missionID, taskID string, gen int, postID, body string, stopped bool, runErr error) {
+ h.crewMu.Lock()
+ defer h.crewMu.Unlock()
+ msg, ok := h.repo.Message(missionID)
+ if !ok || msg.Crew == nil {
+ return
+ }
+ var t *domain.CrewTask
+ for i := range msg.Crew.Tasks {
+ if msg.Crew.Tasks[i].ID == taskID {
+ t = &msg.Crew.Tasks[i]
+ break
+ }
+ }
+ if t == nil || t.Status != "running" || t.StreamGen != gen {
+ return
+ }
+ t.FinishedAt = time.Now().UTC()
+ if stopped {
+ t.Status, t.Error = "failed", "已停止"
+ if msg.Crew.Status == "running" {
+ msg.Crew.Status, msg.Crew.Question, msg.Crew.QuestionAgent = "waiting", "", t.AgentID
+ }
+ h.saveCrew(msg)
+ h.crewSay(msg, crewCaptain, "", t.AgentName+" 停在了「"+t.Title+"」。上面留下了已经写出的内容,回复「重试」可以续跑。", "", "")
+ return
+ }
+ if runErr != nil {
+ t.Status, t.Error = "failed", roomTrim(runErr.Error(), 400)
+ h.markBotDegraded(t.AgentID, t.Error)
+ msg.Crew.Status, msg.Crew.Question, msg.Crew.QuestionAgent = "waiting", "", t.AgentID
+ h.saveCrew(msg)
+ h.crewSay(msg, crewCaptain, "", "@"+crewMention(msg.Crew.StartedByName)+" "+t.AgentName+" 在「"+t.Title+"」卡住了:"+t.Error+"\n回复「重试」「跳过」或「停止」,也可以直接说怎么改。", "", "")
+ return
+ }
+ t.Status = "succeeded"
+ t.Output, t.Summary = roomTrim(body, 6000), crewSummary(body)
+ t.Handoff = parseCrewHandoff(body, t.Summary)
+ t.Error = ""
+ h.clearBotDegraded(t.AgentID)
+ if q := crewQuestion(body); q != "" {
+ msg.Crew.Status, msg.Crew.Question, msg.Crew.QuestionAgent = "waiting", q, t.AgentID
+ h.saveCrew(msg)
+ h.crewSay(msg, crewCaptain, "", "@"+crewMention(msg.Crew.StartedByName)+" "+t.AgentName+" 需要你确认:"+q+"\n直接在群里回复,我会交回给它继续。", "", "")
+ return
+ }
+ next := crewNextPending(msg.Crew)
+ if stored, ok := h.repo.Message(postID); ok && next != nil {
+ stored.TargetName, stored.NodeName = next.AgentName, next.Title
+ _ = h.repo.PutMessage(stored)
+ }
+ if next == nil {
+ msg.Crew.Status = "done"
+ h.saveCrew(msg)
+ h.crewSay(msg, crewCaptain, "", crewWrapUp(msg.Crew), "", "")
+ return
+ }
+ if err := h.startCrewTask(msg, next); err != nil {
+ next.Status, next.Error = "failed", roomTrim(err.Error(), 400)
+ msg.Crew.Status, msg.Crew.QuestionAgent = "waiting", next.AgentID
+ h.saveCrew(msg)
+ h.crewSay(msg, crewCaptain, "", next.AgentName+" 没能开工:"+next.Error+"\n回复「重试」「跳过」或「停止」。", "", "")
+ return
+ }
+ h.saveCrew(msg)
+}
diff --git a/internal/httpapi/gin_helpers.go b/internal/httpapi/gin_helpers.go
index 6182651e..e29dad76 100644
--- a/internal/httpapi/gin_helpers.go
+++ b/internal/httpapi/gin_helpers.go
@@ -23,6 +23,21 @@ type HTTPError struct {
func (e HTTPError) Error() string { return e.Message }
+// codedError is the unified error body: message plus a stable code and the
+// next action the client should offer.
+type codedError struct {
+ Status int
+ Message string
+ Code string
+ Action string
+}
+
+func (e codedError) Error() string { return e.Message }
+
+func apiError(status int, code, action, message string) error {
+ return codedError{Status: status, Message: message, Code: code, Action: action}
+}
+
// respond 渲染操作结果,是唯一的统一响应入口:
// - err == nil → 200 {"ok": true};
// - 否则渲染统一 JSON 错误形态,状态码取 HTTPError 自带值,
@@ -32,13 +47,22 @@ func respond(c *gin.Context, err error) {
c.JSON(http.StatusOK, map[string]bool{"ok": true})
return
}
+ var ce codedError
+ if errors.As(err, &ce) {
+ body := map[string]string{"error": ce.Message, "code": ce.Code}
+ if ce.Action != "" {
+ body["action"] = ce.Action
+ }
+ c.JSON(ce.Status, body)
+ return
+ }
var he HTTPError
if errors.As(err, &he) {
c.JSON(he.Status, map[string]string{"error": he.Message})
return
}
if ae, ok := apperr.As(err); ok {
- body := map[string]any{"error": ae.Message}
+ body := map[string]any{"error": ae.Message, "code": appErrCode(ae.Kind)}
for key, value := range ae.Fields {
body[key] = value
}
@@ -52,6 +76,23 @@ func respond(c *gin.Context, err error) {
c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
+func appErrCode(kind apperr.Kind) string {
+ switch kind {
+ case apperr.NotFound:
+ return "not_found"
+ case apperr.Conflict:
+ return "conflict"
+ case apperr.Forbidden:
+ return "forbidden"
+ case apperr.Unavailable:
+ return "unavailable"
+ case apperr.Upstream:
+ return "upstream"
+ default:
+ return "invalid"
+ }
+}
+
func appErrStatus(kind apperr.Kind) int {
switch kind {
case apperr.NotFound:
diff --git a/internal/httpapi/room_ask.go b/internal/httpapi/room_ask.go
index 646eae35..556b7786 100644
--- a/internal/httpapi/room_ask.go
+++ b/internal/httpapi/room_ask.go
@@ -55,20 +55,21 @@ func roomQuoteText(m domain.ChatMessage) string {
}
// answerInRoom posts a pending captain reply right away so everyone sees the
-// bot is on it, then fills it in.
-func (h *roomsHandlers) answerInRoom(room domain.ChatRoom, said domain.ChatMessage, question string) {
+// bot is on it, then streams the answer token by token.
+func (h *roomsHandlers) answerInRoom(room domain.ChatRoom, said domain.ChatMessage, question string, spec *fakeModelSpec) {
+ parent := said.ParentID
+ if parent == "" {
+ parent = said.ReplyTo
+ }
reply := domain.ChatMessage{
ID: newChatID("msg"), RoomID: room.ID, Author: crewCaptain, Kind: domain.ChatKindCrewPost, Pending: true,
- ReplyTo: said.ID, ReplyAuthor: roomQuoteAuthor(said), ReplyText: roomTrim(said.Body, 200), CreatedAt: time.Now().UTC(),
+ ReplyTo: said.ID, ReplyAuthor: roomQuoteAuthor(said), ReplyText: roomTrim(said.Body, 200),
+ ParentID: parent, CreatedAt: time.Now().UTC(),
}
if err := h.repo.PutMessage(reply); err != nil {
return
}
- go func() {
- reply.Body = h.crewAnswer(room, said, question)
- reply.Pending = false
- _ = h.repo.PutMessage(reply)
- }()
+ h.beginReplyStream(room, said, reply, question, spec)
}
func (h *roomsHandlers) crewAnswer(room domain.ChatRoom, said domain.ChatMessage, question string) string {
@@ -80,23 +81,9 @@ func (h *roomsHandlers) crewAnswer(room domain.ChatRoom, said domain.ChatMessage
}
return "直接回答问题要用模型,你还没配 Key:去「设置 · 个人设置」配好就行。\n现在我能做的:\n- 「@LoopForge + 要做的事」我来拉 Bot 组队干活\n- 问「进度」我汇报群里的任务\n\n" + status
}
- var history []string
- for _, m := range h.repo.Messages(room.ID, 40) {
- if m.ID == said.ID || m.Pending {
- continue
- }
- if text := strings.TrimSpace(roomQuoteText(m)); text != "" {
- history = append(history, roomQuoteAuthor(m)+":"+roomTrim(text, 240))
- }
- }
- quote := "无"
- if said.ReplyTo != "" {
- quote = said.ReplyAuthor + ":" + said.ReplyText
- }
- prompt := fmt.Sprintf(crewAnswerPrompt, status, strings.Join(history, "\n"), quote, roomQuoteAuthor(said), question)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
- raw, err := generateAssistantReply(ctx, prompt, user)
+ raw, err := generateAssistantReply(ctx, h.captainPrompt(room, said, question, status), user)
if text := strings.TrimSpace(raw); err == nil && text != "" {
return roomTrim(text, 2000)
}
@@ -138,13 +125,14 @@ func (h *roomsHandlers) roomStatusDigest(room domain.ChatRoom) string {
}
const crewAnswerPrompt = `你是群聊里的 Bot「LoopForge」,这个项目的 PM 兼 Bot 团队队长。像同事在群里回话一样回答:中文、口语、简短(一般不超过 8 行),可以用 Markdown 列表。
-只根据下面的群任务、群聊记录和引用的消息回答;不知道就直说,不要编。
+只根据下面的群任务、上下文和引用的消息回答;不知道就直说,不要编。
如果对方其实是想让人动手干活,告诉他用「@LoopForge + 要做的事」交给 Bot 团队,或 @ 一条 SOP 按流程跑。
+线程里的提问只带 parent_id 这条链,不要假设你看过群里的其它消息。
## 群任务
%s
-## 最近群聊
+## 上下文(parent_id=%s)
%s
## 引用的消息
@@ -152,3 +140,59 @@ const crewAnswerPrompt = `你是群聊里的 Bot「LoopForge」,这个项目
## 提问(来自 %s)
%s`
+
+func (h *roomsHandlers) captainPrompt(room domain.ChatRoom, said domain.ChatMessage, question, status string) string {
+ history := h.captainHistory(room, said)
+ quote := "无"
+ if said.ReplyTo != "" {
+ quote = said.ReplyAuthor + ":" + said.ReplyText
+ }
+ parent := said.ParentID
+ if parent == "" {
+ parent = "主时间线"
+ }
+ return fmt.Sprintf(crewAnswerPrompt, status, parent, strings.Join(history, "\n"), quote, roomQuoteAuthor(said), question)
+}
+
+// captainHistory is the thread chain when the message has a parent, and a
+// short slice of the room otherwise. A thread never receives the whole timeline.
+func (h *roomsHandlers) captainHistory(room domain.ChatRoom, said domain.ChatMessage) []string {
+ all := h.repo.Messages(room.ID, 40)
+ if said.ParentID != "" || said.ReplyTo != "" {
+ return roomThreadLines(all, said)
+ }
+ var history []string
+ for _, m := range all {
+ if m.ID == said.ID || m.Pending {
+ continue
+ }
+ if text := strings.TrimSpace(roomQuoteText(m)); text != "" {
+ history = append(history, roomQuoteAuthor(m)+":"+roomTrim(text, 240))
+ }
+ }
+ return history
+}
+
+func roomThreadLines(all []domain.ChatMessage, leaf domain.ChatMessage) []string {
+ byID := map[string]domain.ChatMessage{}
+ for _, m := range all {
+ byID[m.ID] = m
+ }
+ var chain []domain.ChatMessage
+ seen := map[string]bool{}
+ id := firstNonEmpty(leaf.ParentID, leaf.ReplyTo)
+ for id != "" && len(chain) < 8 && !seen[id] {
+ seen[id] = true
+ m, ok := byID[id]
+ if !ok {
+ break
+ }
+ chain = append(chain, m)
+ id = firstNonEmpty(m.ParentID, m.ReplyTo)
+ }
+ lines := make([]string, 0, len(chain))
+ for i := len(chain) - 1; i >= 0; i-- {
+ lines = append(lines, "parent_id="+chain[i].ID+" "+roomQuoteAuthor(chain[i])+":"+roomTrim(roomQuoteText(chain[i]), 240))
+ }
+ return lines
+}
diff --git a/internal/httpapi/room_crew.go b/internal/httpapi/room_crew.go
index b8b4a3ae..e4d7fe3f 100644
--- a/internal/httpapi/room_crew.go
+++ b/internal/httpapi/room_crew.go
@@ -20,10 +20,11 @@ const crewMaxTasks = 8
const crewCaptain = "LoopForge"
type crewRequest struct {
- Goal string `json:"goal"`
- Detail string `json:"detail"`
- AutoStart bool `json:"autoStart"`
- Source string `json:"source"`
+ Goal string `json:"goal"`
+ Detail string `json:"detail"`
+ AutoStart bool `json:"autoStart"`
+ Source string `json:"source"`
+ FakeModel *fakeModelSpec `json:"fakeModel"`
}
type crewTaskInput struct {
@@ -31,6 +32,7 @@ type crewTaskInput struct {
AgentID string `json:"agentId"`
Title string `json:"title"`
Instruction string `json:"instruction"`
+ Reason string `json:"reason"`
}
type crewActionRequest struct {
@@ -63,6 +65,9 @@ func (h *roomsHandlers) createCrew(c *gin.Context) {
}
func (h *roomsHandlers) startCrewMission(room domain.ChatRoom, userID int64, author string, req crewRequest) (domain.ChatMessage, error) {
+ if envOn("LOOPFORGE_DEMO_MODE") || (fakeModelAllowed() && req.FakeModel != nil && req.FakeModel.CrewStep) {
+ req.AutoStart = true
+ }
goal := strings.TrimSpace(req.Goal)
detail := strings.TrimSpace(req.Detail)
if goal == "" {
@@ -75,7 +80,7 @@ func (h *roomsHandlers) startCrewMission(room domain.ChatRoom, userID int64, aut
return domain.ChatMessage{}, HTTPError{http.StatusBadRequest, "描述过长"}
}
if len(h.crewRoster(room.ProjectID, userID)) == 0 {
- return domain.ChatMessage{}, HTTPError{http.StatusBadRequest, "这个项目还没有能干活的角色 Bot,先去「构建 · 角色」建一个"}
+ return domain.ChatMessage{}, apiError(http.StatusBadRequest, "no_bot", "open_agents", "这个项目还没有能干活的 Bot,先到「Bot」里准备一个")
}
issue := domain.Issue{
ID: newChatID("iss"), ProjectID: room.ProjectID, Title: goal, Description: detail,
@@ -107,6 +112,11 @@ func (h *roomsHandlers) startCrewMission(room domain.ChatRoom, userID int64, aut
if err := h.repo.PutMessage(msg); err != nil {
return domain.ChatMessage{}, err
}
+ if req.FakeModel != nil && fakeModelAllowed() {
+ h.rememberCrewSpec(mission.ID, req.FakeModel)
+ } else if envOn("LOOPFORGE_DEMO_MODE") {
+ h.rememberCrewSpec(mission.ID, &fakeModelSpec{CrewStep: true, FirstTokenMs: 120, TokenMs: 12})
+ }
h.touchRoom(room)
go h.planCrew(room, msg.ID)
return msg, nil
@@ -115,6 +125,103 @@ func (h *roomsHandlers) startCrewMission(room domain.ChatRoom, userID int64, aut
// crewRoster lists the roles a crew may use: visible to the project and
// runnable by this user (the mock executor always is; real CLIs need a key,
// the engine falls back between built-in CLIs).
+func (h *roomsHandlers) crewVisible(projectID string) []domain.AgentDefinition {
+ var out []domain.AgentDefinition
+ for _, a := range h.repo.Agents() {
+ if catalogVisible(a.ProjectID, a.Shared, projectID) {
+ out = append(out, a)
+ }
+ }
+ return out
+}
+
+func (h *roomsHandlers) reassignUnavailableTasks(projectID string, userID int64, tasks []domain.CrewTask) []domain.CrewTask {
+ statuses := h.botStatuses(projectID, userID)
+ byID := map[string]botStatusView{}
+ var fallback *botStatusView
+ for i := range statuses {
+ byID[statuses[i].AgentID] = statuses[i]
+ if fallback == nil && statuses[i].Status != "unavailable" {
+ fb := statuses[i]
+ fallback = &fb
+ }
+ }
+ for i := range tasks {
+ st, ok := byID[tasks[i].AgentID]
+ if !ok || st.Status != "unavailable" || fallback == nil || fallback.AgentID == tasks[i].AgentID {
+ continue
+ }
+ tasks[i].ReassignedFrom = tasks[i].AgentName
+ tasks[i].ReassignedReason = st.Reason
+ tasks[i].AgentID = fallback.AgentID
+ tasks[i].AgentName = fallback.Name
+ }
+ return tasks
+}
+
+func (h *roomsHandlers) crewAudit(issueID, actor, action, detail string) {
+ if h == nil || h.repo == nil || issueID == "" {
+ return
+ }
+ issue, ok := h.repo.Issue(issueID)
+ if !ok {
+ return
+ }
+ issue.AppendOperation(domain.IssueOperation{Actor: actor, Action: action, Detail: detail})
+ _ = h.repo.PutIssue(issue)
+}
+
+// annotateIdealSkip records when the best-named bot for a step cannot run,
+// even if the planner already picked someone who can. The card then says
+// 「已改由 yy 负责」.
+func (h *roomsHandlers) annotateIdealSkip(goal string, tasks []domain.CrewTask, visible []domain.AgentDefinition, userID int64, projectID string) {
+ _ = goal
+ statuses := map[string]botStatusView{}
+ for _, st := range h.botStatuses(projectID, userID) {
+ statuses[st.AgentID] = st
+ }
+ for i := range tasks {
+ if tasks[i].ReassignedFrom != "" {
+ continue
+ }
+ k := -1
+ for n, kind := range crewRoleKinds {
+ if kind.title == tasks[i].Title {
+ k = n
+ break
+ }
+ }
+ if k < 0 {
+ continue
+ }
+ best, bestScore := -1, 0
+ for j, a := range visible {
+ score := crewRoleScore(a, k)
+ if score == 0 {
+ continue
+ }
+ better := score > bestScore
+ tieReal := score == bestScore && best >= 0 && visible[best].ExecutorID == "mock" && a.ExecutorID != "mock"
+ if better || tieReal {
+ best, bestScore = j, score
+ }
+ }
+ if best < 0 {
+ continue
+ }
+ ideal := visible[best]
+ if ideal.ID == tasks[i].AgentID {
+ continue
+ }
+ st := statuses[ideal.ID]
+ if st.Status != "unavailable" {
+ continue
+ }
+ tasks[i].ReassignedFrom = crewAgentName(ideal)
+ tasks[i].ReassignedReason = firstNonEmpty(st.Reason, "不可用")
+ }
+}
+
func (h *roomsHandlers) crewRoster(projectID string, userID int64) []domain.AgentDefinition {
hasKey := false
if user, ok := h.repo.User(userID); ok {
@@ -203,7 +310,7 @@ func crewPlanRules(goal string, roster []domain.AgentDefinition) []domain.CrewTa
}
a := roster[best]
used[a.ID] = true
- tasks = append(tasks, domain.CrewTask{AgentID: a.ID, AgentName: crewAgentName(a), Title: crewRoleKinds[k].title, Instruction: crewRoleKinds[k].brief, AddedBy: crewCaptain})
+ tasks = append(tasks, domain.CrewTask{AgentID: a.ID, AgentName: crewAgentName(a), Title: crewRoleKinds[k].title, Instruction: crewRoleKinds[k].brief, AddedBy: crewCaptain, PlanReason: "名称最接近「" + crewRoleKinds[k].title + "」,所以这一步交给它。"})
if len(tasks) == 4 {
break
}
@@ -213,7 +320,7 @@ func crewPlanRules(goal string, roster []domain.AgentDefinition) []domain.CrewTa
if i == 2 {
break
}
- tasks = append(tasks, domain.CrewTask{AgentID: a.ID, AgentName: crewAgentName(a), Title: map[bool]string{true: "先做一版", false: "接着完善"}[i == 0], Instruction: "围绕目标完成你职责范围内的部分。", AddedBy: crewCaptain})
+ tasks = append(tasks, domain.CrewTask{AgentID: a.ID, AgentName: crewAgentName(a), Title: map[bool]string{true: "先做一版", false: "接着完善"}[i == 0], Instruction: "围绕目标完成你职责范围内的部分。", AddedBy: crewCaptain, PlanReason: "没有更贴的角色名,按可用名单接着排。"})
}
}
return tasks
@@ -222,7 +329,7 @@ func crewPlanRules(goal string, roster []domain.AgentDefinition) []domain.CrewTa
const crewPlanPrompt = `你是 LoopForge 协作群里的队长 Bot。用户把一件没有固定流程的事交给了群里的 Bot 团队。
请从下面的角色里挑人,排出 2 到 5 步的分工,每一步由一个角色完成,前一步的产出会交给后一步。
只输出一个 JSON 对象,不要任何其它文字:
-{"tasks":[{"agentId":"角色 id","title":"这一步做什么(10 字以内)","instruction":"给这个 Bot 的具体要求(1-3 句)"}]}
+{"tasks":[{"agentId":"角色 id","title":"这一步做什么(10 字以内)","instruction":"给这个 Bot 的具体要求(1-3 句)","reason":"为什么是这个角色(一句话)"}]}
目标:%s
补充说明:%s
@@ -263,7 +370,11 @@ func (h *roomsHandlers) crewPlanAI(goal, detail string, roster []domain.AgentDef
if !ok || strings.TrimSpace(t.Title) == "" {
continue
}
- tasks = append(tasks, domain.CrewTask{AgentID: a.ID, AgentName: crewAgentName(a), Title: roomTrim(strings.TrimSpace(t.Title), 40), Instruction: roomTrim(strings.TrimSpace(t.Instruction), 600), AddedBy: crewCaptain})
+ reason := roomTrim(strings.TrimSpace(t.Reason), 80)
+ if reason == "" {
+ reason = "队长按目标和角色说明选的。"
+ }
+ tasks = append(tasks, domain.CrewTask{AgentID: a.ID, AgentName: crewAgentName(a), Title: roomTrim(strings.TrimSpace(t.Title), 40), Instruction: roomTrim(strings.TrimSpace(t.Instruction), 600), AddedBy: crewCaptain, PlanReason: reason})
if len(tasks) == 5 {
break
}
@@ -286,6 +397,8 @@ func (h *roomsHandlers) planCrew(room domain.ChatRoom, msgID string) {
if err != nil {
tasks, planner = crewPlanRules(m.Goal+" "+m.Detail, roster), "rules"
}
+ tasks = h.reassignUnavailableTasks(room.ProjectID, m.StartedBy, tasks)
+ h.annotateIdealSkip(m.Goal+" "+m.Detail, tasks, h.crewVisible(room.ProjectID), m.StartedBy, room.ProjectID)
h.crewMu.Lock()
defer h.crewMu.Unlock()
msg, ok = h.repo.Message(msgID)
@@ -313,15 +426,30 @@ func (h *roomsHandlers) planCrew(room domain.ChatRoom, msgID string) {
names[i] = t.AgentName + "「" + t.Title + "」"
}
lead := "收到。我拉了 " + fmt.Sprint(len(crewDistinctAgents(tasks))) + " 个 Bot 一起做:" + strings.Join(names, " → ") + "。"
+ for _, t := range tasks {
+ if t.ReassignedFrom != "" {
+ lead += "\n已改由 " + t.AgentName + " 负责(" + t.ReassignedFrom + " " + t.ReassignedReason + ")。"
+ }
+ }
if m.AutoStart {
lead += "已经开工,做完一步我会在群里交接。"
} else {
lead += "分工可以先改,确认后点「开工」。"
}
+ for _, t := range tasks {
+ if t.ReassignedFrom != "" {
+ h.crewAudit(m.IssueID, crewCaptain, "reassign", t.ReassignedFrom+" → "+t.AgentName+"("+t.ReassignedReason+")· "+t.Title)
+ }
+ }
h.crewSay(msg, crewCaptain, "", lead, "", "")
- if m.AutoStart {
+ streamNow := m.AutoStart && h.useCrewFakeStream(msg.ID)
+ if m.AutoStart && !streamNow {
h.ensureCrewLoop()
}
+ if streamNow {
+ id := msg.ID
+ go h.launchNextCrewStep(id)
+ }
}
func crewDistinctAgents(tasks []domain.CrewTask) map[string]bool {
@@ -431,6 +559,10 @@ func (h *roomsHandlers) advanceCrew(msgID string) {
if t.Status != "running" {
continue
}
+ if t.StreamPost != "" || strings.HasPrefix(t.RunID, crewStreamPrefix) {
+ busy = true
+ continue
+ }
run, found := h.repo.Run(t.RunID)
if !found || !roomRunTerminal(run.Status) {
busy = true
@@ -445,6 +577,8 @@ func (h *roomsHandlers) advanceCrew(msgID string) {
output = node.Output
}
t.Status, t.Output, t.Summary = "succeeded", roomTrim(output, 6000), crewSummary(output)
+ t.Handoff = parseCrewHandoff(output, t.Summary)
+ h.clearBotDegraded(t.AgentID)
if q := crewQuestion(output); q != "" {
m.Status, m.Question, m.QuestionAgent = "waiting", q, t.AgentID
h.crewSay(msg, t.AgentName, t.AgentID, firstNonEmpty(t.Summary, "做完了「"+t.Title+"」。"), "", "")
@@ -464,6 +598,7 @@ func (h *roomsHandlers) advanceCrew(msgID string) {
reason = node.Error
}
t.Status, t.Error = "failed", roomTrim(reason, 400)
+ h.markBotDegraded(t.AgentID, t.Error)
m.Status, m.Question, m.QuestionAgent = "waiting", "", t.AgentID
h.crewSay(msg, crewCaptain, "", "@"+crewMention(m.StartedByName)+" "+t.AgentName+" 在「"+t.Title+"」卡住了:"+t.Error+"\n回复「重试」「跳过」或「停止」,也可以直接说怎么改,我交给它重做。", "", "")
}
@@ -484,6 +619,72 @@ func (h *roomsHandlers) advanceCrew(msgID string) {
}
}
+func parseCrewHandoff(output, summary string) *domain.CrewHandoff {
+ h := &domain.CrewHandoff{}
+ cut := func(line, a, b string) (string, bool) {
+ if strings.HasPrefix(line, a) {
+ return strings.TrimSpace(strings.TrimPrefix(line, a)), true
+ }
+ if strings.HasPrefix(line, b) {
+ return strings.TrimSpace(strings.TrimPrefix(line, b)), true
+ }
+ return "", false
+ }
+ for _, line := range strings.Split(output, "\n") {
+ line = strings.TrimSpace(strings.Trim(line, "-* "))
+ if rest, ok := cut(line, "结论:", "结论:"); ok && h.Conclusion == "" {
+ h.Conclusion = rest
+ continue
+ }
+ if rest, ok := cut(line, "产物:", "产物:"); ok && rest != "" && rest != "无" {
+ h.Artifacts = append(h.Artifacts, rest)
+ continue
+ }
+ if rest, ok := cut(line, "未决问题:", "未决问题:"); ok && rest != "" && rest != "无" {
+ h.OpenQuestions = append(h.OpenQuestions, rest)
+ }
+ }
+ if h.Conclusion == "" {
+ head := strings.TrimSpace(strings.SplitN(firstNonEmpty(summary, output), "\n", 2)[0])
+ h.Conclusion = roomTrim(head, 200)
+ }
+ if q := crewQuestion(output); q != "" {
+ h.OpenQuestions = append(h.OpenQuestions, q)
+ }
+ return h
+}
+
+func crewHandoffBlock(t domain.CrewTask) string {
+ h := t.Handoff
+ if h == nil {
+ h = parseCrewHandoff("", t.Summary)
+ }
+ arts := "无"
+ if len(h.Artifacts) > 0 {
+ arts = strings.Join(h.Artifacts, ";")
+ }
+ open := "无"
+ if len(h.OpenQuestions) > 0 {
+ open = strings.Join(h.OpenQuestions, ";")
+ }
+ return "### " + t.AgentName + "「" + t.Title + "」\n结论:" + roomTrim(h.Conclusion, 400) + "\n产物:" + arts + "\n未决问题:" + open
+}
+
+func (h *roomsHandlers) fallbackBot(projectID string, userID int64, skipID string) (domain.AgentDefinition, string) {
+ reason := "不可用"
+ for _, st := range h.botStatuses(projectID, userID) {
+ if st.AgentID == skipID && st.Reason != "" {
+ reason = st.Reason
+ }
+ }
+ for _, a := range h.crewRoster(projectID, userID) {
+ if a.ID != skipID {
+ return a, reason
+ }
+ }
+ return domain.AgentDefinition{}, reason
+}
+
func crewMention(name string) string {
if i := strings.Index(name, "("); i > 0 {
return name[:i]
@@ -525,11 +726,11 @@ func crewBrief(m *domain.CrewMission, t *domain.CrewTask) string {
var done []string
for _, prev := range m.Tasks {
if prev.Status == "succeeded" && prev.ID != t.ID {
- done = append(done, "### "+prev.AgentName+"「"+prev.Title+"」\n"+roomTrim(firstNonEmpty(prev.Output, prev.Summary), 2500))
+ done = append(done, crewHandoffBlock(prev))
}
}
if len(done) > 0 {
- b.WriteString("\n## 队友已经交付的\n" + strings.Join(done, "\n\n") + "\n")
+ b.WriteString("\n## 交接单(只含结论、产物、未决问题,不含完整过程)\n" + strings.Join(done, "\n\n") + "\n")
}
var notes []string
for i := range m.Notes {
@@ -539,7 +740,7 @@ func crewBrief(m *domain.CrewMission, t *domain.CrewTask) string {
if len(notes) > 0 {
b.WriteString("\n## 群里同事的要求(必须遵守)\n" + strings.Join(notes, "\n") + "\n")
}
- b.WriteString("\n## 回复方式\n- 第一行写一句话结论,下面列要点;结果会原样发到群里给大家看。\n- 缺关键信息没法继续时,单独一行写「需要确认:你的问题」,队长会去群里问人。\n")
+ b.WriteString("\n## 回复方式\n用交接单收尾,下一步只能看到这三项,不要贴完整过程:\n结论:一句话\n产物:文件或结果,没有就写无\n未决问题:没有就写无\n缺关键信息时另起一行写「需要确认:你的问题」。\n")
return b.String()
}
@@ -552,6 +753,9 @@ func (h *roomsHandlers) startCrewTask(msg domain.ChatMessage, t *domain.CrewTask
if _, ok := h.repo.Agent(t.AgentID); !ok {
return fmt.Errorf("角色 %s 不存在", t.AgentID)
}
+ if h.useCrewFakeStream(m.ID) {
+ return h.openCrewFakeStep(msg, t)
+ }
// Each finished step closes the delivery loop on the issue; the mission
// is not done yet, so reopen it for the next bot. A person closing the
// issue by hand still blocks the mission.
@@ -574,6 +778,7 @@ func (h *roomsHandlers) startCrewTask(msg domain.ChatMessage, t *domain.CrewTask
return err
}
t.Status, t.RunID, t.WorkflowID, t.StartedAt, t.Error = "running", task.RunID, wf.ID, time.Now().UTC(), ""
+ h.attachCrewRunStream(msg, t)
return nil
}
@@ -630,12 +835,19 @@ func (h *roomsHandlers) crewAction(c *gin.Context) {
if err == nil {
h.saveCrew(msg)
}
+ missionID := msg.ID
+ running := err == nil && msg.Crew != nil && msg.Crew.Status == "running"
+ fake := h.useCrewFakeStream(missionID)
h.crewMu.Unlock()
if err != nil {
respond(c, err)
return
}
- h.ensureCrewLoop()
+ if running && fake {
+ go h.launchNextCrewStep(missionID)
+ } else {
+ h.ensureCrewLoop()
+ }
c.JSON(http.StatusOK, msg)
}
@@ -655,7 +867,21 @@ func (h *roomsHandlers) applyCrewAction(msg *domain.ChatMessage, req crewActionR
return HTTPError{http.StatusConflict, "任务已经结束"}
}
for i := range m.Tasks {
- if m.Tasks[i].Status == "running" && m.Tasks[i].RunID != "" {
+ if m.Tasks[i].Status != "running" {
+ continue
+ }
+ if m.Tasks[i].StreamPost != "" || strings.HasPrefix(m.Tasks[i].RunID, crewStreamPrefix) {
+ id := m.Tasks[i].StreamPost
+ if id == "" {
+ id = strings.TrimPrefix(m.Tasks[i].RunID, crewStreamPrefix)
+ }
+ if st := h.streamHub().get(id); st != nil && st.cancel != nil {
+ st.cancel()
+ }
+ m.Tasks[i].Status = "skipped"
+ continue
+ }
+ if m.Tasks[i].RunID != "" && h.engine != nil {
_ = h.engine.Cancel(m.Tasks[i].RunID)
m.Tasks[i].Status = "skipped"
}
@@ -731,8 +957,22 @@ func (h *roomsHandlers) crewResolveStuck(msg *domain.ChatMessage, action, author
}
h.crewSay(*msg, crewCaptain, "", "好,跳过「"+stuck.Title+"」,继续往下。", "", "")
case action == "retry" && stuck.Status == "failed":
+ var prior []string
+ for _, prev := range m.Tasks {
+ if prev.ID == stuck.ID || prev.Status != "succeeded" || prev.Handoff == nil {
+ continue
+ }
+ prior = append(prior, crewHandoffBlock(prev))
+ }
+ if stuck.Handoff != nil {
+ prior = append(prior, "上次做到:"+crewHandoffBlock(*stuck))
+ }
+ if len(prior) > 0 && !strings.Contains(stuck.Instruction, "交接单") {
+ stuck.Instruction = strings.TrimSpace(stuck.Instruction + "\n\n交接单(接着做,不要重头推翻):\n" + strings.Join(prior, "\n\n"))
+ }
stuck.Status, stuck.Error, stuck.RunID = "pending", "", ""
- h.crewSay(*msg, crewCaptain, "", "让 "+stuck.AgentName+" 再试一次「"+stuck.Title+"」。", "", "")
+ h.crewAudit(m.IssueID, author, "resume", "从「"+stuck.Title+"」接着做,带上已有交接")
+ h.crewSay(*msg, crewCaptain, "", "让 "+stuck.AgentName+" 再试一次「"+stuck.Title+"」,交接单还在。", "", "")
default:
if stuck.Status == "failed" {
stuck.Status = "skipped"
@@ -767,7 +1007,7 @@ func (h *roomsHandlers) crewInsertNext(m *domain.CrewMission, t domain.CrewTask)
// post adds a step for it, any message unblocks a waiting mission, and a reply
// to a mission's messages is handed to the next bot as a requirement.
// Plain chatter between people is left alone.
-func (h *roomsHandlers) crewHear(room domain.ChatRoom, said domain.ChatMessage) {
+func (h *roomsHandlers) crewHear(room domain.ChatRoom, said domain.ChatMessage, spec *fakeModelSpec) {
body := strings.TrimSpace(said.Body)
quoted, hasQuote := domain.ChatMessage{}, false
if said.ReplyTo != "" {
@@ -780,7 +1020,7 @@ func (h *roomsHandlers) crewHear(room domain.ChatRoom, said domain.ChatMessage)
if strings.HasPrefix(lower, "@loopforge") {
goal := strings.TrimSpace(body[len("@loopforge"):])
if goal == "" || crewWantsAnswer(goal) {
- h.answerInRoom(room, said, firstNonEmpty(goal, "你好,你能做什么?"))
+ h.answerInRoom(room, said, firstNonEmpty(goal, "你好,你能做什么?"), spec)
return
}
{
@@ -789,7 +1029,7 @@ func (h *roomsHandlers) crewHear(room domain.ChatRoom, said domain.ChatMessage)
if len(lines) > 1 {
detail = lines[1]
}
- if _, err := h.startCrewMission(room, said.UserID, said.Author, crewRequest{Goal: lines[0], Detail: detail, Source: "chat"}); err != nil {
+ if _, err := h.startCrewMission(room, said.UserID, said.Author, crewRequest{Goal: lines[0], Detail: detail, Source: "chat", FakeModel: spec}); err != nil {
h.crewSay(domain.ChatMessage{RoomID: room.ID}, crewCaptain, "", "没能接这个活:"+err.Error(), "", "")
}
}
@@ -836,7 +1076,23 @@ func (h *roomsHandlers) crewHear(room domain.ChatRoom, said domain.ChatMessage)
continue
}
if !usable[a.ID] {
- h.crewSay(msg, crewCaptain, "", name+" 现在叫不动:它用的模型 CLI 还没配 Key。去「设置 · 个人设置」配好后再 @ 它。", "", "")
+ fb, reason := h.fallbackBot(room.ProjectID, m.StartedBy, a.ID)
+ if fb.ID == "" {
+ h.crewSay(msg, crewCaptain, "", name+" 不可用:"+reason+"。现在没有能接替的 Bot。", "", "")
+ return
+ }
+ from := name
+ a = fb
+ name = crewAgentName(a)
+ ask := strings.TrimSpace(strings.Replace(body, "@"+from, "", 1))
+ t := domain.CrewTask{AgentID: a.ID, AgentName: name, Title: roomTrim(firstNonEmpty(strings.SplitN(ask, "\n", 2)[0], "按群里的要求补一步"), 24), Instruction: ask, Status: "pending", AddedBy: said.Author, ReassignedFrom: from, ReassignedReason: reason}
+ m.Tasks = append(m.Tasks, t)
+ for i := range m.Tasks {
+ m.Tasks[i].ID = fmt.Sprintf("t%d", i+1)
+ }
+ h.crewSay(msg, crewCaptain, "", "已改由 "+name+" 负责("+from+" "+reason+")。给它加了一步「"+t.Title+"」。", "", "")
+ h.saveCrew(msg)
+ h.ensureCrewLoop()
return
}
if len(m.Tasks) >= crewMaxTasks {
diff --git a/internal/httpapi/room_crew_test.go b/internal/httpapi/room_crew_test.go
index 36164427..f1b9206e 100644
--- a/internal/httpapi/room_crew_test.go
+++ b/internal/httpapi/room_crew_test.go
@@ -1,6 +1,7 @@
package httpapi
import (
+ "strings"
"testing"
"github.com/Tencent/LoopForge/internal/domain"
@@ -26,6 +27,9 @@ func TestCrewPlanRulesSplitsRolesByName(t *testing.T) {
t.Fatalf("plan = %v, want %v", got, want)
}
}
+ if tasks[0].PlanReason == "" || !strings.Contains(tasks[0].PlanReason, "拆解需求") {
+ t.Fatalf("plan reason = %q", tasks[0].PlanReason)
+ }
}
func TestCrewQuestionFindsAsk(t *testing.T) {
diff --git a/internal/httpapi/room_phase2_test.go b/internal/httpapi/room_phase2_test.go
new file mode 100644
index 00000000..fb77ee28
--- /dev/null
+++ b/internal/httpapi/room_phase2_test.go
@@ -0,0 +1,226 @@
+package httpapi
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/LoopForge/internal/auth"
+ "github.com/Tencent/LoopForge/internal/domain"
+ "github.com/Tencent/LoopForge/internal/engine"
+ "github.com/Tencent/LoopForge/internal/repo"
+ "github.com/Tencent/LoopForge/internal/runtime"
+ "github.com/Tencent/LoopForge/internal/tracker"
+)
+
+func TestCrewHandoffOmitsTranscript(t *testing.T) {
+ prev := domain.CrewTask{
+ ID: "t1", Status: "succeeded", AgentName: "甲", Title: "方案",
+ Output: "SECRET TRANSCRIPT\n" + strings.Repeat("过程", 800), Summary: "一句结论",
+ Handoff: &domain.CrewHandoff{Conclusion: "定价用阶梯", Artifacts: []string{"notes.md"}, OpenQuestions: []string{"税怎么算"}},
+ }
+ next := domain.CrewTask{ID: "t2", AgentName: "乙", Title: "实现"}
+ brief := crewBrief(&domain.CrewMission{Goal: "定价", Tasks: []domain.CrewTask{prev, next}}, &next)
+ if strings.Contains(brief, "SECRET") || strings.Contains(brief, "过程过程") {
+ t.Fatalf("handoff leaked the transcript:\n%s", brief)
+ }
+ for _, want := range []string{"定价用阶梯", "notes.md", "税怎么算", "结论:", "产物:", "未决问题:"} {
+ if !strings.Contains(brief, want) {
+ t.Fatalf("brief missing %q:\n%s", want, brief)
+ }
+ }
+}
+
+func TestRoomThreadLinesSkipMainTimeline(t *testing.T) {
+ all := []domain.ChatMessage{
+ {ID: "a", Author: "旁人", Body: "无关的主时间线"},
+ {ID: "p", Author: "甲", Body: "线程里的上一条"},
+ {ID: "q", Author: "乙", Body: "接着问", ParentID: "p"},
+ }
+ got := strings.Join(roomThreadLines(all, all[2]), "\n")
+ if strings.Contains(got, "无关") {
+ t.Fatalf("thread context included the main timeline: %s", got)
+ }
+ if !strings.Contains(got, "parent_id=p") || !strings.Contains(got, "线程里的上一条") {
+ t.Fatalf("thread context: %s", got)
+ }
+}
+
+func TestParseCrewHandoffFields(t *testing.T) {
+ got := parseCrewHandoff("结论:可以交付\n产物:api.md\n未决问题:无\nSECRET 不该进结论以外的字段", "")
+ if got.Conclusion != "可以交付" || len(got.Artifacts) != 1 || got.Artifacts[0] != "api.md" || len(got.OpenQuestions) != 0 {
+ t.Fatalf("handoff: %+v", got)
+ }
+}
+
+func phase2Handler(t *testing.T) (*repo.Store, http.Handler, domain.User) {
+ t.Helper()
+ t.Setenv("LOOPFORGE_SESSION_SECRET", "room-phase2-session-secret")
+ t.Setenv("LOOPFORGE_FAKE_MODEL", "1")
+ s, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { s.Close() })
+ if err := s.PutAgent(domain.AgentDefinition{ID: "standin", Name: "开发实现", ProjectID: "platform", Shared: true, ExecutorID: "mock", Description: "演示执行器", Instructions: "实现"}); err != nil {
+ t.Fatal(err)
+ }
+ h := New(s, engine.New(s, runtime.NewManager(t.TempDir())), tracker.NewService(), "", "")
+ owner, _ := s.User(1)
+ return s, h, owner
+}
+
+func TestBotStatusAndMentionReassign(t *testing.T) {
+ _, h, owner := phase2Handler(t)
+ room := requestJSONAuthed[domain.ChatRoomView](t, h, owner, http.MethodPost, "/api/rooms", map[string]any{"projectId": "platform", "name": "状态群"}, http.StatusCreated)
+ rows := requestJSONAuthed[[]botStatusView](t, h, owner, http.MethodGet, "/api/bots/status?projectId=platform", nil, http.StatusOK)
+ var dev, stand botStatusView
+ for _, row := range rows {
+ if row.AgentID == "developer" {
+ dev = row
+ }
+ if row.AgentID == "standin" {
+ stand = row
+ }
+ if row.HeartbeatAt.IsZero() {
+ t.Fatalf("missing heartbeat: %+v", row)
+ }
+ }
+ if dev.Status != "unavailable" || dev.Reason != "缺 Key" {
+ t.Fatalf("developer status: %+v", dev)
+ }
+ if stand.Status != "online" {
+ t.Fatalf("mock bot status: %+v", stand)
+ }
+ msg := requestJSONAuthed[domain.ChatMessage](t, h, owner, http.MethodPost, "/api/rooms/"+room.ID+"/messages", map[string]any{"body": "@实现工程师 帮我看一下"}, http.StatusCreated)
+ if !strings.Contains(msg.Body, "@开发实现") || !strings.Contains(msg.ReassignNote, "已改由 开发实现 负责") {
+ t.Fatalf("mention was not reassigned: %+v", msg)
+ }
+}
+
+func TestCrewPlanCardNamesReassignment(t *testing.T) {
+ _, h, owner := phase2Handler(t)
+ room := requestJSONAuthed[domain.ChatRoomView](t, h, owner, http.MethodPost, "/api/rooms", map[string]any{"projectId": "platform", "name": "分工群"}, http.StatusCreated)
+ requestJSONAuthed[domain.ChatMessage](t, h, owner, http.MethodPost, "/api/rooms/"+room.ID+"/messages", map[string]any{"body": "@LoopForge 实现登录页"}, http.StatusCreated)
+ deadline := time.Now().Add(4 * time.Second)
+ for time.Now().Before(deadline) {
+ messages := requestJSONAuthed[[]domain.ChatMessage](t, h, owner, http.MethodGet, "/api/rooms/"+room.ID+"/messages", nil, http.StatusOK)
+ for _, m := range messages {
+ if m.Crew == nil {
+ continue
+ }
+ for _, task := range m.Crew.Tasks {
+ if task.ReassignedFrom != "" && strings.Contains(task.AgentName, "开发实现") {
+ return
+ }
+ }
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ t.Fatal("crew plan did not record 已改由")
+}
+
+func TestFakeModelStreamsFirstTokenAndStop(t *testing.T) {
+ _, h, owner := phase2Handler(t)
+ ts := httptest.NewServer(h)
+ t.Cleanup(ts.Close)
+ token, err := auth.NewClientFromEnv().SignUser(&auth.User{ID: owner.ID, LoginName: owner.LoginName, AuthTime: time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ room := requestJSONAuthed[domain.ChatRoomView](t, h, owner, http.MethodPost, "/api/rooms", map[string]any{"projectId": "platform", "name": "流式群"}, http.StatusCreated)
+ requestJSONAuthed[domain.ChatMessage](t, h, owner, http.MethodPost, "/api/rooms/"+room.ID+"/messages", map[string]any{
+ "body": "@LoopForge 你好",
+ "fakeModel": map[string]any{"text": "甲乙丙", "firstTokenMs": 40, "tokenMs": 20, "stallAfter": 1, "stallMs": 4000},
+ }, http.StatusCreated)
+ var pending domain.ChatMessage
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ messages := requestJSONAuthed[[]domain.ChatMessage](t, h, owner, http.MethodGet, "/api/rooms/"+room.ID+"/messages", nil, http.StatusOK)
+ for _, m := range messages {
+ if m.Pending && m.Kind == domain.ChatKindCrewPost {
+ pending = m
+ }
+ }
+ if pending.ID != "" {
+ break
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ if pending.ID == "" {
+ t.Fatal("pending reply was not created")
+ }
+ ctxReq, err := http.NewRequest(http.MethodGet, ts.URL+"/api/rooms/"+room.ID+"/messages/"+pending.ID+"/stream", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctxReq.AddCookie(&http.Cookie{Name: authCookieName, Value: token})
+ started := time.Now()
+ type result struct {
+ body string
+ err error
+ }
+ ch := make(chan result, 1)
+ go func() {
+ res, err := http.DefaultClient.Do(ctxReq)
+ if err != nil {
+ ch <- result{err: err}
+ return
+ }
+ defer res.Body.Close()
+ raw, err := io.ReadAll(res.Body)
+ ch <- result{body: string(raw), err: err}
+ }()
+ time.Sleep(120 * time.Millisecond)
+ stopReq, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/rooms/"+room.ID+"/messages/"+pending.ID+"/stop", strings.NewReader(`{}`))
+ stopReq.Header.Set("Content-Type", "application/json")
+ stopReq.AddCookie(&http.Cookie{Name: authCookieName, Value: token})
+ stopRes, err := http.DefaultClient.Do(stopReq)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stopRes.Body.Close()
+ if stopRes.StatusCode != http.StatusOK {
+ t.Fatalf("stop status %d", stopRes.StatusCode)
+ }
+ select {
+ case got := <-ch:
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ if time.Since(started) > 1500*time.Millisecond {
+ t.Fatalf("first token path took %s", time.Since(started))
+ }
+ if !strings.Contains(got.body, "event: token") || !strings.Contains(got.body, "甲") {
+ t.Fatalf("stream body:\n%s", got.body)
+ }
+ if !strings.Contains(got.body, "event: stopped") {
+ t.Fatalf("stop did not end the stream:\n%s", got.body)
+ }
+ if strings.Contains(got.body, "丙") {
+ t.Fatalf("stall token leaked after stop:\n%s", got.body)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("stream did not finish after stop")
+ }
+}
+
+func TestFakeModelGate(t *testing.T) {
+ t.Setenv("LOOPFORGE_FAKE_MODEL", "1")
+ t.Setenv("LOOPFORGE_DEMO_MODE", "")
+ if !fakeModelAllowed() {
+ t.Fatal("LOOPFORGE_FAKE_MODEL should enable the mock")
+ }
+ t.Setenv("LOOPFORGE_FAKE_MODEL", "")
+ t.Setenv("LOOPFORGE_DEMO_MODE", "true")
+ if !fakeModelAllowed() {
+ t.Fatal("demo mode should enable the mock for e2e")
+ }
+ t.Setenv("LOOPFORGE_DEMO_MODE", "")
+ if fakeModelAllowed() {
+ t.Fatal("fake model must stay off in production")
+ }
+}
diff --git a/internal/httpapi/room_phase3_test.go b/internal/httpapi/room_phase3_test.go
new file mode 100644
index 00000000..25222e3e
--- /dev/null
+++ b/internal/httpapi/room_phase3_test.go
@@ -0,0 +1,123 @@
+package httpapi
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/LoopForge/internal/auth"
+ "github.com/Tencent/LoopForge/internal/domain"
+)
+
+func TestCrewStepStreamsFailRetryAndSOP(t *testing.T) {
+ s, h, owner := phase2Handler(t)
+ if err := s.PutAgent(domain.AgentDefinition{ID: "analyst", Name: "需求分析", ProjectID: "platform", Shared: true, ExecutorID: "mock", Description: "拆解需求", Instructions: "分析"}); err != nil {
+ t.Fatal(err)
+ }
+ ts := httptest.NewServer(h)
+ t.Cleanup(ts.Close)
+ token, err := auth.NewClientFromEnv().SignUser(&auth.User{ID: owner.ID, LoginName: owner.LoginName, AuthTime: time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ room := requestJSONAuthed[domain.ChatRoomView](t, h, owner, http.MethodPost, "/api/rooms", map[string]any{"projectId": "platform", "name": "协作流"}, http.StatusCreated)
+ started := time.Now()
+ requestJSONAuthed[domain.ChatMessage](t, h, owner, http.MethodPost, "/api/rooms/"+room.ID+"/messages", map[string]any{
+ "body": "@LoopForge 实现登录页",
+ "fakeModel": map[string]any{"crewStep": true, "failStep": 2, "firstTokenMs": 40, "tokenMs": 4},
+ }, http.StatusCreated)
+
+ var mission domain.ChatMessage
+ var first domain.ChatMessage
+ deadline := time.Now().Add(1500 * time.Millisecond)
+ for time.Now().Before(deadline) {
+ messages := requestJSONAuthed[[]domain.ChatMessage](t, h, owner, http.MethodGet, "/api/rooms/"+room.ID+"/messages", nil, http.StatusOK)
+ for _, m := range messages {
+ if m.Kind == domain.ChatKindCrew && m.Crew != nil {
+ mission = m
+ }
+ if m.Kind == domain.ChatKindCrewPost && m.AgentID != "" && strings.Contains(m.Body, "结论") {
+ first = m
+ }
+ }
+ if mission.ID != "" && first.ID != "" {
+ break
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ if mission.ID == "" || first.ID == "" {
+ t.Fatalf("crew step did not stream a handoff within %s", time.Since(started))
+ }
+ if time.Since(started) > 1500*time.Millisecond {
+ t.Fatalf("first crew token took %s", time.Since(started))
+ }
+
+ ctxReq, err := http.NewRequest(http.MethodGet, ts.URL+"/api/rooms/"+room.ID+"/messages/"+first.ID+"/stream", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctxReq.AddCookie(&http.Cookie{Name: authCookieName, Value: token})
+ res, err := http.DefaultClient.Do(ctxReq)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "event: token") && !strings.Contains(string(raw), "event: done") {
+ t.Fatalf("crew stream:\n%s", raw)
+ }
+
+ var failed domain.ChatMessage
+ deadline = time.Now().Add(4 * time.Second)
+ for time.Now().Before(deadline) {
+ messages := requestJSONAuthed[[]domain.ChatMessage](t, h, owner, http.MethodGet, "/api/rooms/"+room.ID+"/messages", nil, http.StatusOK)
+ for _, m := range messages {
+ if m.Kind == domain.ChatKindCrewPost && m.Error != "" {
+ failed = m
+ }
+ if m.ID == mission.ID && m.Crew != nil {
+ mission = m
+ }
+ }
+ if failed.ID != "" && mission.Crew != nil && mission.Crew.Status == "waiting" {
+ break
+ }
+ time.Sleep(30 * time.Millisecond)
+ }
+ if failed.ID == "" || mission.Crew == nil || mission.Crew.Status != "waiting" {
+ t.Fatalf("step 2 did not fail open: post=%q mission=%+v", failed.Error, mission.Crew)
+ }
+
+ requestJSONAuthed[domain.ChatMessage](t, h, owner, http.MethodPost, "/api/rooms/"+room.ID+"/crew/"+mission.ID, map[string]any{"action": "retry"}, http.StatusOK)
+ deadline = time.Now().Add(4 * time.Second)
+ for time.Now().Before(deadline) {
+ messages := requestJSONAuthed[[]domain.ChatMessage](t, h, owner, http.MethodGet, "/api/rooms/"+room.ID+"/messages", nil, http.StatusOK)
+ for _, m := range messages {
+ if m.ID == mission.ID && m.Crew != nil && m.Crew.Status == "done" {
+ mission = m
+ }
+ }
+ if mission.Crew != nil && mission.Crew.Status == "done" {
+ break
+ }
+ time.Sleep(30 * time.Millisecond)
+ }
+ if mission.Crew == nil || mission.Crew.Status != "done" {
+ t.Fatalf("crew did not finish after retry: %+v", mission.Crew)
+ }
+ for _, task := range mission.Crew.Tasks {
+ if task.Status == "succeeded" && !strings.HasPrefix(task.RunID, "stream:") {
+ t.Fatalf("succeeded step was not streamed: %+v", task)
+ }
+ }
+ saved := requestJSONAuthed[map[string]any](t, h, owner, http.MethodPost, "/api/rooms/"+room.ID+"/crew/"+mission.ID, map[string]any{"action": "sop"}, http.StatusOK)
+ if saved["workflowId"] == "" {
+ t.Fatalf("sop was not saved: %+v", saved)
+ }
+}
diff --git a/internal/httpapi/room_stream.go b/internal/httpapi/room_stream.go
new file mode 100644
index 00000000..b3053fb8
--- /dev/null
+++ b/internal/httpapi/room_stream.go
@@ -0,0 +1,433 @@
+package httpapi
+
+import (
+ "context"
+ "net/http"
+ "os"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "github.com/Tencent/LoopForge/internal/domain"
+ "github.com/gin-gonic/gin"
+)
+
+// fakeModelSpec drives the CI mock model. Ignored unless demo mode or
+// LOOPFORGE_FAKE_MODEL is on, so a production room cannot be told what to say.
+type fakeModelSpec struct {
+ Text string `json:"text"`
+ FirstTokenMs int `json:"firstTokenMs"`
+ TokenMs int `json:"tokenMs"`
+ StallAfter int `json:"stallAfter"`
+ StallMs int `json:"stallMs"`
+ DisconnectAfter int `json:"disconnectAfter"`
+ // CrewStep asks a demo/fake model to stream a bot step instead of the captain.
+ CrewStep bool `json:"crewStep"`
+ // FailStep is the 1-based crew step that errors once, so retry can continue.
+ FailStep int `json:"failStep"`
+ failUsed bool
+}
+
+func fakeModelAllowed() bool {
+ if envOn("LOOPFORGE_FAKE_MODEL") || envOn("LOOPFORGE_DEMO_MODE") {
+ return true
+ }
+ return false
+}
+
+func envOn(key string) bool {
+ switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) {
+ case "1", "true", "yes", "on":
+ return true
+ }
+ return false
+}
+
+type roomStreamEvent struct {
+ Type string `json:"type"`
+ Text string `json:"text,omitempty"`
+ Seq int `json:"seq"`
+}
+
+type roomStreamHub struct {
+ mu sync.Mutex
+ byID map[string]*roomTokenStream
+}
+
+func newRoomStreamHub() *roomStreamHub {
+ return &roomStreamHub{byID: map[string]*roomTokenStream{}}
+}
+
+func (h *roomsHandlers) streamHub() *roomStreamHub {
+ h.streamsOnce.Do(func() { h.streams = newRoomStreamHub() })
+ return h.streams
+}
+
+type roomTokenStream struct {
+ mu sync.Mutex
+ events []roomStreamEvent
+ subs []chan roomStreamEvent
+ cancel context.CancelFunc
+ closed bool
+ spec *fakeModelSpec
+ question string
+ roomID string
+ userID int64
+}
+
+func (s *roomTokenStream) publish(ev roomStreamEvent) {
+ s.mu.Lock()
+ ev.Seq = len(s.events) + 1
+ s.events = append(s.events, ev)
+ subs := append([]chan roomStreamEvent(nil), s.subs...)
+ s.mu.Unlock()
+ for _, ch := range subs {
+ ch <- ev
+ }
+}
+
+func (s *roomTokenStream) finish(ev roomStreamEvent) {
+ s.mu.Lock()
+ if s.closed {
+ s.mu.Unlock()
+ return
+ }
+ s.closed = true
+ ev.Seq = len(s.events) + 1
+ s.events = append(s.events, ev)
+ subs := s.subs
+ s.subs = nil
+ s.mu.Unlock()
+ for _, ch := range subs {
+ ch <- ev
+ close(ch)
+ }
+}
+
+func (s *roomTokenStream) unsubscribe(ch chan roomStreamEvent) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ next := s.subs[:0]
+ for _, sub := range s.subs {
+ if sub != ch {
+ next = append(next, sub)
+ }
+ }
+ s.subs = next
+}
+
+func (s *roomTokenStream) subscribe() (chan roomStreamEvent, []roomStreamEvent) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ replay := append([]roomStreamEvent(nil), s.events...)
+ if s.closed {
+ return nil, replay
+ }
+ ch := make(chan roomStreamEvent, 64)
+ s.subs = append(s.subs, ch)
+ return ch, replay
+}
+
+func (h *roomStreamHub) open(id, roomID, question string, userID int64, spec *fakeModelSpec, cancel context.CancelFunc) *roomTokenStream {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if old := h.byID[id]; old != nil && old.cancel != nil {
+ old.cancel()
+ }
+ st := &roomTokenStream{cancel: cancel, spec: spec, question: question, roomID: roomID, userID: userID}
+ h.byID[id] = st
+ return st
+}
+
+func (h *roomStreamHub) get(id string) *roomTokenStream {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.byID[id]
+}
+
+func (h *roomsHandlers) streamMessage(c *gin.Context) {
+ room, msg, ok := h.roomMessage(c)
+ if !ok {
+ return
+ }
+ if !h.roomAccess(c, room.ProjectID, false) {
+ return
+ }
+ c.Header("Content-Type", "text/event-stream; charset=utf-8")
+ c.Header("Cache-Control", "no-cache, no-transform")
+ c.Header("Connection", "keep-alive")
+ c.Header("X-Accel-Buffering", "no")
+ st := h.streamHub().get(msg.ID)
+ if st == nil {
+ writeSSE(c, "done", roomStreamEvent{Type: "done", Text: msg.Body})
+ return
+ }
+ live, replay := st.subscribe()
+ if live != nil {
+ defer st.unsubscribe(live)
+ }
+ for _, ev := range replay {
+ writeSSE(c, ev.Type, ev)
+ if roomStreamTerminal(ev.Type) {
+ return
+ }
+ }
+ if live == nil {
+ return
+ }
+ ping := time.NewTicker(15 * time.Second)
+ defer ping.Stop()
+ for {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ case <-ping.C:
+ writeSSE(c, "ping", roomStreamEvent{Type: "ping"})
+ case ev, open := <-live:
+ if !open {
+ return
+ }
+ writeSSE(c, ev.Type, ev)
+ if roomStreamTerminal(ev.Type) {
+ return
+ }
+ }
+ }
+}
+
+func roomStreamTerminal(kind string) bool {
+ return kind == "done" || kind == "error" || kind == "stopped"
+}
+
+func (h *roomsHandlers) stopMessage(c *gin.Context) {
+ room, msg, ok := h.roomMessage(c)
+ if !ok {
+ return
+ }
+ if !h.roomAccess(c, room.ProjectID, true) {
+ return
+ }
+ st := h.streamHub().get(msg.ID)
+ if st == nil || st.cancel == nil {
+ c.JSON(http.StatusConflict, gin.H{"error": "这条回复没有正在进行的输出"})
+ return
+ }
+ st.cancel()
+ c.JSON(http.StatusOK, gin.H{"ok": true})
+}
+
+func (h *roomsHandlers) retryMessage(c *gin.Context) {
+ room, msg, ok := h.roomMessage(c)
+ if !ok {
+ return
+ }
+ if !h.roomAccess(c, room.ProjectID, true) {
+ return
+ }
+ if msg.Kind != domain.ChatKindCrewPost {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "只能重试 Bot 的回复"})
+ return
+ }
+ if msg.AgentID != "" && msg.CrewID != "" {
+ h.restartCrewPost(msg)
+ fresh, _ := h.repo.Message(msg.ID)
+ c.JSON(http.StatusOK, fresh)
+ return
+ }
+ prev := h.streamHub().get(msg.ID)
+ spec := (*fakeModelSpec)(nil)
+ question := ""
+ userID := msg.UserID
+ if prev != nil {
+ if prev.cancel != nil {
+ prev.cancel()
+ }
+ spec, question, userID = prev.spec, prev.question, prev.userID
+ }
+ if question == "" {
+ question = firstNonEmpty(msg.ReplyText, "再答一次")
+ }
+ msg.Body = ""
+ msg.Pending = true
+ msg.NodeStatus = ""
+ if err := h.repo.PutMessage(msg); err != nil {
+ respond(c, err)
+ return
+ }
+ said := domain.ChatMessage{ID: msg.ReplyTo, RoomID: room.ID, UserID: userID, Author: msg.ReplyAuthor, Body: question, ParentID: msg.ParentID, ReplyTo: msg.ParentID}
+ h.beginReplyStream(room, said, msg, question, spec)
+ c.JSON(http.StatusOK, msg)
+}
+
+func (h *roomsHandlers) roomMessage(c *gin.Context) (domain.ChatRoom, domain.ChatMessage, bool) {
+ room, ok := h.repo.Room(c.Param("id"))
+ if !ok {
+ c.JSON(http.StatusNotFound, gin.H{"error": "room not found"})
+ return domain.ChatRoom{}, domain.ChatMessage{}, false
+ }
+ msg, ok := h.repo.Message(c.Param("mid"))
+ if !ok || msg.RoomID != room.ID {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return domain.ChatRoom{}, domain.ChatMessage{}, false
+ }
+ return room, msg, true
+}
+
+// beginReplyStream writes tokens onto reply until the model finishes, the
+// caller stops it, or the fake model disconnects.
+func (h *roomsHandlers) beginReplyStream(room domain.ChatRoom, said domain.ChatMessage, reply domain.ChatMessage, question string, spec *fakeModelSpec) {
+ ctx, cancel := context.WithCancel(context.Background())
+ st := h.streamHub().open(reply.ID, room.ID, question, said.UserID, spec, cancel)
+ go func() {
+ defer cancel()
+ var b strings.Builder
+ emit := func(tok string) bool {
+ if tok == "" {
+ return true
+ }
+ select {
+ case <-ctx.Done():
+ return false
+ default:
+ }
+ b.WriteString(tok)
+ st.publish(roomStreamEvent{Type: "token", Text: tok})
+ if b.Len()%24 == 0 {
+ reply.Body = b.String()
+ _ = h.repo.PutMessage(reply)
+ }
+ return true
+ }
+ var err error
+ if spec != nil {
+ err = runFakeModel(ctx, *spec, emit)
+ } else {
+ err = h.streamCaptain(ctx, room, said, question, emit, &b)
+ }
+ reply.Body = strings.TrimSpace(b.String())
+ reply.Pending = false
+ switch {
+ case ctx.Err() != nil:
+ reply.NodeStatus = "stopped"
+ _ = h.repo.PutMessage(reply)
+ st.finish(roomStreamEvent{Type: "stopped", Text: reply.Body})
+ case err != nil:
+ reply.NodeStatus = "error"
+ if reply.Body == "" {
+ reply.Body = err.Error()
+ }
+ _ = h.repo.PutMessage(reply)
+ st.finish(roomStreamEvent{Type: "error", Text: err.Error()})
+ default:
+ _ = h.repo.PutMessage(reply)
+ st.finish(roomStreamEvent{Type: "done", Text: reply.Body})
+ }
+ }()
+}
+
+func runFakeModel(ctx context.Context, spec fakeModelSpec, emit func(string) bool) error {
+ text := spec.Text
+ if strings.TrimSpace(text) == "" {
+ text = "这是一条模拟流式回复。"
+ }
+ tokens := make([]string, 0, utf8.RuneCountInString(text))
+ for _, r := range text {
+ tokens = append(tokens, string(r))
+ }
+ first := time.Duration(spec.FirstTokenMs) * time.Millisecond
+ if first <= 0 {
+ first = 200 * time.Millisecond
+ }
+ gap := time.Duration(spec.TokenMs) * time.Millisecond
+ if gap <= 0 {
+ gap = 40 * time.Millisecond
+ }
+ if !waitCtx(ctx, first) {
+ return ctx.Err()
+ }
+ for i, tok := range tokens {
+ n := i + 1
+ if spec.DisconnectAfter > 0 && n > spec.DisconnectAfter {
+ return errFakeDisconnect
+ }
+ if spec.StallAfter > 0 && n == spec.StallAfter+1 && spec.StallMs > 0 {
+ if !waitCtx(ctx, time.Duration(spec.StallMs)*time.Millisecond) {
+ return ctx.Err()
+ }
+ }
+ if !emit(tok) {
+ return ctx.Err()
+ }
+ if n == len(tokens) {
+ break
+ }
+ if !waitCtx(ctx, gap) {
+ return ctx.Err()
+ }
+ }
+ return nil
+}
+
+var errFakeDisconnect = fakeDisconnectError{}
+
+type fakeDisconnectError struct{}
+
+func (fakeDisconnectError) Error() string { return "模拟模型中途断开" }
+
+func waitCtx(ctx context.Context, d time.Duration) bool {
+ if d <= 0 {
+ return ctx.Err() == nil
+ }
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return false
+ case <-t.C:
+ return true
+ }
+}
+
+func (h *roomsHandlers) streamCaptain(ctx context.Context, room domain.ChatRoom, said domain.ChatMessage, question string, emit func(string) bool, buf *strings.Builder) error {
+ user, ok := h.repo.User(said.UserID)
+ status := h.roomStatusDigest(room)
+ if !ok || strings.TrimSpace(user.CodeBuddyAPIKey) == "" || crewStatusAsk.MatchString(question) {
+ text := h.crewAnswer(room, said, question)
+ return emitRunes(ctx, text, emit)
+ }
+ var filter assistantStreamFilter
+ emitted := false
+ _, _, err := runAssistantCLI(ctx, assistantCLIRequest{Prompt: h.captainPrompt(room, said, question, status), Model: assistantDefaultModel, UserID: user.ID}, user, func(ev assistantStreamEvent) {
+ if !filter.accept(ev) || ev.Kind != "answer" || ev.Text == "" || ev.Full {
+ return
+ }
+ emitted = true
+ emit(ev.Text)
+ })
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ if !emitted {
+ text := h.crewAnswer(room, said, question)
+ if buf.Len() == 0 {
+ return emitRunes(ctx, text, emit)
+ }
+ }
+ if err != nil && buf.Len() == 0 {
+ return err
+ }
+ return nil
+}
+
+func emitRunes(ctx context.Context, text string, emit func(string) bool) error {
+ for _, r := range text {
+ if !emit(string(r)) {
+ return ctx.Err()
+ }
+ if !waitCtx(ctx, 12*time.Millisecond) {
+ return ctx.Err()
+ }
+ }
+ return nil
+}
diff --git a/internal/httpapi/rooms.go b/internal/httpapi/rooms.go
index 2d0be0c4..c52e9f0a 100644
--- a/internal/httpapi/rooms.go
+++ b/internal/httpapi/rooms.go
@@ -18,8 +18,14 @@ type roomsHandlers struct {
*deps
runCache roomRunCache
// crewMu serialises crew mission writes; crewLoopOn guards the captain loop.
- crewMu sync.Mutex
- crewLoopOn atomic.Bool
+ crewMu sync.Mutex
+ crewLoopOn atomic.Bool
+ crewSpecMu sync.Mutex
+ crewSpecs map[string]*fakeModelSpec
+ streamsOnce sync.Once
+ streams *roomStreamHub
+ pulseOnce sync.Once
+ pulse *botHealth
}
// roomMaxSOPs bounds one multi-SOP dispatch.
@@ -174,8 +180,10 @@ func (h *roomsHandlers) messages(c *gin.Context) {
c.JSON(http.StatusOK, messages)
case http.MethodPost:
var req struct {
- Body string `json:"body"`
- ReplyTo string `json:"replyTo"`
+ Body string `json:"body"`
+ ReplyTo string `json:"replyTo"`
+ ParentID string `json:"parentId"`
+ FakeModel *fakeModelSpec `json:"fakeModel"`
}
if !decode(c, &req) {
return
@@ -190,16 +198,34 @@ func (h *roomsHandlers) messages(c *gin.Context) {
return
}
userID, author := h.roomActor(c)
- msg := domain.ChatMessage{ID: newChatID("msg"), RoomID: room.ID, UserID: userID, Author: author, Kind: "text", Body: body, CreatedAt: time.Now().UTC()}
- if quoted, ok := h.repo.Message(strings.TrimSpace(req.ReplyTo)); ok && quoted.RoomID == room.ID {
+ body, note, err := h.rewriteRoomMentions(room.ProjectID, userID, body)
+ if err != nil {
+ respond(c, err)
+ return
+ }
+ msg := domain.ChatMessage{ID: newChatID("msg"), RoomID: room.ID, UserID: userID, Author: author, Kind: "text", Body: body, ParentID: strings.TrimSpace(req.ParentID), ReassignNote: note, CreatedAt: time.Now().UTC()}
+ if msg.ParentID == "" {
+ msg.ParentID = strings.TrimSpace(req.ReplyTo)
+ }
+ if quoted, ok := h.repo.Message(firstNonEmpty(strings.TrimSpace(req.ReplyTo), msg.ParentID)); ok && quoted.RoomID == room.ID {
msg.ReplyTo, msg.ReplyAuthor, msg.ReplyText = quoted.ID, roomQuoteAuthor(quoted), roomTrim(roomQuoteText(quoted), 200)
+ if msg.ParentID == "" {
+ msg.ParentID = quoted.ParentID
+ if msg.ParentID == "" {
+ msg.ParentID = quoted.ID
+ }
+ }
}
if err := h.repo.PutMessage(msg); err != nil {
respond(c, err)
return
}
h.touchRoom(room)
- h.crewHear(room, msg)
+ spec := req.FakeModel
+ if spec != nil && !fakeModelAllowed() {
+ spec = nil
+ }
+ h.crewHear(room, msg, spec)
c.JSON(http.StatusCreated, msg)
default:
c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "method not allowed"})
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index 72af2882..10b9a0a3 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -304,6 +304,10 @@ func New(s *repo.Store, e *engine.Engine, syncSvc *tracker.Service, basicUser, b
g.PATCH("/api/rooms/:id", rooms.room)
g.GET("/api/rooms/:id/messages", rooms.messages)
g.POST("/api/rooms/:id/messages", rooms.messages)
+ g.GET("/api/rooms/:id/messages/:mid/stream", rooms.streamMessage)
+ g.POST("/api/rooms/:id/messages/:mid/stop", rooms.stopMessage)
+ g.POST("/api/rooms/:id/messages/:mid/retry", rooms.retryMessage)
+ g.GET("/api/bots/status", rooms.botStatus)
g.POST("/api/rooms/:id/issues", rooms.createIssue)
g.POST("/api/rooms/:id/decisions", rooms.decide)
g.POST("/api/rooms/:id/crew", rooms.createCrew)
diff --git a/web/access.css b/web/access.css
index e76871b7..c87271b1 100644
--- a/web/access.css
+++ b/web/access.css
@@ -1,18 +1,18 @@
.access-summary{max-width:1180px;margin:0 auto 12px;display:flex;align-items:center;gap:18px;padding:13px 16px;border:1px solid var(--line);border-radius:13px;background:linear-gradient(135deg,var(--panel),var(--bg-soft));box-shadow:var(--shadow-sm)}
-.access-instance{display:flex;align-items:center;gap:11px;min-width:360px}.access-instance>span{width:38px;height:38px;display:grid;place-items:center;border-radius:10px;background:var(--accent-gradient);color:#fff;font-size:10px;font-weight:850}.access-instance small,.access-instance b,.access-instance p{display:block}.access-instance small{font-size:8.5px;color:var(--muted-2);font-weight:750;letter-spacing:.08em}.access-instance b{font:650 12px var(--mono);margin-top:2px}.access-instance p{font-size:10px;color:var(--muted-2);margin:3px 0 0}
-.access-facts{display:flex;align-self:stretch;margin-left:auto}.access-fact{min-width:112px;padding:3px 16px;border-left:1px solid var(--line);display:flex;flex-direction:column;justify-content:center}.access-fact span{font-size:8.5px;color:var(--muted-2)}.access-fact b{font-size:12px;margin-top:3px}.access-fact.good b{color:#059669}
+.access-instance{display:flex;align-items:center;gap:11px;min-width:360px}.access-instance>span{width:38px;height:38px;display:grid;place-items:center;border-radius:10px;background:var(--accent-gradient);color:var(--lf-on-accent);font-size:10px;font-weight:850}.access-instance small,.access-instance b,.access-instance p{display:block}.access-instance small{font-size:8.5px;color:var(--muted-2);font-weight:750;letter-spacing:.08em}.access-instance b{font:650 12px var(--mono);margin-top:2px}.access-instance p{font-size:10px;color:var(--muted-2);margin:3px 0 0}
+.access-facts{display:flex;align-self:stretch;margin-left:auto}.access-fact{min-width:112px;padding:3px 16px;border-left:1px solid var(--line);display:flex;flex-direction:column;justify-content:center}.access-fact span{font-size:8.5px;color:var(--muted-2)}.access-fact b{font-size:12px;margin-top:3px}.access-fact.good b{color:var(--lf-ok)}
.access-tabs{max-width:1180px;margin:0 auto 14px;display:flex;gap:4px;padding:4px;border:1px solid var(--line);border-radius:10px;background:var(--panel)}.access-tabs button{padding:7px 13px;border:0;border-radius:7px;background:transparent;color:var(--muted);font-size:11.5px;font-weight:650;cursor:pointer}.access-tabs button:hover{color:var(--text);background:var(--hover)}.access-tabs button.active{color:var(--blue-dim);background:var(--blue-soft)}
.access-grid{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(330px,.85fr);gap:14px;max-width:1180px;margin:0 auto}.access-card{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:18px 20px;box-shadow:var(--shadow-sm)}.access-card-title{display:flex;align-items:center;gap:8px;margin-bottom:12px;font-size:13px;font-weight:700}.access-card-title i{width:22px;height:22px;display:grid;place-items:center;border-radius:6px;background:var(--blue-soft);color:var(--blue);font-size:10px;font-style:normal}
.access-step{display:flex;align-items:center;gap:8px;margin:15px 0 7px}.access-step>span{width:19px;height:19px;display:grid;place-items:center;border-radius:50%;background:var(--blue-soft);color:var(--blue-dim);font-size:10px;font-weight:800}.access-step b{font-size:12px}.access-step small{font-size:10.5px;color:var(--muted-2)}
.access-clients{display:flex;gap:7px;flex-wrap:wrap}.access-clients button{display:flex;align-items:center;gap:6px;padding:7px 11px;border:1px solid var(--line-strong);border-radius:8px;background:var(--panel);color:var(--muted);font-size:11.5px;font-weight:650;cursor:pointer}.access-clients button.active{border-color:var(--blue);background:var(--blue-soft);color:var(--blue-dim)}
.access-code{border:1px solid var(--line-strong);border-radius:10px;background:var(--panel-2);overflow:hidden}.access-code-head{display:flex;align-items:center;padding:6px 10px;border-bottom:1px solid var(--line);background:var(--panel)}.access-code-head b{font-size:10.5px;color:var(--muted)}.access-copy{margin-left:auto;padding:3px 9px;border:1px solid var(--line-strong);border-radius:6px;background:var(--panel);color:var(--blue-dim);font-size:10px;font-weight:750;cursor:pointer}.access-code pre{margin:0;padding:11px 13px;overflow:auto;color:var(--text);font:11.5px/1.7 var(--mono);white-space:pre-wrap;word-break:break-word}
.access-note{margin-top:12px;padding:10px 12px;border:1px solid var(--line);border-radius:9px;background:var(--panel-2);color:var(--muted);font-size:11px;line-height:1.65}.access-note b{color:var(--text)}
-.access-agent-setup{display:flex;align-items:center;gap:18px;margin:20px 0 12px;padding:17px 18px;border:1px solid rgba(59,130,246,.3);border-radius:12px;background:var(--blue-soft)}.access-agent-setup>div{min-width:0;flex:1}.access-agent-setup b{font-size:13px}.access-agent-setup p{margin:5px 0 0;color:var(--muted);font-size:10.5px;line-height:1.55}.access-recommended{display:inline-block;margin-right:8px;padding:3px 7px;border-radius:5px;background:var(--blue);color:#fff;font-size:9px;font-weight:800;vertical-align:2px}.access-agent-setup .button{flex:none;min-width:156px}.access-manual{margin-top:14px}.access-manual summary{cursor:pointer;color:var(--muted);font-size:10.5px;font-weight:650}.access-manual[open] summary{margin-bottom:8px}
+.access-agent-setup{display:flex;align-items:center;gap:18px;margin:20px 0 12px;padding:17px 18px;border:1px solid color-mix(in srgb, var(--lf-brand-2) 30%, transparent);border-radius:12px;background:var(--blue-soft)}.access-agent-setup>div{min-width:0;flex:1}.access-agent-setup b{font-size:13px}.access-agent-setup p{margin:5px 0 0;color:var(--muted);font-size:10.5px;line-height:1.55}.access-recommended{display:inline-block;margin-right:8px;padding:3px 7px;border-radius:5px;background:var(--blue);color:var(--lf-on-accent);font-size:9px;font-weight:800;vertical-align:2px}.access-agent-setup .button{flex:none;min-width:156px}.access-manual{margin-top:14px}.access-manual summary{cursor:pointer;color:var(--muted);font-size:10.5px;font-weight:650}.access-manual[open] summary{margin-bottom:8px}
.access-tool{display:flex;align-items:center;gap:10px;padding:8px 2px}.access-tool+.access-tool{border-top:1px dashed var(--line)}.access-tool code{padding:2px 7px;border-radius:5px;background:var(--blue-soft);color:var(--blue-dim);font:650 10.5px var(--mono)}.access-tool p{margin:0;color:var(--muted);font-size:11.5px}
.access-toolbar{display:flex;align-items:center;gap:9px;max-width:1560px;margin:0 auto 11px}.access-toolbar input{max-width:330px}.access-table-wrap{max-width:1560px;margin:0 auto;border:1px solid var(--line);border-radius:12px;background:var(--panel);overflow:hidden}.access-table{width:100%;border-collapse:collapse;font-size:11.5px}.access-table th{text-align:left;padding:9px 12px;border-bottom:1px solid var(--line);color:var(--muted-2);font-size:9.5px;letter-spacing:.06em}.access-table td{padding:9px 12px;border-bottom:1px solid var(--line);color:var(--muted)}.access-table tr:last-child td{border-bottom:0}.access-table tbody tr:hover td{background:var(--hover)}.access-table code{color:var(--blue-dim);font:650 10.5px var(--mono)}.access-method{font:700 9.5px var(--mono);color:var(--text)}
.access-tokens{max-width:1560px;margin:0 auto}.token-list{display:grid;gap:9px}.token-row{display:flex;align-items:center;gap:12px;padding:13px 14px;border:1px solid var(--line);border-radius:10px;background:var(--panel)}.token-row.revoked{opacity:.58}.token-row-main{min-width:0;flex:1}.token-row-main b{display:block;font-size:12px}.token-row-main code{font-size:10.5px;color:var(--muted)}.token-meta{font-size:10.5px;color:var(--muted-2)}.token-empty{text-align:center;padding:48px 20px;color:var(--muted)}
.token-create-form{display:grid;grid-template-columns:1fr 180px auto;gap:10px;align-items:end;margin-bottom:16px}.token-create-form label{font-size:10.5px;color:var(--muted)}.token-create-form input,.token-create-form select{margin-top:5px}
-.token-reveal{margin-bottom:16px;padding:14px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.09)}.token-reveal b{display:block;font-size:12px}.token-reveal p{margin:4px 0 10px;color:var(--muted);font-size:10.5px}.token-reveal-line{display:flex;gap:8px}.token-reveal-line code{min-width:0;flex:1;padding:9px 11px;border:1px solid var(--line-strong);border-radius:8px;background:var(--panel);font-size:11px;word-break:break-all}
+.token-reveal{margin-bottom:16px;padding:14px;border:1px solid color-mix(in srgb, var(--lf-wait) 45%, transparent);border-radius:10px;background:color-mix(in srgb, var(--lf-wait) 9%, transparent)}.token-reveal b{display:block;font-size:12px}.token-reveal p{margin:4px 0 10px;color:var(--muted);font-size:10.5px}.token-reveal-line{display:flex;gap:8px}.token-reveal-line code{min-width:0;flex:1;padding:9px 11px;border:1px solid var(--line-strong);border-radius:8px;background:var(--panel);font-size:11px;word-break:break-all}
.quick-wrap{max-width:1180px;margin:0 auto}
.quick-hero{display:flex;align-items:center;gap:24px;padding:26px 28px;margin-bottom:14px;border:1px solid var(--line);border-radius:14px;background:linear-gradient(120deg,var(--blue-soft),var(--panel) 55%);box-shadow:var(--shadow-sm)}
.quick-hero-text h2{margin:0;font-size:20px;letter-spacing:.01em}
@@ -22,12 +22,12 @@
.quick-hero-facts b{display:block;font-size:19px}
.quick-hero-facts span{font-size:10px;color:var(--muted-2)}
.quick-steps{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin-bottom:14px}
-.quick-onboard{display:grid;grid-template-columns:minmax(0,1.5fr) 320px;margin-bottom:14px;border:1px solid var(--line);border-radius:14px;background:var(--panel);box-shadow:var(--shadow-sm);overflow:hidden}.quick-onboard-main{padding:30px 32px}.quick-onboard-heading{margin-bottom:24px}.quick-onboard-heading>span,.quick-next-label{display:block;margin-bottom:7px;color:var(--blue);font-size:9.5px;font-weight:800;letter-spacing:.08em}.quick-onboard-heading h2{margin:0;font-size:20px;letter-spacing:-.02em}.quick-onboard-heading p{max-width:650px;margin:8px 0 0;color:var(--muted);font-size:11.5px;line-height:1.65}.quick-onboard-label{display:block;margin-bottom:10px;color:var(--muted);font-size:10.5px;font-weight:750}.quick-onboard .access-clients button{padding:9px 14px}.quick-safe-note{color:var(--muted-2);font-size:9.5px;line-height:1.6}.quick-onboard-next{padding:30px 26px;border-left:1px solid var(--line);background:var(--bg-soft)}.quick-onboard-next>b{font-size:14px}.quick-onboard-next ol{display:grid;gap:13px;margin:22px 0 24px;padding:0;list-style:none}.quick-onboard-next li{display:flex;align-items:center;gap:9px;color:var(--muted);font-size:11px}.quick-onboard-next li i{width:21px;height:21px;display:grid;place-items:center;border-radius:50%;background:var(--panel);color:var(--blue);font-style:normal;font-size:9px;font-weight:800}.quick-success{padding:11px 12px;border-radius:9px;background:rgba(16,185,129,.1);color:#059669;font-size:10px;font-weight:700}.quick-after{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(280px,.55fr);gap:14px}.quick-tool-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-bottom:14px}.quick-tool{display:flex;align-items:center;gap:9px;padding:10px 11px;border:1px solid var(--line);border-radius:9px;background:var(--bg-soft)}.quick-tool code{color:var(--blue-dim);font:650 10px var(--mono)}.quick-tool span{color:var(--muted);font-size:10.5px}.quick-help{display:flex;flex-direction:column;gap:14px}.quick-help>div+div{padding-top:14px;border-top:1px solid var(--line)}.quick-help b{font-size:11.5px}.quick-help p{margin:5px 0 0;color:var(--muted);font-size:10.5px;line-height:1.6}.quick-help code{font:650 10px var(--mono);color:var(--blue-dim)}.quick-help>.button{align-self:flex-start;margin-top:auto}
+.quick-onboard{display:grid;grid-template-columns:minmax(0,1.5fr) 320px;margin-bottom:14px;border:1px solid var(--line);border-radius:14px;background:var(--panel);box-shadow:var(--shadow-sm);overflow:hidden}.quick-onboard-main{padding:30px 32px}.quick-onboard-heading{margin-bottom:24px}.quick-onboard-heading>span,.quick-next-label{display:block;margin-bottom:7px;color:var(--blue);font-size:9.5px;font-weight:800;letter-spacing:.08em}.quick-onboard-heading h2{margin:0;font-size:20px;letter-spacing:-.02em}.quick-onboard-heading p{max-width:650px;margin:8px 0 0;color:var(--muted);font-size:11.5px;line-height:1.65}.quick-onboard-label{display:block;margin-bottom:10px;color:var(--muted);font-size:10.5px;font-weight:750}.quick-onboard .access-clients button{padding:9px 14px}.quick-safe-note{color:var(--muted-2);font-size:9.5px;line-height:1.6}.quick-onboard-next{padding:30px 26px;border-left:1px solid var(--line);background:var(--bg-soft)}.quick-onboard-next>b{font-size:14px}.quick-onboard-next ol{display:grid;gap:13px;margin:22px 0 24px;padding:0;list-style:none}.quick-onboard-next li{display:flex;align-items:center;gap:9px;color:var(--muted);font-size:11px}.quick-onboard-next li i{width:21px;height:21px;display:grid;place-items:center;border-radius:50%;background:var(--panel);color:var(--blue);font-style:normal;font-size:9px;font-weight:800}.quick-success{padding:11px 12px;border-radius:9px;background:color-mix(in srgb, var(--lf-ok) 10%, transparent);color:var(--lf-ok);font-size:10px;font-weight:700}.quick-after{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(280px,.55fr);gap:14px}.quick-tool-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-bottom:14px}.quick-tool{display:flex;align-items:center;gap:9px;padding:10px 11px;border:1px solid var(--line);border-radius:9px;background:var(--bg-soft)}.quick-tool code{color:var(--blue-dim);font:650 10px var(--mono)}.quick-tool span{color:var(--muted);font-size:10.5px}.quick-help{display:flex;flex-direction:column;gap:14px}.quick-help>div+div{padding-top:14px;border-top:1px solid var(--line)}.quick-help b{font-size:11.5px}.quick-help p{margin:5px 0 0;color:var(--muted);font-size:10.5px;line-height:1.6}.quick-help code{font:650 10px var(--mono);color:var(--blue-dim)}.quick-help>.button{align-self:flex-start;margin-top:auto}
.quick-steps-4{grid-template-columns:repeat(4,minmax(0,1fr))}
.quick-card{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:18px 20px;box-shadow:var(--shadow-sm);display:flex;flex-direction:column}
.quick-card>b{display:block;margin-top:12px;font-size:13.5px}
.quick-card>p{margin:6px 0 10px;color:var(--muted);font-size:11.5px;line-height:1.65}
-.quick-num{width:30px;height:30px;display:grid;place-items:center;border-radius:9px;background:var(--accent-gradient);color:#fff;font-size:13px;font-weight:850}
+.quick-num{width:30px;height:30px;display:grid;place-items:center;border-radius:9px;background:var(--accent-gradient);color:var(--lf-on-accent);font-size:13px;font-weight:850}
.quick-hint{margin-top:10px;color:var(--muted-2);font-size:10px}
.guide-section{display:flex;align-items:baseline;gap:12px;margin:24px 0 12px}
.guide-section b{font-size:14px}
@@ -36,14 +36,14 @@
/* --- 最小接入配置 --- */
.setup-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;margin-bottom:14px}
.setup-card{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:18px 20px;box-shadow:var(--shadow-sm)}
-.setup-card.is-ready{border-color:rgba(5,150,105,.4)}
+.setup-card.is-ready{border-color:color-mix(in srgb, var(--lf-ok) 40%, transparent)}
.setup-card-head{display:flex;align-items:baseline;gap:10px}
.setup-card-head b{font-size:13.5px}
.setup-card-head small{color:var(--muted-2);font-size:10.5px}
.setup-card>p{margin:9px 0 0;color:var(--muted);font-size:11.5px;line-height:1.65}
.setup-status{margin-left:auto;align-self:center;font-size:10px;font-weight:750;padding:3px 10px;border-radius:999px;white-space:nowrap}
-.setup-status.ready{background:rgba(5,150,105,.12);color:#059669}
-.setup-status.missing{background:rgba(217,119,6,.14);color:#b45309}
+.setup-status.ready{background:color-mix(in srgb, var(--lf-ok) 12%, transparent);color:var(--lf-ok)}
+.setup-status.missing{background:color-mix(in srgb, var(--lf-wait) 14%, transparent);color:var(--lf-wait)}
.setup-steps{display:grid;gap:8px;margin-top:14px}
.setup-step{display:flex;align-items:center;gap:10px;width:100%;padding:10px 12px;border:1px solid var(--line-strong);border-radius:10px;background:var(--panel-2);color:var(--text);font-size:11.5px;text-align:left;cursor:pointer;text-decoration:none}
.setup-step:hover{border-color:var(--blue);background:var(--blue-soft)}
@@ -51,16 +51,16 @@
.setup-step span{flex:1}
.setup-step em{color:var(--muted-2);font-style:normal;font-size:12px}
.setup-sub{display:flex;align-items:center;gap:8px;padding:9px 11px;border:1px solid var(--line);border-radius:10px;background:var(--panel-2)}
-.setup-sub.is-ready{border-color:rgba(5,150,105,.35)}
+.setup-sub.is-ready{border-color:color-mix(in srgb, var(--lf-ok) 35%, transparent)}
.setup-sub-info{flex:1;min-width:0}
.setup-sub-info > b{display:block;font-size:11.5px}
.setup-sub-info small{display:block;color:var(--muted-2);font-size:10px;margin-top:2px}
-.setup-sub-info small b{color:#b45309;font-weight:750}
+.setup-sub-info small b{color:var(--lf-wait);font-weight:750}
html[data-theme="dark"] .setup-sub-info small b{color:var(--amber)}
.setup-mini{flex:none;padding:4px 9px;border:1px solid var(--line-strong);border-radius:6px;background:var(--panel);color:var(--blue-dim);font-size:10px;font-weight:750;cursor:pointer;text-decoration:none;white-space:nowrap}
.setup-mini:hover{border-color:var(--blue);background:var(--blue-soft)}
-.setup-done{display:flex;align-items:center;gap:14px;padding:16px 18px;border:1px solid rgba(5,150,105,.4);border-radius:12px;background:rgba(5,150,105,.07);max-width:1560px;margin:0 auto}
-.setup-done b{font-size:13px;color:#047857}
+.setup-done{display:flex;align-items:center;gap:14px;padding:16px 18px;border:1px solid color-mix(in srgb, var(--lf-ok) 40%, transparent);border-radius:12px;background:color-mix(in srgb, var(--lf-ok) 7%, transparent);max-width:1560px;margin:0 auto}
+.setup-done b{font-size:13px;color:var(--lf-ok)}
.setup-done p{margin:3px 0 0;color:var(--muted);font-size:11px}
.setup-done .button{margin-left:auto}
.setup-done.pending{border-color:var(--line);background:var(--panel)}
diff --git a/web/app.js b/web/app.js
index 39ba3758..93bd4d69 100644
--- a/web/app.js
+++ b/web/app.js
@@ -88,10 +88,27 @@ async function api(path, options={}) {
try{
const request={...fetchOpts};
if(!request.headers&&!(request.body instanceof FormData))request.headers={'Content-Type':'application/json'};
- const res = await fetch(path, request);
+ let res;
+ try {
+ res = await fetch(path, request);
+ } catch (err) {
+ if (typeof lfSyncOffline === 'function') lfSyncOffline();
+ if (typeof navigator !== 'undefined' && navigator.onLine === false) {
+ const offline = new Error('网络已断开');
+ offline.code = 'offline';
+ offline.action = 'retry';
+ throw offline;
+ }
+ throw err;
+ }
const body = await res.json().catch(()=>({}));
if (res.status===401 && state.authRequired && !state.proxyAuth && !String(path).startsWith('/api/auth/')) openLoginModal({forced:true});
- if (!res.ok) throw new Error(body.error || `HTTP ${res.status}`);
+ if (!res.ok) {
+ const err = new Error(body.error || `HTTP ${res.status}`);
+ err.code = body.code || '';
+ err.action = body.action || '';
+ throw err;
+ }
return body;
} finally {
if(!silent){
@@ -100,7 +117,24 @@ async function api(path, options={}) {
}
}
}
-function toast(message, type='info', duration=type==='err'?6000:2600){
+let toastUndoHandler=null;
+function clearToastUndo(){
+ if(toastUndoHandler){document.removeEventListener('keydown',toastUndoHandler);toastUndoHandler=null}
+}
+function armToastUndo(fn,remove){
+ clearToastUndo();
+ toastUndoHandler=e=>{
+ if(!(e.metaKey||e.ctrlKey)||e.key.toLowerCase()!=='z'||e.shiftKey)return;
+ if(e.target?.closest?.('input,textarea,select,[contenteditable="true"]'))return;
+ e.preventDefault();
+ clearToastUndo();
+ remove();
+ try{fn()}catch(err){console.error(err)}
+ };
+ document.addEventListener('keydown',toastUndoHandler);
+}
+function toast(message, type='info', duration=type==='err'?6000:2600, extra){
+ if(extra?.undo)duration=Math.max(Number(duration)||0,8000);
const container=$('#toastContainer');
const legacy=$('#toast');
if(!container&&legacy){
@@ -117,7 +151,7 @@ function toast(message, type='info', duration=type==='err'?6000:2600){
const item=document.createElement('div');
item.className=`toast-item toast-${kind}`;
item.setAttribute('role','status');
- item.innerHTML=`${escapeHTML(message)}`;
+ item.innerHTML=`${escapeHTML(message)}${extra?.undo?'':''}`;
container.appendChild(item);
let timer=null;
const remove=()=>{
@@ -128,7 +162,13 @@ function toast(message, type='info', duration=type==='err'?6000:2600){
timer=setTimeout(remove, duration);
item.onmouseenter=()=>clearTimeout(timer);
item.onmouseleave=()=>{timer=setTimeout(remove, 1400)};
- item.querySelector('.toast-item-close').onclick=remove;
+ item.querySelector('.toast-item-close').onclick=()=>{clearToastUndo();remove()};
+ if(extra?.undo){
+ const undo=item.querySelector('.toast-undo');
+ const run=()=>{clearToastUndo();remove();extra.undo()};
+ if(undo)undo.onclick=run;
+ armToastUndo(extra.undo,remove);
+ }
}
let confirmPromiseResolve = null;
@@ -144,7 +184,8 @@ function afConfirm(options){
const message=opt.message||'确定要继续吗?';
const confirmText=opt.confirmText||(opt.danger?'确定执行':'确定');
const cancelText=opt.cancelText||'取消';
- const danger=!!opt.danger;
+ const danger=!!(opt.danger||opt.isDanger);
+ const confirmName=String(opt.confirmName||'').trim();
$('#confirmTitle').textContent=title;
$('#confirmMessage').textContent=message;
@@ -157,8 +198,16 @@ function afConfirm(options){
promptWrap.hidden=true;
if(rerunFields)rerunFields.hidden=true;
+ const nameWrap=$('#confirmNameWrap');
+ const nameInput=$('#confirmNameInput');
+ const nameHint=$('#confirmNameHint');
+ if(nameWrap)nameWrap.hidden=!confirmName;
+ if(nameInput){nameInput.value='';nameInput.placeholder=confirmName}
+ if(nameHint&&confirmName)nameHint.textContent=`输入 ${confirmName} 以确认`;
okBtn.textContent=confirmText;
- okBtn.className=`button ${danger?'danger-btn':'primary'}`;
+ okBtn.className=`button ${danger?'danger-outline':'primary'}`;
+ okBtn.disabled=!!confirmName;
+ if(nameInput&&confirmName)nameInput.oninput=()=>{okBtn.disabled=nameInput.value.trim()!==confirmName};
cancelBtn.textContent=cancelText;
cancelBtn.hidden=false;
@@ -166,10 +215,13 @@ function afConfirm(options){
iconEl.textContent=danger?'🗑️':(opt.info?'ℹ️':'⚠️');
modal.classList.add('open');
- okBtn.focus();
+ if(confirmName&&nameInput)nameInput.focus();else okBtn.focus();
confirmPromiseResolve=(val)=>{
+ if(val&&confirmName&&nameInput&&nameInput.value.trim()!==confirmName)return;
modal.classList.remove('open');
+ okBtn.disabled=false;
+ if(nameWrap)nameWrap.hidden=true;
confirmPromiseResolve=null;
resolve(val);
};
@@ -203,6 +255,8 @@ function afPrompt(options, defaultVal=''){
promptWrap.hidden=false;
if(rerunFields)rerunFields.hidden=true;
+ const nameWrap=$('#confirmNameWrap');if(nameWrap)nameWrap.hidden=true;
+ okBtn.disabled=false;
promptLabel.textContent=opt.label||title;
promptInput.value=defaultValue;
promptInput.placeholder=placeholder;
@@ -239,6 +293,7 @@ function afAlert(options){
$('#confirmTitle').textContent=opt.title||'提示';
$('#confirmMessage').textContent=opt.message||'';
$('#confirmPromptWrap').hidden=true;
+ const nameWrap=$('#confirmNameWrap');if(nameWrap)nameWrap.hidden=true;
const rerunFields=$('#rerunFromNodeFields');
if(rerunFields)rerunFields.hidden=true;
const okBtn=$('#confirmOkBtn');
@@ -840,9 +895,31 @@ function openSetupScreen(){
setTimeout(()=>modal.querySelector('[name=loginName]')?.focus(),50);
}
+function lfSyncOffline(){
+ const el=$('#lfOffline');
+ if(!el)return;
+ el.hidden=typeof navigator==='undefined'||navigator.onLine!==false;
+}
+function lfBindChrome(){
+ if(document.body.dataset.lfChrome)return;
+ document.body.dataset.lfChrome='1';
+ window.addEventListener('offline',lfSyncOffline);
+ window.addEventListener('online',()=>{lfSyncOffline();toast('网络已恢复','ok');if(typeof roomReattachOnline==='function')roomReattachOnline()});
+ $('#lfOfflineRetry')&&($('#lfOfflineRetry').onclick=()=>{lfSyncOffline();if(navigator.onLine)toast('网络是通的','ok');else toast('还是连不上','err')});
+ lfSyncOffline();
+}
+function bindGallery(){
+ const root=$('#lfGallery');
+ if(!root||root.dataset.bound)return;
+ root.dataset.bound='1';
+ root.querySelector('[data-gallery-danger]')?.addEventListener('click',async()=>{await afConfirm({title:'删除组件示例?',message:'此操作不可撤销。',confirmText:'删除',danger:true,confirmName:'组件示例'})});
+ root.querySelector('[data-gallery-dialog]')?.addEventListener('click',()=>afConfirm({title:'保存这份草稿?',message:'确认后才会写入。',confirmText:'保存'}));
+ root.querySelector('[data-gallery-toast]')?.addEventListener('click',()=>toast('已归档,8 秒内可以撤销','ok',8000,{undo(){toast('已撤销','ok')}}));
+ root.querySelector('[data-gallery-empty]')?.addEventListener('click',()=>toast('这是空态的主操作','ok'));
+}
async function boot(){
state.data = {runs:[],issues:[],tasks:[],workflowMetrics:[],syncLogs:[],agents:[],workflows:[],projects:[],repositories:[],users:[],rules:[],skills:[],mcpServers:[],executors:[],dockerfiles:[],environments:[],sandboxes:[]};
- bind(); renderProjectSwitcher(); updateApprovalBadge();
+ bind(); lfBindChrome(); renderProjectSwitcher(); updateApprovalBadge();
// 1. 获取当前登录身份(本地账号 Cookie 或受信反向代理身份头)
if (!state.currentUser) {
@@ -952,7 +1029,7 @@ function bind(){
$('#workflowDescription').oninput=e=>{if(!state.workflow)return;state.workflow.description=e.target.value;dirty()};
$('#saveWorkflow').onclick=saveWorkflow; $('#discardWorkflow').onclick=discardWorkflow; $('#publishWorkflow').onclick=publishWorkflow;
$('#flowHistory')&&($('#flowHistory').onclick=()=>openRevisionHistory('workflow', state.workflow?.id, state.workflow?.name));
- $('#deleteNode').onclick=deleteSelected;{const wb=$('.flow-workbench'),tg=$('#flowPropsToggle');const setProps=on=>{wb?.classList.toggle('props-hidden',!on);tg?.classList.toggle('on',on);localStorage.setItem('loopforge.flowProps',on?'1':'0');renderEdges()};setProps(localStorage.getItem('loopforge.flowProps')!=='0');tg&&(tg.onclick=()=>setProps(wb.classList.contains('props-hidden')));$('#nodes')?.addEventListener('dblclick',e=>{if(e.target.closest('.flow-node'))setProps(true)})} $('#fitButton').onclick=arrange;
+ $('#deleteNode').onclick=confirmDeleteSelected;{const wb=$('.flow-workbench'),tg=$('#flowPropsToggle');const setProps=on=>{wb?.classList.toggle('props-hidden',!on);tg?.classList.toggle('on',on);localStorage.setItem('loopforge.flowProps',on?'1':'0');renderEdges()};setProps(localStorage.getItem('loopforge.flowProps')!=='0');tg&&(tg.onclick=()=>setProps(wb.classList.contains('props-hidden')));$('#nodes')?.addEventListener('dblclick',e=>{if(e.target.closest('.flow-node'))setProps(true)})} $('#fitButton').onclick=arrange;
bindFlowResize();
$('#runButton').onclick=()=>openRunModal(state.workflow?.id);
$('#flowSettingsToggle').onclick=()=>{const panel=$('#flowSettingsPanel');panel.hidden=!panel.hidden;$('#flowSettingsToggle').classList.toggle('active',!panel.hidden)};
@@ -1145,7 +1222,7 @@ function bind(){
$('#chatCreateDirect')&&($('#chatCreateDirect').onclick=()=>createIssueDirect());
$('#chatCreateLocal')&&($('#chatCreateLocal').onclick=()=>createIssueFromChat('local'));
$('#chatCreateGitHub').onclick=()=>createIssueFromChat('github');
- $('#chatInput').addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){if(chatHistory.length>0){e.preventDefault();sendChatClarify()}}});
+ $('#chatInput').addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey&&!e.isComposing&&e.keyCode!==229){e.preventDefault();sendChatClarify()}});
$('#reqWorkflow')&&($('#reqWorkflow').onchange=()=>persistRequirementComposer());
$('#chatInput').addEventListener('input',()=>{syncComposerReplyState();persistRequirementComposer()});
window.addEventListener('beforeunload',()=>persistRequirementComposer());
@@ -1202,6 +1279,7 @@ function bind(){
if(e.key==='Escape'){closeCommandPalette();return}
if(e.key==='ArrowDown'){e.preventDefault();moveCommandSelection(1);return}
if(e.key==='ArrowUp'){e.preventDefault();moveCommandSelection(-1);return}
+ if(e.key==='Tab'){e.preventDefault();if(typeof cycleCommandFilter==='function')cycleCommandFilter();return}
if(e.key==='Enter'){e.preventDefault();executeCommand(commandSelectedIndex);return}
}
if(e.key==='Escape'){
@@ -1373,7 +1451,54 @@ function bindGlobalModals(){
}
}
const pluginViews=new Map();
-function viewTitles(){return {...Object.fromEntries([...pluginViews.values()].map(v=>[v.id,v.title])),chat:'首页',issues:'需求看板',rooms:'协作群聊',runs:'运行',metrics:'研发效能',approvals:'待我确认',sops:'流程模板',flow:'流程设计',agents:'角色',mcp:'MCP',rules:'规则',skills:'技能',dockerfiles:'Dockerfile',environments:'安装脚本',sandboxes:'沙箱',observability:'用量分析',projects:'项目',businessDomains:'业务领域',platform:'平台管理',businessDomainManagement:'领域管理',runners:'执行机器',settings:'个人设置',access:'接入方式',guide:'接入指南',knowledge:'知识中心'}}
+function viewTitles(){return {...Object.fromEntries([...pluginViews.values()].map(v=>[v.id,v.title])),chat:'首页',issues:'SOP 运行',rooms:'群聊',runs:'进行中',runsDone:'已完成',metrics:'运行洞察',approvals:'待确认',sops:'流程',flow:'流程设计',agents:'Bot',mcp:'MCP',rules:'规则',skills:'技能',dockerfiles:'Dockerfile',environments:'安装脚本',sandboxes:'环境',observability:'成本',projects:'项目',businessDomains:'业务领域',platform:'成员与权限',businessDomainManagement:'领域管理',runners:'执行机器',settings:'个人设置',access:'接入方式',guide:'接入指南',knowledge:'知识库',gallery:'组件'}}
+function sidebarViewFor(name){
+ const map={runs:'issues',runsDone:'issues',approvals:'issues',flow:'sops',skills:'agents',mcp:'agents',rules:'agents',dockerfiles:'sandboxes',environments:'sandboxes',businessDomains:'metrics',businessDomainManagement:'platform',runners:'settings',guide:'settings',access:'settings',build:'sops',me:'settings',admin:'platform',insights:'metrics'};
+ return map[name]||name;
+}
+function lfModelReady(){
+ const stored=(typeof userById==='function'?userById(state.currentUser?.id):null)||{};
+ return !!(stored.codeBuddyApiKeyConfigured||stored.codexApiKeyConfigured||stored.claudeCodeApiKeyConfigured);
+}
+function lfBotQueue(agentId){
+ let n=0;
+ (state.data?.runs||[]).forEach(r=>{
+ if(!['running','queued','waiting'].includes(r.status))return;
+ (r.workflowSnapshot?.nodes||[]).forEach(node=>{
+ if(node.agentId!==agentId)return;
+ const st=r.nodes?.[node.id]?.status;
+ if(st==='running'||st==='pending'||st==='queued')n++;
+ });
+ });
+ if(typeof roomState==='function'){
+ (roomState().lastMessages||[]).forEach(m=>{(m.crew?.tasks||[]).forEach(t=>{if(t.agentId===agentId&&(t.status==='running'||t.status==='pending'))n++})});
+ }
+ return n;
+}
+function lfBotStatus(agent){
+ if(!agent)return {key:'off',label:'不可用',reason:'找不到这个 Bot',queue:0};
+ const demoExec=agent.executorId==='mock';
+ const live=(state.botStatus||[]).find(item=>item.agentId===agent.id);
+ if(live&&!(demoExec&&live.status==='unavailable'&&/key/i.test(live.reason||''))){
+ const key=live.status==='online'?'ok':live.status==='busy'?'busy':live.status==='degraded'?'wait':'off';
+ const label=live.status==='online'?'可用':live.status==='busy'?'忙':live.status==='degraded'?'降级':(/key/i.test(live.reason||'')?'缺 Key':'不可用');
+ return {key,label,reason:live.reason||label,queue:live.queue||0};
+ }
+ if(demoExec){
+ const queue=live?.queue||lfBotQueue(agent.id);
+ if(queue>0)return {key:'busy',label:'忙',reason:'排队 '+queue,queue};
+ return {key:'ok',label:'可用',reason:'演示执行器,无需 Key',queue:0};
+ }
+ if(!lfModelReady())return {key:'off',label:'缺 Key',reason:'还没配置模型 API Key',queue:0};
+ const queue=lfBotQueue(agent.id);
+ if(queue>0)return {key:'busy',label:'忙',reason:'排队 '+queue,queue};
+ return {key:'ok',label:'可用',reason:'可直接 @',queue:0};
+}
+function lfStatusBadge(agent){
+ const st=lfBotStatus(agent);
+ const extra=st.key==='busy'&&st.queue?' '+st.queue:'';
+ return `${escapeHTML(st.label+extra)}`;
+}
function activeViewName(){if(state.currentView)return state.currentView;const el=document.querySelector('.view.active');return el?el.id.replace(/View$/,''):''}
function setCapabilityNavExpanded(expanded){const toggle=$('#capabilityNavToggle'),group=$('#capabilityNavGroup');if(!toggle||!group)return;toggle.setAttribute('aria-expanded',String(expanded));group.hidden=!expanded;localStorage.setItem('loopforge.capabilityNavExpanded',String(expanded))}
function setNavGroupExpanded(group,expanded){const toggle=$(`[data-nav-group="${group}"]`),body=$(`[data-nav-group-body="${group}"]`);if(!toggle||!body)return;toggle.setAttribute('aria-expanded',String(expanded));body.hidden=!expanded;localStorage.setItem(`loopforge.navGroup.${group}`,String(expanded))}
@@ -1460,16 +1585,13 @@ function persistView(name,push=false){
}
// 侧栏只留几个入口;入口下的页面用顶部标签(必要时再加一层子标签)切换。
const VIEW_TABSETS=[
- {nav:'issues',label:'交付',tabs:[{view:'issues',label:'需求看板'},{view:'runs',label:'运行'},{view:'approvals',label:'待我确认',count:true}]},
- {nav:'build',label:'构建',tabs:[
- {view:'sops',label:'流程',subs:[['sops','模板'],['flow','设计']]},
- {view:'agents',label:'角色'},
- {view:'skills',label:'能力',subs:[['skills','技能'],['mcp','MCP'],['rules','规则'],['knowledge','知识']]},
- {view:'sandboxes',label:'环境',subs:[['sandboxes','沙箱'],['dockerfiles','Dockerfile'],['environments','安装脚本']]},
- {view:'projects',label:'项目'}]},
- {nav:'insights',label:'洞察',tabs:[{view:'metrics',label:'效能'},{view:'observability',label:'用量'},{view:'businessDomains',label:'汇报'}],plugins:true},
- {nav:'admin',label:'平台',tabs:[{view:'platform',label:'账号与权限',when:()=>isPlatformAdmin()},{view:'businessDomainManagement',label:'业务领域'}]},
- {nav:'me',label:'设置',tabs:[{view:'settings',label:'个人设置'},{view:'runners',label:'执行机器'},{view:'guide',label:'接入指南'}]},
+ {nav:'issues',label:'工作',tabs:[{view:'issues',label:'SOP 运行',count:true,subs:[['runs','进行中'],['approvals','待确认'],['runsDone','已完成'],['issues','需求']]}]},
+ {nav:'sops',label:'配置',tabs:[{view:'sops',label:'流程',subs:[['sops','模板'],['flow','设计']]}]},
+ {nav:'agents',label:'配置',tabs:[{view:'agents',label:'Bot',subs:[['agents','Bot'],['skills','技能'],['mcp','MCP'],['rules','规则']]}]},
+ {nav:'sandboxes',label:'配置',tabs:[{view:'sandboxes',label:'环境',subs:[['sandboxes','沙箱'],['dockerfiles','Dockerfile'],['environments','安装脚本']]}]},
+ {nav:'metrics',label:'洞察',tabs:[{view:'metrics',label:'运行洞察',subs:[['metrics','运行洞察'],['businessDomains','汇报']]}],plugins:true},
+ {nav:'platform',label:'管理',tabs:[{view:'platform',label:'成员与权限',when:()=>isPlatformAdmin()},{view:'businessDomainManagement',label:'领域',when:()=>canAccessPlatformManagement()}]},
+ {nav:'settings',label:'设置',tabs:[{view:'settings',label:'个人设置'},{view:'runners',label:'执行机器'},{view:'guide',label:'接入指南'}]},
];
function tabsetTabs(set){
const tabs=set.tabs.filter(t=>!t.when||t.when());
@@ -1493,7 +1615,6 @@ function applyViewTabset(name,target){
const tabs=tabsetTabs(set);
const cur=tabs.find(t=>tabOwns(t,name));
const count=$('#approvalNavBadge')?.textContent||'';
- const title=$('#pageTitle');if(title)title.innerHTML=`${set.label}/${escapeHTML(cur?.label||title.textContent)}${cur?.subs?`/${escapeHTML((cur.subs.find(s=>s[0]===name)||[])[1]||'')}`:''}`;
let pagebar=view.querySelector(':scope>.lf-pagebar');
if(!pagebar){
pagebar=document.createElement('div');pagebar.className='lf-pagebar';
@@ -1507,28 +1628,44 @@ function applyViewTabset(name,target){
if(cur?.subs){
localStorage.setItem(`loopforge.sub.${cur.view}`,name);
const sub=document.createElement('div');sub.className='lf-subtabs';
- sub.innerHTML=cur.subs.map(([v,l])=>``).join('');
+ const capViews=new Set(['skills','mcp','rules']);
+ const caps=cur.view==='agents'?cur.subs.filter(([v])=>capViews.has(v)):[];
+ const main=caps.length?cur.subs.filter(([v])=>!capViews.has(v)):cur.subs;
+ const tabBtn=([v,l])=>``;
+ sub.innerHTML=main.map(tabBtn).join('');
+ if(caps.length){
+ const details=document.createElement('details');
+ details.className='lf-cap';
+ if(caps.some(([v])=>v===name))details.open=true;
+ details.innerHTML=`
${escapeHTML(a.description||'尚未填写职责说明')}
调整搜索,或新建一个角色。
${escapeHTML(a.description||'尚未填写职责说明')}
调整搜索,或新建一个角色。
流程停在人工确认节点时会出现在这里,侧边栏「运行」上也会亮起角标。
流程停在人工确认节点时会出现在这里,侧边栏「SOP 运行」上也会亮起角标。
${escapeHTML(a.description||'暂无说明')}
${shareHint}
${assetEmptyHint()}
${shareHint}
${assetEmptyHint()}
${escapeHTML(a.id)}`}从左侧选一条,或新建一份给当前项目用。
${escapeHTML(a.id)}`}从上方选择一种节点开始
先加一个 Agent 步骤,再把后面的检查和人工门禁连上去。
稍候刷新,或从「SOP 目录」打开一条已发布流程。
从 SOP 目录打开一条流程。如果一直停在这里,刷新后再试。
Agent 步骤绑定角色、连线、统一校验清单和失败打回。节点会同步展示角色定义的产物与门禁。
点左侧步骤,或直接加一个 Agent 步骤再绑角色。
子 SOP 成功后,下列文件会出现在本节点,供下一步读取。留空则收下子流程交出的全部产物。
可以从这一步续跑,上游已完成的步骤会保留。
${escapeHTML(homeGreeting())},${escapeHTML(user.displayName || user.name || user.loginName || '')}
还没有未完成的事。点一个示例,马上开跑。
需要开通时,请让现有管理员在这里加上你的登录名。
在流程设计或角色定义中修改通用模板后,所有关联项目下次运行自动用最新版本。
${(allRows&&allRows.length)?'请尝试更换搜索关键字或重置筛选条件。':'还没有配置平台管理员。'}
+${(allRows&&allRows.length)?'换个关键字,或切回「全部」。':'在上方填登录名,把同事加为平台管理员。'}
+ ${(allRows&&allRows.length)?'':''}