dsh-task-mascot 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ART_LICENSE.md +36 -0
- package/LICENSE +25 -0
- package/NOTICE.md +12 -0
- package/README.md +149 -2
- package/assets/packs/claude/cmd.png +0 -0
- package/assets/packs/claude/cmd.webm +0 -0
- package/assets/packs/claude/cmd.webp +0 -0
- package/assets/packs/claude/coding.png +0 -0
- package/assets/packs/claude/coding.webm +0 -0
- package/assets/packs/claude/coding.webp +0 -0
- package/assets/packs/claude/done.png +0 -0
- package/assets/packs/claude/done.webm +0 -0
- package/assets/packs/claude/done.webp +0 -0
- package/assets/packs/claude/editing.png +0 -0
- package/assets/packs/claude/editing.webm +0 -0
- package/assets/packs/claude/editing.webp +0 -0
- package/assets/packs/claude/error.png +0 -0
- package/assets/packs/claude/error.webm +0 -0
- package/assets/packs/claude/error.webp +0 -0
- package/assets/packs/claude/manifest.json +106 -0
- package/assets/packs/claude/planning.png +0 -0
- package/assets/packs/claude/planning.webm +0 -0
- package/assets/packs/claude/planning.webp +0 -0
- package/assets/packs/claude/reading.png +0 -0
- package/assets/packs/claude/reading.webm +0 -0
- package/assets/packs/claude/reading.webp +0 -0
- package/assets/packs/claude/search.png +0 -0
- package/assets/packs/claude/search.webm +0 -0
- package/assets/packs/claude/search.webp +0 -0
- package/assets/packs/claude/subagents.png +0 -0
- package/assets/packs/claude/subagents.webm +0 -0
- package/assets/packs/claude/subagents.webp +0 -0
- package/assets/packs/claude/thinking.png +0 -0
- package/assets/packs/claude/thinking.webm +0 -0
- package/assets/packs/claude/thinking.webp +0 -0
- package/assets/packs/claude/waiting.png +0 -0
- package/assets/packs/claude/waiting.webm +0 -0
- package/assets/packs/claude/waiting.webp +0 -0
- package/assets/packs/dafeiyu/cmd.png +0 -0
- package/assets/packs/dafeiyu/cmd.webm +0 -0
- package/assets/packs/dafeiyu/cmd.webp +0 -0
- package/assets/packs/dafeiyu/coding.png +0 -0
- package/assets/packs/dafeiyu/coding.webm +0 -0
- package/assets/packs/dafeiyu/coding.webp +0 -0
- package/assets/packs/dafeiyu/done.png +0 -0
- package/assets/packs/dafeiyu/done.webm +0 -0
- package/assets/packs/dafeiyu/done.webp +0 -0
- package/assets/packs/dafeiyu/editing.png +0 -0
- package/assets/packs/dafeiyu/editing.webm +0 -0
- package/assets/packs/dafeiyu/editing.webp +0 -0
- package/assets/packs/dafeiyu/error.png +0 -0
- package/assets/packs/dafeiyu/error.webm +0 -0
- package/assets/packs/dafeiyu/error.webp +0 -0
- package/assets/packs/dafeiyu/manifest.json +106 -0
- package/assets/packs/dafeiyu/planning.png +0 -0
- package/assets/packs/dafeiyu/planning.webm +0 -0
- package/assets/packs/dafeiyu/planning.webp +0 -0
- package/assets/packs/dafeiyu/reading.png +0 -0
- package/assets/packs/dafeiyu/reading.webm +0 -0
- package/assets/packs/dafeiyu/reading.webp +0 -0
- package/assets/packs/dafeiyu/search.png +0 -0
- package/assets/packs/dafeiyu/search.webm +0 -0
- package/assets/packs/dafeiyu/search.webp +0 -0
- package/assets/packs/dafeiyu/subagents.png +0 -0
- package/assets/packs/dafeiyu/subagents.webm +0 -0
- package/assets/packs/dafeiyu/subagents.webp +0 -0
- package/assets/packs/dafeiyu/thinking.png +0 -0
- package/assets/packs/dafeiyu/thinking.webm +0 -0
- package/assets/packs/dafeiyu/thinking.webp +0 -0
- package/assets/packs/dafeiyu/waiting.png +0 -0
- package/assets/packs/dafeiyu/waiting.webm +0 -0
- package/assets/packs/dafeiyu/waiting.webp +0 -0
- package/cordis.patch.yml +5 -0
- package/lib/client.js +654 -0
- package/lib/index.js +162 -0
- package/package.json +67 -4
package/lib/client.js
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
// dsh-task-mascot — browser half. Plain JS in the dsh ModuleLoader format (no build step).
|
|
2
|
+
window.__ModuleLoader__.load({
|
|
3
|
+
id: 'dsh-task-mascot',
|
|
4
|
+
factory: (require) => {
|
|
5
|
+
var module = { exports: {} };
|
|
6
|
+
var exports = module.exports;
|
|
7
|
+
const React = require('react');
|
|
8
|
+
const h = React.createElement;
|
|
9
|
+
const API = '/api/dsh-task-mascot';
|
|
10
|
+
const LS_KEY = 'dsh-task-mascot:settings:v1';
|
|
11
|
+
|
|
12
|
+
// ---------------------------------------------------------------- mapping
|
|
13
|
+
/** Default tool → state rules, first match wins. `ext` (optional) matches the target file extension. */
|
|
14
|
+
const DEFAULT_RULES = [
|
|
15
|
+
{ tool: '^(write|edit|str_replace_editor)$', ext: '^(md|mdx|txt|rst|adoc|docx?|tex)$', state: 'writingdoc' },
|
|
16
|
+
{ tool: '^write$', state: 'coding' },
|
|
17
|
+
{ tool: '^(edit|str_replace_editor)$', state: 'editing' },
|
|
18
|
+
{ tool: '^(read|read_image|read_mcp_resource|lsp)$', state: 'reading' },
|
|
19
|
+
{ tool: '^(glob|grep|session_.*)$', state: 'search' },
|
|
20
|
+
{ tool: '^(web_search|web_fetch|stagehand_.*)$', state: 'search' },
|
|
21
|
+
{ tool: '^(bash|pwsh|terminal_.*|job_.*)$', state: 'cmd' },
|
|
22
|
+
{ tool: '^(run_code|workflow)$', state: 'data' },
|
|
23
|
+
{ tool: '^(todo_write|exit_plan_mode|create_goal|get_goal|update_goal|schedule_.*)$', state: 'planning' },
|
|
24
|
+
{ tool: '^(subagent|list_subagent_models|send_message|list_agents|interrupt_agent|spawn_teammate|team_task_.*|ralph)$', state: 'subagents' },
|
|
25
|
+
{ tool: '^ask_user_question$', state: 'waiting' },
|
|
26
|
+
{ tool: '^present$', state: 'summary' },
|
|
27
|
+
{ tool: '^(skill|plugin_manager|plugin_market|working_directory)$', state: 'tools' },
|
|
28
|
+
{ tool: '.*', state: 'tools' },
|
|
29
|
+
];
|
|
30
|
+
const ALL_STATES = ['idle', 'thinking', 'reading', 'search', 'coding', 'editing', 'writingdoc', 'cmd', 'data', 'planning', 'subagents', 'tools', 'summary', 'waiting', 'done', 'error'];
|
|
31
|
+
|
|
32
|
+
function compileRules(rules) {
|
|
33
|
+
const out = [];
|
|
34
|
+
for (const r of rules || []) {
|
|
35
|
+
try { out.push({ tool: new RegExp(r.tool || '.*', 'i'), ext: r.ext ? new RegExp(r.ext, 'i') : null, state: String(r.state || 'tools') }); } catch (_e) { /* skip bad regex */ }
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
function stateForTool(tool, args, compiled) {
|
|
40
|
+
const ext = args && typeof args === 'object' ? args.ext : undefined;
|
|
41
|
+
for (const r of compiled) {
|
|
42
|
+
if (!r.tool.test(tool || '')) continue;
|
|
43
|
+
if (r.ext && !(ext && r.ext.test(ext))) continue;
|
|
44
|
+
return r.state;
|
|
45
|
+
}
|
|
46
|
+
return 'tools';
|
|
47
|
+
}
|
|
48
|
+
/** Resolve a logical state to a state the pack actually has, via manifest fallbacks then a global chain. */
|
|
49
|
+
const GLOBAL_FALLBACK = { writingdoc: ['editing', 'coding'], data: ['cmd', 'thinking'], tools: ['cmd', 'thinking'], subagents: ['planning', 'tools'], summary: ['done', 'thinking'], idle: ['waiting', 'thinking'], generating: ['thinking'] };
|
|
50
|
+
function resolveState(state, manifest) {
|
|
51
|
+
const has = (s) => !!(manifest && manifest.states && manifest.states[s]);
|
|
52
|
+
const seen = new Set(); const queue = [state];
|
|
53
|
+
while (queue.length) {
|
|
54
|
+
const s = queue.shift(); if (seen.has(s)) continue; seen.add(s);
|
|
55
|
+
if (has(s)) return s;
|
|
56
|
+
const fb = (manifest && manifest.fallback && manifest.fallback[s]) || GLOBAL_FALLBACK[s] || [];
|
|
57
|
+
queue.push(...fb);
|
|
58
|
+
}
|
|
59
|
+
const star = (manifest && manifest.fallback && manifest.fallback['*']) || ['thinking'];
|
|
60
|
+
for (const s of star) if (has(s)) return s;
|
|
61
|
+
const keys = manifest && manifest.states ? Object.keys(manifest.states) : [];
|
|
62
|
+
return keys[0] || null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------- activity state machine
|
|
66
|
+
/**
|
|
67
|
+
* Tracks one "focus" session. Priority: error/done one-shot > waiting (approval/question) >
|
|
68
|
+
* active tool > generating/thinking > idle.
|
|
69
|
+
*/
|
|
70
|
+
function createMachine(opts) {
|
|
71
|
+
const o = Object.assign({ oneShotMs: 3000, toolLingerMs: 1200, idleAfterMs: 20000, now: () => Date.now() }, opts || {});
|
|
72
|
+
let compiled = compileRules(o.rules || DEFAULT_RULES);
|
|
73
|
+
const st = { running: false, waiting: false, tools: new Map(), lastTool: null, lastToolEnd: 0, oneShot: null, lastActivity: 0, sessionId: null, label: '' };
|
|
74
|
+
function setRules(r) { compiled = compileRules(r && r.length ? r : DEFAULT_RULES); }
|
|
75
|
+
function feed(f) {
|
|
76
|
+
if (!f || !f.kind) return;
|
|
77
|
+
const t = o.now();
|
|
78
|
+
if (f.sessionId) st.sessionId = f.sessionId;
|
|
79
|
+
st.lastActivity = t;
|
|
80
|
+
switch (f.kind) {
|
|
81
|
+
case 'turn-start': case 'user-message': st.running = true; st.oneShot = null; break;
|
|
82
|
+
case 'step-start': case 'generating': st.running = true; break;
|
|
83
|
+
case 'tool-call': {
|
|
84
|
+
st.running = true;
|
|
85
|
+
const s = stateForTool(f.tool, f.args, compiled);
|
|
86
|
+
st.tools.set(f.callId || f.tool + ':' + t, { state: s, tool: f.tool, at: t });
|
|
87
|
+
st.lastTool = { state: s, tool: f.tool }; st.label = f.tool || '';
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
case 'tool-result': {
|
|
91
|
+
if (f.callId && st.tools.has(f.callId)) st.tools.delete(f.callId);
|
|
92
|
+
else if (st.tools.size) st.tools.delete(st.tools.keys().next().value);
|
|
93
|
+
st.lastToolEnd = t;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
case 'approval': case 'question': st.waiting = !!f.pending; break;
|
|
97
|
+
case 'turn-end': {
|
|
98
|
+
st.running = false; st.waiting = false; st.tools.clear();
|
|
99
|
+
const err = f.reason && !/^(completed|complete|stop|end_turn|done|ok)$/i.test(f.reason) && /error|fail/i.test(f.reason);
|
|
100
|
+
const cancelled = /cancel|interrupt|abort/i.test(f.reason || '');
|
|
101
|
+
if (!cancelled) st.oneShot = { state: err ? 'error' : 'done', until: t + o.oneShotMs };
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
default: break;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Coarse status from useSessions() (fallback when SSE is absent). */
|
|
108
|
+
function feedStatus(s) {
|
|
109
|
+
if (!s) return;
|
|
110
|
+
const t = o.now();
|
|
111
|
+
if (s.pendingInteraction && !st.waiting) { st.waiting = true; st.lastActivity = t; }
|
|
112
|
+
if (!s.pendingInteraction && st.waiting && s.source === 'status') st.waiting = false;
|
|
113
|
+
if (s.running && !st.running) { st.running = true; st.lastActivity = t; }
|
|
114
|
+
if (s.running === false && st.running && s.source === 'status') { feed({ kind: 'turn-end', reason: s.error ? 'error' : 'completed' }); }
|
|
115
|
+
}
|
|
116
|
+
function current() {
|
|
117
|
+
const t = o.now();
|
|
118
|
+
if (st.oneShot && t < st.oneShot.until) return { state: st.oneShot.state, oneShot: true, label: st.oneShot.state };
|
|
119
|
+
if (st.oneShot && t >= st.oneShot.until) st.oneShot = null;
|
|
120
|
+
if (st.waiting) return { state: 'waiting', label: 'waiting' };
|
|
121
|
+
if (st.tools.size) { const last = Array.from(st.tools.values()).pop(); return { state: last.state, label: last.tool }; }
|
|
122
|
+
if (st.running && st.lastTool && t - st.lastToolEnd < o.toolLingerMs) return { state: st.lastTool.state, label: st.lastTool.tool };
|
|
123
|
+
if (st.running) return { state: 'thinking', label: 'thinking' };
|
|
124
|
+
return { state: 'idle', label: 'idle' };
|
|
125
|
+
}
|
|
126
|
+
return { feed, feedStatus, current, setRules, _st: st };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ---------------------------------------------------------------- v2: step tracker over the authenticated in-browser event stream
|
|
130
|
+
const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); n = n || 48; return s.length > n ? s.slice(0, n - 1) + '…' : s; };
|
|
131
|
+
const shortPath = (p) => String(p || '').split(/[\\/]/).filter(Boolean).slice(-2).join('/');
|
|
132
|
+
const extOf = (p) => { const m = /\.([A-Za-z0-9]+)$/.exec(String(p || '')); return m ? m[1].toLowerCase() : undefined; };
|
|
133
|
+
/** Parse possibly-incomplete streamed JSON arguments; falls back to regex-extracting known string fields. */
|
|
134
|
+
function partialArgs(raw) {
|
|
135
|
+
if (raw && typeof raw === 'object') return raw;
|
|
136
|
+
try { const v = JSON.parse(raw); if (v && typeof v === 'object') return v; } catch (_e) { /* partial */ }
|
|
137
|
+
const o = {}; const src = String(raw || '');
|
|
138
|
+
for (const k of ['file_path', 'path', 'pattern', 'command', 'description', 'query', 'url', 'prompt', 'name', 'server', 'tool']) {
|
|
139
|
+
const m = new RegExp('"' + k + '"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"').exec(src);
|
|
140
|
+
if (m) { let v; try { v = JSON.parse('"' + m[1] + '"'); } catch (_e) { v = m[1].replace(/\\(["\\/])/g, '$1').replace(/\\[nrt]/g, ' '); } o[k] = v; }
|
|
141
|
+
}
|
|
142
|
+
const q = /"queries"\s*:\s*\[\s*"((?:[^"\\]|\\.)*)"/.exec(src); if (q) o.queries = [q[1]];
|
|
143
|
+
return o;
|
|
144
|
+
}
|
|
145
|
+
/** Chinese one-line description of what a tool call is doing (args stay in the browser). */
|
|
146
|
+
function actionText(tool, a) {
|
|
147
|
+
a = a || {}; const t = String(tool || ''); const f = shortPath(a.file_path || a.path || a.notebook_path);
|
|
148
|
+
if (!t) return '准备调用工具…';
|
|
149
|
+
if (/^(mcp__|mcp[_-])/i.test(t)) { const parts = t.replace(/^mcp(__|[_-])/i, '').split(/__|\//); return '调用 MCP: ' + clip(parts.join(' · '), 40); }
|
|
150
|
+
switch (t) {
|
|
151
|
+
case 'read': case 'read_image': return '正在读 ' + (f || '文件');
|
|
152
|
+
case 'write': return '正在写 ' + (f || '文件');
|
|
153
|
+
case 'edit': case 'str_replace_editor': return '正在改 ' + (f || '文件');
|
|
154
|
+
case 'grep': return '正在搜索 "' + clip(a.pattern, 30) + '"' + (a.path && a.path !== '.' ? ' @ ' + shortPath(a.path) : '');
|
|
155
|
+
case 'glob': return '正在查找文件 ' + clip(a.pattern, 36);
|
|
156
|
+
case 'web_search': return '正在联网搜索 "' + clip((a.queries && a.queries[0]) || a.query, 30) + '"';
|
|
157
|
+
case 'web_fetch': return '正在抓取 ' + clip(a.url, 40);
|
|
158
|
+
case 'bash': case 'pwsh': return '运行 ' + clip(a.command, 44);
|
|
159
|
+
case 'todo_write': return '正在更新待办' + (Array.isArray(a.todos) ? '(' + a.todos.length + ' 项)' : '');
|
|
160
|
+
case 'subagent': case 'spawn_teammate': return '派出子代理:' + clip(a.description || a.prompt, 36);
|
|
161
|
+
case 'send_message': return '给子代理发消息';
|
|
162
|
+
case 'ask_user_question': return '正在向你提问';
|
|
163
|
+
case 'job_output': return '查看后台任务输出';
|
|
164
|
+
case 'present': return '正在展示交付物';
|
|
165
|
+
case 'lsp': return '查询代码索引';
|
|
166
|
+
default: return '调用工具 ' + t + (f ? ' · ' + f : '');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function resultBrief(message) {
|
|
170
|
+
const m = message || {}; const c = m.content;
|
|
171
|
+
const text = typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => (x && x.text) || '').join('\n') : '';
|
|
172
|
+
const line = text.split('\n').map((x) => x.replace(/<\/?[a-z_]+>/g, '').trim()).find((x) => x) || '';
|
|
173
|
+
return clip(line.replace(/^Error:\s*/i, ''), 70);
|
|
174
|
+
}
|
|
175
|
+
let frameSeq = 0;
|
|
176
|
+
/**
|
|
177
|
+
* Pure reducer + display queue for one Session. feed() takes SessionEventLikeEntry objects
|
|
178
|
+
* ({type:'event'|'transient', event}). Live entries enqueue display frames that are each shown
|
|
179
|
+
* for at least `dwellMs`; history entries rebuild state silently.
|
|
180
|
+
*/
|
|
181
|
+
function createTracker(opts) {
|
|
182
|
+
const o = Object.assign({ dwellMs: 600, now: () => Date.now(), schedule: (fn, ms) => setTimeout(fn, ms), rules: null }, opts || {});
|
|
183
|
+
let compiled = compileRules(o.rules || DEFAULT_RULES);
|
|
184
|
+
const S = { turn: 0, active: false, turnStart: 0, turnEnd: 0, steps: [], byCall: new Map(), queue: [], cur: null, curShownAt: 0, version: 0, turns: new Map(), lastSeq: -1, lastLiveAt: 0, outcome: null, subagents: 0 };
|
|
185
|
+
const listeners = new Set(); let timer = null;
|
|
186
|
+
const emit = () => { S.version++; listeners.forEach((f) => { try { f(); } catch (_e) { /* ignore */ } }); };
|
|
187
|
+
function show(fr) { S.cur = fr; S.curShownAt = o.now(); fr.shownAt = S.curShownAt; }
|
|
188
|
+
function arm() {
|
|
189
|
+
if (timer || !S.queue.length) return;
|
|
190
|
+
const wait = Math.max(0, o.dwellMs - (o.now() - S.curShownAt));
|
|
191
|
+
timer = o.schedule(() => { timer = null; if (S.queue.length) { show(S.queue.shift()); emit(); } arm(); }, wait);
|
|
192
|
+
}
|
|
193
|
+
function push(fr, ctx) {
|
|
194
|
+
fr.id = ++frameSeq; fr.turn = S.turn; fr.eventTime = ctx.time; fr.recvAt = ctx.recvAt;
|
|
195
|
+
if (!ctx.live) { S.queue.length = 0; S.cur = fr; S.curShownAt = 0; return; }
|
|
196
|
+
const last = S.queue[S.queue.length - 1] || S.cur;
|
|
197
|
+
if (last && fr.kind === 'thinking' && last.kind === 'thinking' && last.turn === fr.turn) { last.text = fr.text; return; }
|
|
198
|
+
if (!S.cur || (!S.queue.length && o.now() - S.curShownAt >= o.dwellMs)) show(fr); else { S.queue.push(fr); arm(); }
|
|
199
|
+
}
|
|
200
|
+
function stepFor(id, tool, ctx) {
|
|
201
|
+
let st = id ? S.byCall.get(id) : null; let created = false;
|
|
202
|
+
if (!st) {
|
|
203
|
+
st = { n: S.steps.length + 1, callId: id, tool: tool || '', raw: '', args: {}, status: 'streaming', startAt: ctx.time, endAt: 0, result: '', text: '' };
|
|
204
|
+
S.steps.push(st); if (id) S.byCall.set(id, st); created = true;
|
|
205
|
+
}
|
|
206
|
+
return [st, created];
|
|
207
|
+
}
|
|
208
|
+
function finishStep(st) { st.state = stateForTool(st.tool, { ext: extOf(st.args.file_path || st.args.path) }, compiled); st.text = actionText(st.tool, st.args); }
|
|
209
|
+
function feed(entry, live, recvAt) {
|
|
210
|
+
const ev = entry && entry.event; if (!ev || !ev.type) return;
|
|
211
|
+
if (entry.type === 'event' && typeof ev.seq === 'number') { if (ev.seq <= S.lastSeq) return; S.lastSeq = ev.seq; }
|
|
212
|
+
const d = ev.data || {}; const ctx = { live: !!live, time: ev.time || o.now(), recvAt: recvAt || o.now() };
|
|
213
|
+
if (live) S.lastLiveAt = ctx.recvAt;
|
|
214
|
+
switch (ev.type) {
|
|
215
|
+
case 'turn/start': {
|
|
216
|
+
S.turn = d.turn || S.turn + 1; S.active = true; S.turnStart = ctx.time; S.turnEnd = 0; S.outcome = null;
|
|
217
|
+
S.steps = []; S.byCall = new Map(); S.turns.set(S.turn, { steps: S.steps, startAt: ctx.time, endAt: 0, outcome: null });
|
|
218
|
+
push({ kind: 'thinking', state: 'thinking', text: '正在思考…' }, ctx); break;
|
|
219
|
+
}
|
|
220
|
+
case 'assistant/live-chunk': {
|
|
221
|
+
const c = d.chunk || {}; if (!S.active) break;
|
|
222
|
+
if (c.type === 'reasoning-delta') push({ kind: 'thinking', state: 'thinking', text: '思考中…' }, ctx);
|
|
223
|
+
else if (c.type === 'text-delta') push({ kind: 'thinking', state: 'thinking', text: '正在组织回复…' }, ctx);
|
|
224
|
+
else if (c.type === 'tool-call-delta') {
|
|
225
|
+
const [st, created] = stepFor(c.id, c.name, ctx);
|
|
226
|
+
if (c.name) st.tool = c.name; st.raw += c.argumentsDelta || ''; st.args = partialArgs(st.raw); finishStep(st);
|
|
227
|
+
if (created) push({ kind: 'tool', step: st, partial: true }, ctx);
|
|
228
|
+
} else return;
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
case 'tool/call': {
|
|
232
|
+
const [st, created] = stepFor(d.callId, d.name, ctx);
|
|
233
|
+
st.tool = d.name || st.tool; st.args = partialArgs(d.arguments); if (st.status === 'streaming') st.status = 'running'; finishStep(st);
|
|
234
|
+
if (created) push({ kind: 'tool', step: st }, ctx);
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
case 'approval/asked': {
|
|
238
|
+
const st = (d.callId && S.byCall.get(d.callId)) || S.steps.filter((x) => x.status === 'running' || x.status === 'streaming').pop();
|
|
239
|
+
if (st) { st.status = 'waiting'; st.approvalId = d.id; }
|
|
240
|
+
push({ kind: 'waiting', state: 'waiting', step: st, text: '等待你批准:' + clip(d.reason || (st && st.text) || d.toolName, 40) }, ctx); break;
|
|
241
|
+
}
|
|
242
|
+
case 'approval/decided': {
|
|
243
|
+
const st = S.steps.find((x) => x.approvalId === d.id);
|
|
244
|
+
if (d.outcome === 'allowed-once') { if (st) st.status = 'running'; push({ kind: 'tool', step: st, text: st ? '已批准 · ' + st.text : '已批准' }, ctx); }
|
|
245
|
+
else { if (st) { st.status = 'error'; st.result = d.outcome === 'rejected' ? '已拒绝' : '审批' + d.outcome; } push({ kind: 'error', state: 'error', step: st, text: '审批未通过(' + d.outcome + ')' }, ctx); }
|
|
246
|
+
break;
|
|
247
|
+
}
|
|
248
|
+
case 'job/registered': { const st = d.toolCall && S.byCall.get(d.toolCall.callId); if (st) st.job = true; break; }
|
|
249
|
+
case 'subagent/catalog': case 'tool-workflow/agent-start': {
|
|
250
|
+
S.subagents++; push({ kind: 'subagent', state: 'subagents', text: '子代理「' + clip(d.label || d.name || '', 24) + '」已启动' }, ctx); break;
|
|
251
|
+
}
|
|
252
|
+
case 'tool/result': {
|
|
253
|
+
const m = d.message || {}; const id = m.toolCallId || (m.source && m.source.callId);
|
|
254
|
+
const st = S.byCall.get(id); if (!st) break;
|
|
255
|
+
st.status = m.isError ? 'error' : 'ok'; st.endAt = ctx.time; st.result = resultBrief(m) || (m.isError ? '失败' : '完成');
|
|
256
|
+
if (m.isError) push({ kind: 'error', state: 'error', step: st, text: '失败:' + st.result }, ctx);
|
|
257
|
+
else emit();
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
case 'llm/retry': push({ kind: 'error', state: 'error', text: '模型请求失败,正在重试' }, ctx); break;
|
|
261
|
+
case 'turn/end': {
|
|
262
|
+
const k = (d.reason && d.reason.kind) || 'completed'; const ok = /^(completed|complete|stop|end_turn|done|ok)$/i.test(k);
|
|
263
|
+
const cancelled = /cancel|interrupt|abort/i.test(k);
|
|
264
|
+
S.active = false; S.turnEnd = ctx.time; S.outcome = ok ? 'ok' : cancelled ? 'cancelled' : 'error';
|
|
265
|
+
const rec = S.turns.get(S.turn); if (rec) { rec.endAt = ctx.time; rec.outcome = S.outcome; }
|
|
266
|
+
for (const st of S.steps) if (st.status === 'running' || st.status === 'streaming' || st.status === 'waiting') st.status = cancelled ? 'cancelled' : 'error';
|
|
267
|
+
push({ kind: ok ? 'done' : 'error', state: ok ? 'done' : cancelled ? 'idle' : 'error', text: ok ? '完成 · 共 ' + S.steps.length + ' 步' : cancelled ? '已中断' : '本轮出错(' + k + ')' }, ctx);
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
default: return;
|
|
271
|
+
}
|
|
272
|
+
if (live) emit();
|
|
273
|
+
}
|
|
274
|
+
function reset() { S.steps = []; S.byCall = new Map(); S.queue.length = 0; S.cur = null; S.lastSeq = -1; S.active = false; S.turns = new Map(); }
|
|
275
|
+
/** Current display: frame state resolved for a tool frame, live step reference. */
|
|
276
|
+
function view() {
|
|
277
|
+
const fr = S.cur; const now = o.now();
|
|
278
|
+
let state = 'idle'; let text = '待机中';
|
|
279
|
+
if (fr) {
|
|
280
|
+
state = fr.kind === 'tool' ? (fr.step && fr.step.state) || 'tools' : fr.state;
|
|
281
|
+
text = fr.text || (fr.step && fr.step.text) || '';
|
|
282
|
+
if (fr.kind === 'tool' && fr.step && fr.step.status === 'waiting') state = 'waiting';
|
|
283
|
+
}
|
|
284
|
+
if (!S.active && fr && (fr.kind === 'done' || fr.kind === 'error') && !S.queue.length && now - S.curShownAt > 4000 && S.curShownAt) { state = 'idle'; text = '待机中'; }
|
|
285
|
+
return { state, text, frame: fr, active: S.active, turn: S.turn, turnStart: S.turnStart, turnEnd: S.turnEnd, steps: S.steps, queued: S.queue.length, outcome: S.outcome, version: S.version };
|
|
286
|
+
}
|
|
287
|
+
return { feed, reset, view, S, setRules: (r) => { compiled = compileRules(r && r.length ? r : DEFAULT_RULES); }, setDwell: (ms) => { o.dwellMs = ms; }, subscribe: (f) => { listeners.add(f); return () => listeners.delete(f); }, emit };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ---------------------------------------------------------------- settings store (shared by every surface)
|
|
291
|
+
const LS_KEY2 = 'dsh-task-mascot:settings:v2';
|
|
292
|
+
const DEFAULT_SETTINGS = { inline: true, dock: true, pet: false, pack: 'dafeiyu', size: 160, cardSize: 96, corner: 'bottom-right', pos: null, rules: null, showChip: true, opacity: 1, dwellMs: 600, sound: false, avoid: true };
|
|
293
|
+
function loadSettings() {
|
|
294
|
+
try {
|
|
295
|
+
const v2 = localStorage.getItem(LS_KEY2);
|
|
296
|
+
if (v2) return Object.assign({}, DEFAULT_SETTINGS, JSON.parse(v2));
|
|
297
|
+
const v1 = JSON.parse(localStorage.getItem(LS_KEY) || 'null'); // migrate v1: `enabled` meant the floating pet
|
|
298
|
+
if (v1) { const m = Object.assign({}, DEFAULT_SETTINGS, v1, { pet: v1.enabled !== false }); delete m.enabled; return m; }
|
|
299
|
+
} catch (_e) { /* fallthrough */ }
|
|
300
|
+
return Object.assign({}, DEFAULT_SETTINGS);
|
|
301
|
+
}
|
|
302
|
+
const store = { value: loadSettings(), subs: new Set() };
|
|
303
|
+
function setSettings(patch) { store.value = Object.assign({}, store.value, patch); try { localStorage.setItem(LS_KEY2, JSON.stringify(store.value)); } catch (_e) { /* ignore */ } store.subs.forEach((f) => f()); }
|
|
304
|
+
function useSettings() {
|
|
305
|
+
const [, force] = React.useState(0);
|
|
306
|
+
React.useEffect(() => { const f = () => force((n) => n + 1); store.subs.add(f); return () => store.subs.delete(f); }, []);
|
|
307
|
+
return store.value;
|
|
308
|
+
}
|
|
309
|
+
function usePackManifest(pack) {
|
|
310
|
+
const [manifest, setManifest] = React.useState(null);
|
|
311
|
+
React.useEffect(() => { let ok = true; fetchManifest(pack).then((m) => { if (ok) setManifest(m); }); return () => { ok = false; }; }, [pack]);
|
|
312
|
+
return manifest;
|
|
313
|
+
}
|
|
314
|
+
const manifests = new Map();
|
|
315
|
+
function fetchManifest(pack) {
|
|
316
|
+
if (!manifests.has(pack)) manifests.set(pack, fetch(API + '/asset?f=' + encodeURIComponent(pack + '/manifest.json')).then((r) => (r.ok ? r.json() : null)).catch(() => null));
|
|
317
|
+
return manifests.get(pack);
|
|
318
|
+
}
|
|
319
|
+
let packsPromise = null;
|
|
320
|
+
function fetchPacks() { packsPromise = packsPromise || fetch(API + '/packs').then((r) => r.json()).then((j) => j.packs || []).catch(() => []); return packsPromise; }
|
|
321
|
+
function assetUrl(pack, file) { return API + '/asset?f=' + encodeURIComponent(pack + '/' + file); }
|
|
322
|
+
function canPlayAlphaWebm() {
|
|
323
|
+
// Safari/iOS decode VP9 but drop the alpha plane -> use animated WebP there.
|
|
324
|
+
const ua = navigator.userAgent || '';
|
|
325
|
+
const safari = /Safari\//.test(ua) && !/(Chrome|Chromium|Edg|OPR|Firefox)\//.test(ua);
|
|
326
|
+
if (safari) return false;
|
|
327
|
+
const v = document.createElement('video');
|
|
328
|
+
return !!v.canPlayType && v.canPlayType('video/webm; codecs="vp09.00.10.08"') !== '' || v.canPlayType('video/webm; codecs="vp9"') !== '';
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ---------------------------------------------------------------- double-buffered player
|
|
332
|
+
function Player({ pack, manifest, state, size, onOneShotEnd }) {
|
|
333
|
+
const aRef = React.useRef(null); const bRef = React.useRef(null);
|
|
334
|
+
const front = React.useRef(0); const shown = React.useRef(null);
|
|
335
|
+
const useVideo = React.useMemo(() => canPlayAlphaWebm(), []);
|
|
336
|
+
const [imgSrc, setImgSrc] = React.useState(null);
|
|
337
|
+
React.useEffect(() => {
|
|
338
|
+
if (!manifest || !state) return;
|
|
339
|
+
const entry = manifest.states[state]; if (!entry) return;
|
|
340
|
+
const key = pack + '/' + state;
|
|
341
|
+
if (shown.current === key) return;
|
|
342
|
+
if (!useVideo) { setImgSrc(assetUrl(pack, entry.webp || entry.poster)); shown.current = key; return; }
|
|
343
|
+
const vids = [aRef.current, bRef.current]; const back = vids[1 - front.current]; const cur = vids[front.current];
|
|
344
|
+
if (!back) return;
|
|
345
|
+
let cancelled = false;
|
|
346
|
+
back.loop = entry.loop !== false; back.muted = true; back.playsInline = true;
|
|
347
|
+
back.src = assetUrl(pack, entry.webm); back.poster = entry.poster ? assetUrl(pack, entry.poster) : '';
|
|
348
|
+
const swap = () => {
|
|
349
|
+
if (cancelled) return;
|
|
350
|
+
back.play().catch(() => {}).finally(() => {
|
|
351
|
+
if (cancelled) return;
|
|
352
|
+
back.style.opacity = '1'; if (cur) cur.style.opacity = '0';
|
|
353
|
+
front.current = 1 - front.current; shown.current = key;
|
|
354
|
+
setTimeout(() => { if (cur && !cancelled) { cur.pause(); } }, 120);
|
|
355
|
+
});
|
|
356
|
+
};
|
|
357
|
+
// Only reveal the back buffer once a frame is decoded: no blank flash between clips.
|
|
358
|
+
if (back.readyState >= 2) swap(); else back.addEventListener('loadeddata', swap, { once: true });
|
|
359
|
+
return () => { cancelled = true; back.removeEventListener('loadeddata', swap); };
|
|
360
|
+
}, [pack, manifest, state, useVideo]);
|
|
361
|
+
const vstyle = { position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', transition: 'opacity 90ms linear', pointerEvents: 'none', background: 'transparent' };
|
|
362
|
+
if (!useVideo) return h('img', { src: imgSrc || '', alt: state || '', draggable: false, style: Object.assign({}, vstyle, { position: 'static' }), 'data-mascot-state': state });
|
|
363
|
+
const ended = () => onOneShotEnd && onOneShotEnd();
|
|
364
|
+
return h('div', { style: { position: 'relative', width: size, height: size } },
|
|
365
|
+
h('video', { ref: aRef, muted: true, playsInline: true, autoPlay: true, onEnded: ended, style: Object.assign({}, vstyle, { opacity: 0 }), 'data-buf': 'a' }),
|
|
366
|
+
h('video', { ref: bRef, muted: true, playsInline: true, autoPlay: true, onEnded: ended, style: Object.assign({}, vstyle, { opacity: 0 }), 'data-buf': 'b' }));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ---------------------------------------------------------------- v2 surfaces: tracker registry, inline card, dock bar, turn summary, pet
|
|
370
|
+
const STATE_ZH = { idle: '待机', thinking: '思考中', reading: '读文件', search: '搜索', coding: '写代码', editing: '改代码', writingdoc: '写文档', cmd: '跑命令', data: '跑数据', planning: '做计划', subagents: '派子代理', tools: '用工具', summary: '总结', waiting: '等你确认', done: '完成', error: '出错了' };
|
|
371
|
+
const STATE_ICON = { thinking: '💭', reading: '📖', search: '🔍', coding: '⌨️', editing: '✏️', writingdoc: '📝', cmd: '💻', data: '📊', planning: '🗂️', subagents: '🤝', tools: '🧰', summary: '📋', waiting: '✋', done: '✅', error: '❌', idle: '😴' };
|
|
372
|
+
const STATUS_MARK = { ok: { c: '#30a46c', m: '✓' }, error: { c: '#e5484d', m: '✗' }, waiting: { c: '#f5a524', m: '⏳' }, running: { c: '#3e63dd', m: '•' }, streaming: { c: '#8e4ec6', m: '…' }, cancelled: { c: '#888', m: '–' } };
|
|
373
|
+
const ReactDOM = require('react-dom');
|
|
374
|
+
const host = { ctx: null, trackers: new Map(), lastLive: null, subs: new Set() };
|
|
375
|
+
const notifyHost = () => host.subs.forEach((f) => f());
|
|
376
|
+
const LAT = (window.__dshMascotLatency = window.__dshMascotLatency || []);
|
|
377
|
+
let actx = null;
|
|
378
|
+
/** Optional short WebAudio cue (off by default): waiting = two rising notes, done = chime, error = low buzz. */
|
|
379
|
+
function cue(kind) {
|
|
380
|
+
try {
|
|
381
|
+
actx = actx || new (window.AudioContext || window.webkitAudioContext)(); const t = actx.currentTime;
|
|
382
|
+
const notes = kind === 'waiting' ? [[660, 0], [880, 0.14]] : kind === 'done' ? [[784, 0], [1046, 0.12]] : [[220, 0], [196, 0.16]];
|
|
383
|
+
for (const [f, dt] of notes) { const o = actx.createOscillator(); const g = actx.createGain(); o.type = kind === 'error' ? 'square' : 'sine'; o.frequency.value = f; g.gain.setValueAtTime(0.0001, t + dt); g.gain.exponentialRampToValueAtTime(0.08, t + dt + 0.02); g.gain.exponentialRampToValueAtTime(0.0001, t + dt + 0.18); o.connect(g).connect(actx.destination); o.start(t + dt); o.stop(t + dt + 0.2); }
|
|
384
|
+
} catch (_e) { /* audio unavailable */ }
|
|
385
|
+
}
|
|
386
|
+
let cssDone = false;
|
|
387
|
+
function ensureCss() {
|
|
388
|
+
if (cssDone) return; cssDone = true;
|
|
389
|
+
const st = document.createElement('style'); st.setAttribute('data-mascot-css', '');
|
|
390
|
+
st.textContent = '@keyframes dshMascotIn{from{opacity:0;transform:translateY(3px)}to{opacity:1;transform:none}}[data-mascot-action]{animation:dshMascotIn .18s ease-out}[data-mascot-card]{transition:border-color .2s}[data-mascot-host-in]{animation:dshMascotIn .22s ease-out}#dsh-task-mascot{transition:transform .25s ease}';
|
|
391
|
+
document.head.appendChild(st);
|
|
392
|
+
}
|
|
393
|
+
function getTracker(sid) {
|
|
394
|
+
if (!sid || !host.ctx || !host.ctx.sessions) return null;
|
|
395
|
+
const have = host.trackers.get(sid); if (have) return have;
|
|
396
|
+
let binding; try { binding = host.ctx.sessions.binding(sid); } catch (_e) { binding = null; }
|
|
397
|
+
if (!binding || !binding.eventSource) return null;
|
|
398
|
+
const tr = createTracker({ dwellMs: store.value.dwellMs, rules: store.value.rules }); tr.sid = sid;
|
|
399
|
+
const src = binding.eventSource;
|
|
400
|
+
const replay = (w) => { tr.reset(); for (const e of w.entries || []) tr.feed(e, false); tr.emit(); };
|
|
401
|
+
replay(src.getSnapshot());
|
|
402
|
+
tr.unsub = src.subscribe(() => {
|
|
403
|
+
const w = src.getSnapshot(); const ch = w.change || {}; const recvAt = Date.now();
|
|
404
|
+
if (ch.kind === 'append') { for (const e of ch.entries || []) tr.feed(e, true, recvAt); if (host.lastLive !== tr) { host.lastLive = tr; notifyHost(); } }
|
|
405
|
+
else if (ch.kind === 'replace') replay(w);
|
|
406
|
+
});
|
|
407
|
+
let lastCue = 0; tr.subscribe(() => { const f = tr.S.cur; if (!f || f.id === lastCue || !f.recvAt) return; lastCue = f.id; if (store.value.sound && (f.kind === 'waiting' || f.kind === 'done' || f.kind === 'error')) cue(f.kind); });
|
|
408
|
+
host.trackers.set(sid, tr); notifyHost();
|
|
409
|
+
return tr;
|
|
410
|
+
}
|
|
411
|
+
function useTracker(sid) {
|
|
412
|
+
const [tr, setTr] = React.useState(() => getTracker(sid));
|
|
413
|
+
React.useEffect(() => { if (tr && tr.sid === sid) return undefined; let n = 0; const iv = setInterval(() => { const t = getTracker(sid); if (t || ++n > 40) { clearInterval(iv); if (t) setTr(t); } }, 250); const t0 = getTracker(sid); if (t0) { clearInterval(iv); setTr(t0); } return () => clearInterval(iv); }, [sid]);
|
|
414
|
+
return tr && tr.sid === sid ? tr : null;
|
|
415
|
+
}
|
|
416
|
+
function useView(tr) {
|
|
417
|
+
const [, force] = React.useState(0);
|
|
418
|
+
React.useEffect(() => { if (!tr) return undefined; const un = tr.subscribe(() => force((n) => n + 1)); return un; }, [tr]);
|
|
419
|
+
const v = tr ? tr.view() : null;
|
|
420
|
+
const live = !!(v && (v.active || v.queued || (v.turnEnd && Date.now() - v.turnEnd < 6000)));
|
|
421
|
+
React.useEffect(() => { if (!live) return undefined; const iv = setInterval(() => force((n) => n + 1), 250); return () => clearInterval(iv); }, [live]);
|
|
422
|
+
const s = useSettings();
|
|
423
|
+
React.useEffect(() => { if (tr) { tr.setRules(s.rules); tr.setDwell(s.dwellMs || 600); } }, [tr, s.rules, s.dwellMs]);
|
|
424
|
+
return v;
|
|
425
|
+
}
|
|
426
|
+
/** Record event→DOM latency once per (frame, surface). recvAt/eventTime are ms epoch; paint is the next animation frame. */
|
|
427
|
+
function useLatency(v, surface, ref) {
|
|
428
|
+
const fr = v && v.frame;
|
|
429
|
+
React.useLayoutEffect(() => {
|
|
430
|
+
if (!fr || !fr.recvAt || !fr.shownAt) return;
|
|
431
|
+
const key = surface + ':' + fr.id; if (useLatency.seen.has(key)) return; useLatency.seen.add(key);
|
|
432
|
+
const commit = Date.now();
|
|
433
|
+
requestAnimationFrame(() => {
|
|
434
|
+
const paint = Date.now();
|
|
435
|
+
const rec = { surface, frame: fr.id, kind: fr.kind, state: v.state, eventToRecv: fr.eventTime ? fr.recvAt - fr.eventTime : null, queueWait: fr.shownAt - fr.recvAt, shownToCommit: commit - fr.shownAt, recvToPaint: paint - fr.recvAt, eventToPaint: fr.eventTime ? paint - fr.eventTime : null, at: paint };
|
|
436
|
+
LAT.push(rec); if (LAT.length > 2000) LAT.shift();
|
|
437
|
+
if (ref && ref.current) ref.current.setAttribute('data-latency', JSON.stringify(rec));
|
|
438
|
+
});
|
|
439
|
+
}, [fr && fr.id, surface]);
|
|
440
|
+
}
|
|
441
|
+
useLatency.seen = new Set();
|
|
442
|
+
const fmtDur = (ms) => { ms = Math.max(0, ms | 0); const s = Math.floor(ms / 1000); return s < 60 ? (ms / 1000).toFixed(1) + 's' : Math.floor(s / 60) + 'm' + String(s % 60).padStart(2, '0') + 's'; };
|
|
443
|
+
function StepIcons({ steps, max, current }) {
|
|
444
|
+
const list = steps.slice(-(max || 10));
|
|
445
|
+
return h('div', { 'data-mascot-timeline': '', style: { display: 'flex', gap: 3, flexWrap: 'wrap', alignItems: 'center' } },
|
|
446
|
+
steps.length > list.length ? h('span', { style: { fontSize: 11, opacity: 0.6 } }, '+' + (steps.length - list.length)) : null,
|
|
447
|
+
list.map((st) => {
|
|
448
|
+
const mk = STATUS_MARK[st.status] || STATUS_MARK.running; const cur = current && current === st;
|
|
449
|
+
return h('span', { key: st.n, 'data-step': st.n, 'data-status': st.status, title: '第 ' + st.n + ' 步 · ' + st.text + (st.result ? '\n→ ' + st.result : '') + (st.endAt ? '\n用时 ' + fmtDur(st.endAt - st.startAt) : ''),
|
|
450
|
+
style: { position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 22, height: 22, borderRadius: 6, fontSize: 12, background: cur ? 'rgba(62,99,221,.16)' : 'rgba(127,127,127,.12)', outline: cur ? '1.5px solid #3e63dd' : 'none' } },
|
|
451
|
+
STATE_ICON[st.state] || '🧰',
|
|
452
|
+
h('span', { style: { position: 'absolute', right: -3, bottom: -3, fontSize: 9, lineHeight: '11px', minWidth: 11, textAlign: 'center', borderRadius: 6, color: '#fff', background: mk.c } }, mk.m));
|
|
453
|
+
}));
|
|
454
|
+
}
|
|
455
|
+
function StepList({ steps }) {
|
|
456
|
+
return h('ol', { 'data-mascot-steplist': '', style: { margin: '6px 0 0', padding: '0 0 0 18px', fontSize: 12, lineHeight: 1.6, maxHeight: 220, overflow: 'auto' } },
|
|
457
|
+
steps.map((st) => h('li', { key: st.n, 'data-status': st.status, style: { color: st.status === 'error' ? '#e5484d' : 'inherit' } },
|
|
458
|
+
(STATE_ICON[st.state] || '🧰') + ' ' + st.text + (st.result ? ' → ' + clip(st.result, 60) : '') + (st.endAt ? '(' + fmtDur(st.endAt - st.startAt) + ')' : st.status === 'waiting' ? '(等待批准)' : ''))));
|
|
459
|
+
}
|
|
460
|
+
function CardBody({ v, size, compact, manifest, pack, surface }) {
|
|
461
|
+
const ref = React.useRef(null); useLatency(v, surface, ref); ensureCss();
|
|
462
|
+
const [open, setOpen] = React.useState(false);
|
|
463
|
+
const now = Date.now(); const fr = v.frame || {}; const st = fr.step;
|
|
464
|
+
const resolved = resolveState(v.state, manifest);
|
|
465
|
+
const stepNo = st ? st.n : v.steps.length;
|
|
466
|
+
const stepElapsed = st ? (st.endAt || (v.active ? now : v.turnEnd || now)) - st.startAt : 0;
|
|
467
|
+
const turnElapsed = v.turnStart ? (v.active ? now : v.turnEnd || now) - v.turnStart : 0;
|
|
468
|
+
const lastDone = v.steps.slice().reverse().find((x) => x.status === 'ok' || x.status === 'error');
|
|
469
|
+
const tone = v.state === 'error' ? '#e5484d' : v.state === 'waiting' ? '#f5a524' : v.state === 'done' ? '#30a46c' : '#3e63dd';
|
|
470
|
+
return h('div', { onClick: compact ? undefined : () => setOpen((x) => !x), title: compact ? undefined : '点击展开/收起本轮全部步骤', style: { cursor: compact ? 'default' : 'pointer' } }, h('div', { ref, 'data-mascot-card': surface, 'data-state': v.state, 'data-resolved': resolved || '', 'data-step': stepNo, 'data-queued': v.queued,
|
|
471
|
+
style: { display: 'flex', gap: compact ? 10 : 14, alignItems: 'center', padding: compact ? '6px 10px' : '10px 14px', borderRadius: 12, border: '1px solid ' + tone + '55', background: 'var(--dsw-alias-bg-l1, rgba(127,127,127,.06))', boxShadow: '0 1px 6px rgba(0,0,0,.06)', font: '13px/1.45 system-ui, sans-serif', color: 'inherit', maxWidth: '100%' } },
|
|
472
|
+
h('div', { style: { flex: 'none', width: size, height: size } }, manifest ? h(Player, { pack, manifest, state: resolved, size }) : null),
|
|
473
|
+
h('div', { style: { minWidth: 0, flex: 1, display: 'flex', flexDirection: compact ? 'row' : 'column', gap: compact ? 12 : 4, alignItems: compact ? 'center' : 'stretch' } },
|
|
474
|
+
h('div', { style: { display: 'flex', gap: 8, alignItems: 'baseline', minWidth: 0, flex: compact ? '1 1 auto' : 'none' } },
|
|
475
|
+
h('span', { style: { flex: 'none', fontSize: 11, padding: '0 6px', borderRadius: 8, color: '#fff', background: tone } }, STATE_ZH[v.state] || v.state),
|
|
476
|
+
h('span', { key: v.text, 'data-mascot-action': '', style: { fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } }, v.text || '')),
|
|
477
|
+
h('div', { style: { display: 'flex', gap: 10, fontSize: 12, opacity: 0.75, flex: 'none', whiteSpace: 'nowrap' } },
|
|
478
|
+
stepNo ? h('span', { 'data-mascot-stepno': '' }, '第 ' + stepNo + ' 步') : null,
|
|
479
|
+
st ? h('span', null, '本步 ' + fmtDur(stepElapsed)) : null,
|
|
480
|
+
turnElapsed ? h('span', { 'data-mascot-elapsed': '' }, '总计 ' + fmtDur(turnElapsed)) : null,
|
|
481
|
+
v.queued ? h('span', { title: '排队等待展示的步骤' }, '队列 ' + v.queued) : null),
|
|
482
|
+
!compact && v.steps.length ? h(StepIcons, { steps: v.steps, max: 14, current: st }) : null,
|
|
483
|
+
compact && v.steps.length ? h(StepIcons, { steps: v.steps, max: 8, current: st }) : null,
|
|
484
|
+
!compact && lastDone ? h('div', { 'data-mascot-result': lastDone.status, style: { fontSize: 12, color: lastDone.status === 'error' ? '#e5484d' : '#30a46c', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } },
|
|
485
|
+
(lastDone.status === 'error' ? '✗ ' : '✓ ') + '第 ' + lastDone.n + ' 步 ' + clip(lastDone.text, 24) + ' → ' + (lastDone.result || (lastDone.status === 'ok' ? '完成' : '失败'))) : null)),
|
|
486
|
+
open && !compact && v.steps.length ? h(StepList, { steps: v.steps }) : null);
|
|
487
|
+
}
|
|
488
|
+
/** Align a surface to the chat column: same width as the composer card, centred. */
|
|
489
|
+
function fitToColumn(el, sid) {
|
|
490
|
+
if (!el) return;
|
|
491
|
+
const root = document.querySelector('[data-conversation-session="' + sid + '"]') || document;
|
|
492
|
+
const bar = root.querySelector('[data-slot="conversation.composer.bar"] > *') || root.querySelector('[data-slot="conversation.composer.bar"]');
|
|
493
|
+
const w = bar && bar.getBoundingClientRect().width;
|
|
494
|
+
if (w > 200) { el.style.maxWidth = Math.round(w) + 'px'; el.style.marginLeft = 'auto'; el.style.marginRight = 'auto'; el.style.boxSizing = 'border-box'; }
|
|
495
|
+
}
|
|
496
|
+
const showLive = (v) => !!v && (v.active || v.queued > 0 || (v.turnEnd && Date.now() - v.turnEnd < 4500) || (v.frame && v.frame.shownAt && Date.now() - v.frame.shownAt < 600));
|
|
497
|
+
/** Inline card: portalled into the chat column right after the last row, i.e. at the active step. */
|
|
498
|
+
function InlineCard({ sid }) {
|
|
499
|
+
const s = useSettings(); const tr = useTracker(sid); const v = useView(tr); const manifest = usePackManifest(s.pack);
|
|
500
|
+
const [el, setEl] = React.useState(null);
|
|
501
|
+
const visible = s.inline && showLive(v);
|
|
502
|
+
React.useEffect(() => {
|
|
503
|
+
if (!visible) return undefined;
|
|
504
|
+
const box = document.createElement('div'); box.setAttribute('data-mascot-inline-host', sid); box.style.cssText = 'padding:4px 0 12px;'; box.setAttribute('data-mascot-host-in', '');
|
|
505
|
+
const place = () => {
|
|
506
|
+
const tail = document.querySelector('[data-conversation-session="' + sid + '"] [data-chat-following-tail]');
|
|
507
|
+
if (!tail) return;
|
|
508
|
+
if (box.parentNode !== tail.parentNode || box.previousSibling !== tail) tail.parentNode.insertBefore(box, tail.nextSibling);
|
|
509
|
+
fitToColumn(box, sid);
|
|
510
|
+
};
|
|
511
|
+
place(); setEl(box); const iv = setInterval(place, 500);
|
|
512
|
+
return () => { clearInterval(iv); box.remove(); setEl(null); };
|
|
513
|
+
}, [visible, sid]);
|
|
514
|
+
if (!visible || !el || !v) return null;
|
|
515
|
+
return ReactDOM.createPortal(h(CardBody, { v, size: s.cardSize || 96, manifest, pack: s.pack, surface: 'inline' }), el);
|
|
516
|
+
}
|
|
517
|
+
function DockBar({ sid }) {
|
|
518
|
+
const s = useSettings(); const tr = useTracker(sid); const v = useView(tr); const manifest = usePackManifest(s.pack);
|
|
519
|
+
const ref = React.useRef(null);
|
|
520
|
+
React.useLayoutEffect(() => { fitToColumn(ref.current, sid); });
|
|
521
|
+
if (!s.dock || !showLive(v)) return null;
|
|
522
|
+
return h('div', { ref, 'data-mascot-dock': sid, style: { padding: '0 0 6px' } }, h(CardBody, { v, size: 40, compact: true, manifest, pack: s.pack, surface: 'dock' }));
|
|
523
|
+
}
|
|
524
|
+
function SessionSurfaces(props) {
|
|
525
|
+
const sid = props.sid;
|
|
526
|
+
return h(React.Fragment, null, h(InlineCard, { sid }), h(DockBar, { sid }));
|
|
527
|
+
}
|
|
528
|
+
/** Completed-turn summary in the turn's tail (data comes from the tracker's per-turn record). */
|
|
529
|
+
function TurnSummary(props) {
|
|
530
|
+
const s = useSettings(); const tr = useTracker(props.sid); useView(tr); const [open, setOpen] = React.useState(false);
|
|
531
|
+
const turnNo = props.turn && typeof props.turn === 'object' ? props.turn.turn : props.turn;
|
|
532
|
+
if (!s.inline || !tr) return null;
|
|
533
|
+
const rec = tr.S.turns.get(turnNo); if (!rec || !rec.endAt || !rec.steps.length) return null;
|
|
534
|
+
const ok = rec.steps.filter((x) => x.status === 'ok').length; const bad = rec.steps.filter((x) => x.status === 'error').length;
|
|
535
|
+
return h('div', { 'data-mascot-turn-summary': turnNo, onClick: () => setOpen((x) => !x), title: '点击查看本轮每一步', style: { cursor: 'pointer', font: '12px system-ui, sans-serif', opacity: 0.85, padding: '4px 0' } }, h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' } },
|
|
536
|
+
h('span', null, (rec.outcome === 'ok' ? '✅' : '❌') + ' 本轮 ' + rec.steps.length + ' 步 · 用时 ' + fmtDur(rec.endAt - rec.startAt) + ' · 成功 ' + ok + (bad ? ' · 失败 ' + bad : '')),
|
|
537
|
+
h(StepIcons, { steps: rec.steps, max: 24 }), h('span', { style: { opacity: 0.6 } }, open ? '收起 ▲' : '回放 ▼')),
|
|
538
|
+
open ? h(StepList, { steps: rec.steps }) : null);
|
|
539
|
+
}
|
|
540
|
+
// ---- floating pet (follows whichever bound session produced the latest live event)
|
|
541
|
+
function useActivity(useSessions) {
|
|
542
|
+
const machineRef = React.useRef(null);
|
|
543
|
+
if (!machineRef.current) machineRef.current = createMachine({ rules: store.value.rules });
|
|
544
|
+
const m = machineRef.current;
|
|
545
|
+
const settings = useSettings();
|
|
546
|
+
React.useEffect(() => { m.setRules(settings.rules); }, [settings.rules]);
|
|
547
|
+
const [, setTick] = React.useState(0);
|
|
548
|
+
React.useEffect(() => { const iv = setInterval(() => setTick((n) => n + 1), 500); return () => clearInterval(iv); }, []);
|
|
549
|
+
const status = useSessions ? useSessions((s) => {
|
|
550
|
+
let running = false; let pending = null;
|
|
551
|
+
for (const row of Object.values((s && s.byId) || {})) {
|
|
552
|
+
const ss = row.sessionStatus || row.status || row;
|
|
553
|
+
if (ss && ss.running) running = true;
|
|
554
|
+
if (ss && ss.pendingInteraction) pending = ss.pendingInteraction.kind || 'pending';
|
|
555
|
+
}
|
|
556
|
+
return (running ? 'R' : '-') + '|' + (pending || '');
|
|
557
|
+
}) : '-|';
|
|
558
|
+
React.useEffect(() => { const [r, p] = String(status).split('|'); m.feedStatus({ running: r === 'R', pendingInteraction: p ? { kind: p } : null, source: 'status' }); setTick((n) => n + 1); }, [status]);
|
|
559
|
+
return m.current();
|
|
560
|
+
}
|
|
561
|
+
function MascotOverlay(props) {
|
|
562
|
+
const settings = useSettings();
|
|
563
|
+
const [, force] = React.useState(0);
|
|
564
|
+
React.useEffect(() => { const f = () => force((n) => n + 1); host.subs.add(f); return () => host.subs.delete(f); }, []);
|
|
565
|
+
const tr = host.lastLive; const v = useView(tr);
|
|
566
|
+
const coarse = useActivity(props.useSessions);
|
|
567
|
+
const act = v ? { state: v.state, label: v.text } : { state: coarse.state, label: coarse.label };
|
|
568
|
+
const manifest = usePackManifest(settings.pack);
|
|
569
|
+
const ref = React.useRef(null); useLatency(v, 'pet', ref);
|
|
570
|
+
const drag = React.useRef(null);
|
|
571
|
+
const [pos, setPos] = React.useState(settings.pos);
|
|
572
|
+
React.useEffect(() => { setPos(settings.pos); }, [settings.pos]);
|
|
573
|
+
const [dodge, setDodge] = React.useState(0);
|
|
574
|
+
React.useEffect(() => {
|
|
575
|
+
if (!settings.pet || settings.avoid === false) return undefined;
|
|
576
|
+
const iv = setInterval(() => {
|
|
577
|
+
const me = ref.current; if (!me) return; const r = me.getBoundingClientRect(); const base = r.top - dodge;
|
|
578
|
+
let need = 0;
|
|
579
|
+
for (const b of document.querySelectorAll('button, [role=button], textarea, [data-composer-input]')) {
|
|
580
|
+
if (me.contains(b)) continue; const q = b.getBoundingClientRect(); if (!q.width) continue;
|
|
581
|
+
const hit = q.left < r.right && q.right > r.left && q.top < base + r.height && q.bottom > base;
|
|
582
|
+
if (hit) need = Math.min(need, q.top - (base + r.height) - 8);
|
|
583
|
+
}
|
|
584
|
+
if (Math.abs(need - dodge) > 2) setDodge(Math.max(need, -base));
|
|
585
|
+
}, 400);
|
|
586
|
+
return () => clearInterval(iv);
|
|
587
|
+
}, [settings.pet, settings.avoid, dodge]);
|
|
588
|
+
if (!settings.pet || !manifest) return null;
|
|
589
|
+
const resolved = resolveState(act.state, manifest);
|
|
590
|
+
const size = Math.max(64, Math.min(480, settings.size | 0));
|
|
591
|
+
const anchor = pos ? { left: pos.x, top: pos.y } : ({ 'bottom-right': { right: 24, bottom: 96 }, 'bottom-left': { left: 24, bottom: 96 }, 'top-right': { right: 24, top: 64 }, 'top-left': { left: 24, top: 64 } }[settings.corner] || { right: 24, bottom: 96 });
|
|
592
|
+
const onDown = (e) => { if (e.button !== 0) return; const el = e.currentTarget; const r = el.getBoundingClientRect(); drag.current = { dx: e.clientX - r.left, dy: e.clientY - r.top, moved: false }; el.setPointerCapture(e.pointerId); };
|
|
593
|
+
const onMove = (e) => { if (!drag.current) return; drag.current.moved = true; setPos({ x: Math.max(0, Math.min(window.innerWidth - size, e.clientX - drag.current.dx)), y: Math.max(0, Math.min(window.innerHeight - size, e.clientY - drag.current.dy)) }); };
|
|
594
|
+
const onUp = () => { if (drag.current && drag.current.moved && pos) setSettings({ pos }); drag.current = null; };
|
|
595
|
+
return h('div', {
|
|
596
|
+
id: 'dsh-task-mascot', ref, 'data-state': act.state, 'data-resolved': resolved || '', 'data-pack': settings.pack,
|
|
597
|
+
onPointerDown: onDown, onPointerMove: onMove, onPointerUp: onUp, onDoubleClick: () => setSettings({ pos: null }),
|
|
598
|
+
title: (STATE_ZH[act.state] || act.state) + ' · ' + (act.label || '') + '\n拖动移动,双击归位',
|
|
599
|
+
style: Object.assign({ position: 'fixed', zIndex: 2147483000, width: size, height: size, cursor: 'grab', userSelect: 'none', touchAction: 'none', opacity: settings.opacity, transform: dodge ? 'translateY(' + dodge + 'px)' : 'none' }, anchor), 'data-dodge': dodge,
|
|
600
|
+
},
|
|
601
|
+
h(Player, { pack: settings.pack, manifest, state: resolved, size }),
|
|
602
|
+
settings.showChip ? h('div', { 'data-mascot-chip': '', style: { position: 'absolute', left: '50%', bottom: -6, transform: 'translateX(-50%)', maxWidth: size, boxSizing: 'border-box', overflow: 'hidden', textOverflow: 'ellipsis', font: '12px/18px system-ui, sans-serif', padding: '0 8px', borderRadius: 9, background: act.state === 'error' ? '#e5484d' : act.state === 'waiting' ? '#f5a524' : 'rgba(30,30,40,.72)', color: '#fff', whiteSpace: 'nowrap', pointerEvents: 'none' } },
|
|
603
|
+
v && v.text ? v.text : (STATE_ZH[act.state] || act.state)) : null);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// ---------------------------------------------------------------- settings section
|
|
607
|
+
function SettingsSection() {
|
|
608
|
+
const s = useSettings();
|
|
609
|
+
const [packs, setPacks] = React.useState([]);
|
|
610
|
+
React.useEffect(() => { fetchPacks().then(setPacks); }, []);
|
|
611
|
+
const [rulesText, setRulesText] = React.useState(JSON.stringify(s.rules || DEFAULT_RULES, null, 2));
|
|
612
|
+
const [err, setErr] = React.useState('');
|
|
613
|
+
const row = (label, ctl, key) => h('label', { key, style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '10px 0', borderBottom: '.5px solid var(--dsw-alias-border-l2, #ddd)', fontSize: 14 } }, h('span', null, label), ctl);
|
|
614
|
+
const cb = (k) => h('input', { type: 'checkbox', 'data-setting': k, checked: !!s[k], onChange: (e) => setSettings({ [k]: e.target.checked }) });
|
|
615
|
+
return h('div', { 'data-mascot-settings': '', style: { maxWidth: 640 } },
|
|
616
|
+
h('h2', { style: { fontSize: 18, margin: '0 0 8px' } }, '任务状态角色 / Task Mascot'),
|
|
617
|
+
h('p', { style: { fontSize: 12, opacity: 0.7, margin: '0 0 8px' } }, '角色动画实时跟随 Agent 的每一步(工具调用、思考、审批、出错、完成)。三种展示位置可任意组合。'),
|
|
618
|
+
row('对话内卡片 Inline card(当前步骤处)', cb('inline')),
|
|
619
|
+
row('输入框上方状态条 Input dock bar', cb('dock')),
|
|
620
|
+
row('悬浮角色 Floating pet', cb('pet')),
|
|
621
|
+
row('角色包 Pack', h('select', { value: s.pack, onChange: (e) => setSettings({ pack: e.target.value }) }, packs.map((p) => h('option', { key: p.id, value: p.id }, p.title || p.id)))),
|
|
622
|
+
row('卡片动画大小 Card size: ' + s.cardSize + 'px', h('input', { type: 'range', min: 48, max: 200, step: 8, value: s.cardSize, onChange: (e) => setSettings({ cardSize: +e.target.value }) })),
|
|
623
|
+
row('每步最短展示 Min dwell: ' + s.dwellMs + 'ms', h('input', { type: 'range', min: 0, max: 2000, step: 100, value: s.dwellMs, onChange: (e) => setSettings({ dwellMs: +e.target.value }) })),
|
|
624
|
+
row('悬浮角色大小 Pet size: ' + s.size + 'px', h('input', { type: 'range', min: 64, max: 480, step: 8, value: s.size, onChange: (e) => setSettings({ size: +e.target.value }) })),
|
|
625
|
+
row('悬浮位置 Pet position', h('select', { value: s.corner, onChange: (e) => setSettings({ corner: e.target.value, pos: null }) }, ['bottom-right', 'bottom-left', 'top-right', 'top-left'].map((c) => h('option', { key: c, value: c }, c)))),
|
|
626
|
+
row('悬浮状态标签 Pet chip', cb('showChip')),
|
|
627
|
+
row('悬浮角色自动避让按钮/审批框 Pet avoids buttons', cb('avoid')),
|
|
628
|
+
row('提示音(审批/完成/出错)Sound cues', cb('sound')),
|
|
629
|
+
row('悬浮不透明度 Pet opacity', h('input', { type: 'range', min: 0.3, max: 1, step: 0.05, value: s.opacity, onChange: (e) => setSettings({ opacity: +e.target.value }) })),
|
|
630
|
+
h('details', { style: { marginTop: 12 } },
|
|
631
|
+
h('summary', { style: { cursor: 'pointer', fontSize: 14 } }, '工具 → 动画映射(高级)Tool → state mapping (advanced)'),
|
|
632
|
+
h('p', { style: { fontSize: 12, opacity: 0.7 } }, '按顺序匹配,第一个命中生效。tool/ext 是正则。可用状态:' + ALL_STATES.join(', ')),
|
|
633
|
+
h('textarea', { value: rulesText, onChange: (e) => setRulesText(e.target.value), spellCheck: false, style: { width: '100%', minHeight: 240, fontFamily: 'ui-monospace, monospace', fontSize: 12 } }),
|
|
634
|
+
h('div', { style: { display: 'flex', gap: 8, alignItems: 'center' } },
|
|
635
|
+
h('button', { type: 'button', onClick: () => { try { const r = JSON.parse(rulesText); if (!Array.isArray(r)) throw new Error('需要数组 / must be an array'); r.forEach((x) => { new RegExp(x.tool || '.*'); if (x.ext) new RegExp(x.ext); }); setSettings({ rules: r }); setErr('已保存 saved'); } catch (e) { setErr(String(e.message || e)); } } }, '保存 Save'),
|
|
636
|
+
h('button', { type: 'button', onClick: () => { setSettings({ rules: null }); setRulesText(JSON.stringify(DEFAULT_RULES, null, 2)); setErr('已恢复默认 reset'); } }, '恢复默认 Reset'),
|
|
637
|
+
h('span', { style: { fontSize: 12 } }, err))));
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// ---------------------------------------------------------------- plugin entry
|
|
641
|
+
const inject = ['slots', 'sessions'];
|
|
642
|
+
function apply(ctx) {
|
|
643
|
+
host.ctx = ctx;
|
|
644
|
+
ctx.slots.inject('shell.overlay', () => ctx.slots.register({ name: 'shell.overlay', id: 'dsh-task-mascot', order: 900, label: 'Task Mascot' }, MascotOverlay));
|
|
645
|
+
ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'dsh-task-mascot', order: 80, label: () => '任务角色 Mascot' }, SettingsSection));
|
|
646
|
+
ctx.slots.inject('conversation.input.dock', () => ctx.slots.register({ name: 'conversation.input.dock', id: 'dsh-task-mascot', order: 5, inject: (sessionId) => ({ sid: sessionId }) }, SessionSurfaces));
|
|
647
|
+
ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({ name: 'conversation.chat.turnTail', id: 'dsh-task-mascot', order: 50, inject: (sessionId) => ({ sid: sessionId }) }, TurnSummary));
|
|
648
|
+
}
|
|
649
|
+
exports.apply = apply;
|
|
650
|
+
exports.inject = inject;
|
|
651
|
+
exports.__internals = { DEFAULT_RULES, ALL_STATES, compileRules, stateForTool, resolveState, createMachine, createTracker, actionText, partialArgs, resultBrief, GLOBAL_FALLBACK };
|
|
652
|
+
return module.exports;
|
|
653
|
+
},
|
|
654
|
+
});
|