@zhin.js/client 1.1.3 → 1.1.5

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.
Files changed (104) hide show
  1. package/README.md +89 -433
  2. package/client/agent-stream.ts +121 -0
  3. package/client/bootstrap/loadConsoleEntries.test.ts +28 -2
  4. package/client/bootstrap/loadConsoleEntries.ts +40 -8
  5. package/client/console-events.ts +37 -0
  6. package/client/console-utils/remoteApi.test.ts +91 -0
  7. package/client/console-utils/remoteApi.ts +47 -2
  8. package/client/index.ts +75 -19
  9. package/client/mediaSrc.test.ts +49 -0
  10. package/client/mediaSrc.ts +84 -11
  11. package/client/message-content/MarkdownContent.tsx +128 -0
  12. package/client/message-content/markdown.test.ts +48 -0
  13. package/client/message-content/markdown.ts +247 -0
  14. package/client/persistence/idb-store.test.ts +139 -0
  15. package/client/persistence/idb-store.ts +43 -21
  16. package/client/runtime/index.ts +1 -1
  17. package/client/segments.test.ts +16 -0
  18. package/client/segments.ts +39 -0
  19. package/client/types.ts +5 -5
  20. package/client/websocket/hooks.test.ts +21 -0
  21. package/client/websocket/hooks.ts +56 -27
  22. package/client/websocket/index.ts +6 -1
  23. package/client/websocket/manager.test.ts +349 -0
  24. package/client/websocket/manager.ts +245 -54
  25. package/client/websocket/remote-settings.ts +25 -3
  26. package/client/websocket/types.ts +5 -0
  27. package/client/workroom/WorkroomRunsPage.tsx +355 -0
  28. package/client/workroom/registerWorkroomConsole.test.ts +26 -0
  29. package/client/workroom/registerWorkroomConsole.ts +17 -0
  30. package/dist/agent-stream.d.ts +17 -0
  31. package/dist/agent-stream.d.ts.map +1 -0
  32. package/dist/agent-stream.js +73 -0
  33. package/dist/agent-stream.js.map +1 -0
  34. package/dist/bootstrap/loadConsoleEntries.d.ts +10 -1
  35. package/dist/bootstrap/loadConsoleEntries.d.ts.map +1 -1
  36. package/dist/bootstrap/loadConsoleEntries.js +37 -2
  37. package/dist/bootstrap/loadConsoleEntries.js.map +1 -1
  38. package/dist/console-events.d.ts +7 -0
  39. package/dist/console-events.d.ts.map +1 -0
  40. package/dist/console-events.js +26 -0
  41. package/dist/console-events.js.map +1 -0
  42. package/dist/console-utils/remoteApi.d.ts +2 -0
  43. package/dist/console-utils/remoteApi.d.ts.map +1 -1
  44. package/dist/console-utils/remoteApi.js +46 -2
  45. package/dist/console-utils/remoteApi.js.map +1 -1
  46. package/dist/index.d.ts +9 -3
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +12 -3
  49. package/dist/index.js.map +1 -1
  50. package/dist/mediaSrc.d.ts +1 -1
  51. package/dist/mediaSrc.d.ts.map +1 -1
  52. package/dist/mediaSrc.js +91 -11
  53. package/dist/mediaSrc.js.map +1 -1
  54. package/dist/message-content/MarkdownContent.d.ts +11 -0
  55. package/dist/message-content/MarkdownContent.d.ts.map +1 -0
  56. package/dist/message-content/MarkdownContent.js +68 -0
  57. package/dist/message-content/MarkdownContent.js.map +1 -0
  58. package/dist/message-content/markdown.d.ts +47 -0
  59. package/dist/message-content/markdown.d.ts.map +1 -0
  60. package/dist/message-content/markdown.js +219 -0
  61. package/dist/message-content/markdown.js.map +1 -0
  62. package/dist/persistence/idb-store.d.ts +5 -2
  63. package/dist/persistence/idb-store.d.ts.map +1 -1
  64. package/dist/persistence/idb-store.js +31 -20
  65. package/dist/persistence/idb-store.js.map +1 -1
  66. package/dist/runtime/index.d.ts +1 -1
  67. package/dist/runtime/index.d.ts.map +1 -1
  68. package/dist/segments.d.ts +9 -0
  69. package/dist/segments.d.ts.map +1 -0
  70. package/dist/segments.js +35 -0
  71. package/dist/segments.js.map +1 -0
  72. package/dist/types.d.ts +4 -3
  73. package/dist/types.d.ts.map +1 -1
  74. package/dist/websocket/hooks.d.ts +9 -0
  75. package/dist/websocket/hooks.d.ts.map +1 -1
  76. package/dist/websocket/hooks.js +52 -31
  77. package/dist/websocket/hooks.js.map +1 -1
  78. package/dist/websocket/index.d.ts +1 -1
  79. package/dist/websocket/index.d.ts.map +1 -1
  80. package/dist/websocket/index.js +1 -1
  81. package/dist/websocket/index.js.map +1 -1
  82. package/dist/websocket/manager.d.ts +20 -2
  83. package/dist/websocket/manager.d.ts.map +1 -1
  84. package/dist/websocket/manager.js +222 -44
  85. package/dist/websocket/manager.js.map +1 -1
  86. package/dist/websocket/remote-settings.d.ts.map +1 -1
  87. package/dist/websocket/remote-settings.js +27 -3
  88. package/dist/websocket/remote-settings.js.map +1 -1
  89. package/dist/websocket/types.d.ts +4 -0
  90. package/dist/websocket/types.d.ts.map +1 -1
  91. package/dist/websocket/types.js.map +1 -1
  92. package/dist/workroom/WorkroomRunsPage.d.ts +2 -0
  93. package/dist/workroom/WorkroomRunsPage.d.ts.map +1 -0
  94. package/dist/workroom/WorkroomRunsPage.js +111 -0
  95. package/dist/workroom/WorkroomRunsPage.js.map +1 -0
  96. package/dist/workroom/registerWorkroomConsole.d.ts +4 -0
  97. package/dist/workroom/registerWorkroomConsole.d.ts.map +1 -0
  98. package/dist/workroom/registerWorkroomConsole.js +16 -0
  99. package/dist/workroom/registerWorkroomConsole.js.map +1 -0
  100. package/package.json +18 -8
  101. package/dist/bootstrap/loadConsoleEntries.test.d.ts +0 -2
  102. package/dist/bootstrap/loadConsoleEntries.test.d.ts.map +0 -1
  103. package/dist/bootstrap/loadConsoleEntries.test.js +0 -27
  104. package/dist/bootstrap/loadConsoleEntries.test.js.map +0 -1
@@ -0,0 +1,128 @@
1
+ import { Fragment, useMemo, useState, type ReactNode } from 'react';
2
+ import {
3
+ highlightCodeLine,
4
+ parseMarkdown,
5
+ type MarkdownInline,
6
+ } from './markdown.js';
7
+
8
+ export interface MarkdownContentProps {
9
+ readonly text: string;
10
+ readonly className?: string;
11
+ }
12
+
13
+ function InlineContent({ content }: { readonly content: readonly MarkdownInline[] }) {
14
+ const nodes: ReactNode[] = [];
15
+ content.forEach((token, index) => {
16
+ const key = `${token.type}-${index}`;
17
+ const value = token.value.split('\n').map((line, lineIndex, lines) => (
18
+ <Fragment key={`${key}-line-${lineIndex}`}>
19
+ {line}
20
+ {lineIndex < lines.length - 1 ? <br /> : null}
21
+ </Fragment>
22
+ ));
23
+ if (token.type === 'strong') nodes.push(<strong key={key}>{value}</strong>);
24
+ else if (token.type === 'emphasis') nodes.push(<em key={key}>{value}</em>);
25
+ else if (token.type === 'strike') nodes.push(<del key={key}>{value}</del>);
26
+ else if (token.type === 'code') nodes.push(<code key={key} className="im-inline-code">{token.value}</code>);
27
+ else if (token.type === 'link') nodes.push(
28
+ <a key={key} href={token.href} target={token.href.startsWith('#') ? undefined : '_blank'} rel="noreferrer" className="im-message-link">{value}</a>,
29
+ );
30
+ else nodes.push(<Fragment key={key}>{value}</Fragment>);
31
+ });
32
+ return <>{nodes}</>;
33
+ }
34
+
35
+ export function CodeBlock({ code, language = '', closed = true }: { readonly code: string; readonly language?: string; readonly closed?: boolean }) {
36
+ const [copied, setCopied] = useState(false);
37
+ const [wrapped, setWrapped] = useState(false);
38
+ const [expanded, setExpanded] = useState(false);
39
+ const lines = useMemo(() => code.split('\n'), [code]);
40
+ const isLong = lines.length > 18 || code.length > 1800;
41
+ const visibleLines = isLong && !expanded ? lines.slice(0, 18) : lines;
42
+
43
+ const copy = async () => {
44
+ try {
45
+ await navigator.clipboard.writeText(code);
46
+ setCopied(true);
47
+ window.setTimeout(() => setCopied(false), 1600);
48
+ } catch {
49
+ setCopied(false);
50
+ }
51
+ };
52
+
53
+ return (
54
+ <figure className="zhin-code-block">
55
+ <figcaption className="zhin-code-toolbar">
56
+ <span className="zhin-code-language">{language || 'plain text'}</span>
57
+ {!closed ? <span className="zhin-code-streaming">生成中</span> : null}
58
+ <span className="zhin-code-actions">
59
+ <button type="button" onClick={() => setWrapped((value) => !value)} aria-pressed={wrapped}>{wrapped ? '不折行' : '折行'}</button>
60
+ <button type="button" onClick={() => void copy()}>{copied ? '已复制' : '复制'}</button>
61
+ </span>
62
+ </figcaption>
63
+ <pre className={wrapped ? 'zhin-code-pre zhin-code-pre--wrap' : 'zhin-code-pre'}>
64
+ <code>
65
+ {visibleLines.map((line, lineIndex) => (
66
+ <span className="zhin-code-line" key={`${lineIndex}-${line}`}>
67
+ <span className="zhin-code-line-number" aria-hidden="true">{lineIndex + 1}</span>
68
+ <span className="zhin-code-line-content">
69
+ {highlightCodeLine(line, language).map((token, tokenIndex) => (
70
+ <span key={`${token.kind}-${tokenIndex}`} className={`zhin-code-token zhin-code-token--${token.kind}`}>{token.value}</span>
71
+ ))}
72
+ {'\n'}
73
+ </span>
74
+ </span>
75
+ ))}
76
+ </code>
77
+ </pre>
78
+ {isLong ? (
79
+ <button type="button" className="zhin-code-expand" onClick={() => setExpanded((value) => !value)}>
80
+ {expanded ? '收起代码' : `展开其余 ${lines.length - visibleLines.length} 行`}
81
+ </button>
82
+ ) : null}
83
+ </figure>
84
+ );
85
+ }
86
+
87
+ export function MarkdownContent({ text, className }: MarkdownContentProps) {
88
+ const blocks = useMemo(() => parseMarkdown(text), [text]);
89
+
90
+ return (
91
+ <div className={['im-markdown-body', 'zhin-markdown', className].filter(Boolean).join(' ')}>
92
+ {blocks.map((block, index) => {
93
+ if (block.type === 'heading') {
94
+ const Heading = `h${block.level}` as keyof React.JSX.IntrinsicElements;
95
+ return <Heading key={index} className={`im-markdown-heading im-markdown-heading-${block.level}`}><InlineContent content={block.content} /></Heading>;
96
+ }
97
+ if (block.type === 'paragraph') return <p key={index} className="im-markdown-paragraph"><InlineContent content={block.content} /></p>;
98
+ if (block.type === 'quote') return <blockquote key={index} className="im-markdown-quote"><InlineContent content={block.content} /></blockquote>;
99
+ if (block.type === 'rule') return <hr key={index} className="zhin-markdown-rule" />;
100
+ if (block.type === 'code') return <CodeBlock key={index} code={block.value} language={block.language} closed={block.closed} />;
101
+ if (block.type === 'list') {
102
+ const List = block.ordered ? 'ol' : 'ul';
103
+ return (
104
+ <List key={index} className={`im-markdown-list${block.ordered ? ' im-markdown-list-ordered' : ''}`}>
105
+ {block.items.map((item, itemIndex) => (
106
+ <li key={itemIndex} className={item.checked === undefined ? undefined : 'zhin-markdown-task'}>
107
+ {item.checked === undefined ? null : <input type="checkbox" checked={item.checked} readOnly aria-label={item.checked ? '已完成' : '未完成'} />}
108
+ <InlineContent content={item.content} />
109
+ </li>
110
+ ))}
111
+ </List>
112
+ );
113
+ }
114
+ if (block.type === 'table') {
115
+ return (
116
+ <div className="zhin-markdown-table-wrap" key={index}>
117
+ <table className="zhin-markdown-table">
118
+ <thead><tr>{block.header.map((cell, cellIndex) => <th key={cellIndex}><InlineContent content={cell} /></th>)}</tr></thead>
119
+ <tbody>{block.rows.map((row, rowIndex) => <tr key={rowIndex}>{row.map((cell, cellIndex) => <td key={cellIndex}><InlineContent content={cell} /></td>)}</tr>)}</tbody>
120
+ </table>
121
+ </div>
122
+ );
123
+ }
124
+ return null;
125
+ })}
126
+ </div>
127
+ );
128
+ }
@@ -0,0 +1,48 @@
1
+ import { highlightCodeLine, isSafeMarkdownHref, parseMarkdown, parseMarkdownInline } from './markdown.js';
2
+
3
+ describe('message markdown', () => {
4
+ it('parses rich blocks including tables and tasks', () => {
5
+ const blocks = parseMarkdown(`# Result
6
+
7
+ - [x] inspect runtime
8
+ - [ ] publish patch
9
+
10
+ | field | value |
11
+ | --- | --- |
12
+ | status | **ready** |`);
13
+
14
+ expect(blocks.map((block) => block.type)).toEqual(['heading', 'list', 'table']);
15
+ expect(blocks[1]).toMatchObject({ type: 'list', items: [{ checked: true }, { checked: false }] });
16
+ });
17
+
18
+ it('keeps incomplete streaming fences renderable', () => {
19
+ expect(parseMarkdown('```ts\nconst ready = true')).toEqual([
20
+ { type: 'code', language: 'ts', value: 'const ready = true', closed: false },
21
+ ]);
22
+ });
23
+
24
+ it('rejects unsafe markdown links without emitting active links', () => {
25
+ expect(isSafeMarkdownHref('javascript:alert(1)')).toBe(false);
26
+ expect(isSafeMarkdownHref('https://zhin.dev/docs')).toBe(true);
27
+ expect(parseMarkdownInline('[run](javascript:alert(1))')).toEqual([
28
+ { type: 'text', value: '[run](javascript:alert(1))' },
29
+ ]);
30
+ });
31
+
32
+ it('treats repeated unmatched link openers as plain text', () => {
33
+ const value = '['.repeat(20_000);
34
+ expect(parseMarkdownInline(value)).toEqual([{ type: 'text', value }]);
35
+ });
36
+
37
+ it('tokenizes common code without producing html', () => {
38
+ expect(highlightCodeLine('const answer = "<safe>" // note', 'ts')).toEqual([
39
+ { kind: 'keyword', value: 'const' },
40
+ { kind: 'plain', value: ' ' },
41
+ { kind: 'plain', value: 'answer' },
42
+ { kind: 'plain', value: ' = ' },
43
+ { kind: 'string', value: '"<safe>"' },
44
+ { kind: 'plain', value: ' ' },
45
+ { kind: 'comment', value: '// note' },
46
+ ]);
47
+ });
48
+ });
@@ -0,0 +1,247 @@
1
+ export type MarkdownInline =
2
+ | { readonly type: 'text'; readonly value: string }
3
+ | { readonly type: 'strong' | 'emphasis' | 'strike' | 'code'; readonly value: string }
4
+ | { readonly type: 'link'; readonly value: string; readonly href: string };
5
+
6
+ export type MarkdownBlock =
7
+ | { readonly type: 'heading'; readonly level: number; readonly content: MarkdownInline[] }
8
+ | { readonly type: 'paragraph' | 'quote'; readonly content: MarkdownInline[] }
9
+ | { readonly type: 'list'; readonly ordered: boolean; readonly items: ReadonlyArray<{ readonly content: MarkdownInline[]; readonly checked?: boolean }> }
10
+ | { readonly type: 'code'; readonly language: string; readonly value: string; readonly closed: boolean }
11
+ | { readonly type: 'table'; readonly header: ReadonlyArray<MarkdownInline[]>; readonly rows: ReadonlyArray<ReadonlyArray<MarkdownInline[]>> }
12
+ | { readonly type: 'rule' };
13
+
14
+ export type CodeTokenKind = 'plain' | 'comment' | 'string' | 'number' | 'keyword' | 'literal';
15
+
16
+ export interface CodeToken {
17
+ readonly kind: CodeTokenKind;
18
+ readonly value: string;
19
+ }
20
+
21
+ // Excluding another opening bracket from link labels prevents the regexp
22
+ // engine from rescanning an attacker-controlled run of `[` characters.
23
+ const INLINE_PATTERN = /(`[^`\n]+`)|(\*\*[^*\n]+\*\*|__[^_\n]+__)|(~~[^~\n]+~~)|(\*[^*\n]+\*|_[^_\n]+_)|(\[[^\[\]\n]+\]\([^\s()]+(?:\s+"[^"\n]*")?\))|(https?:\/\/[^\s<>()]+)/g;
24
+ const TABLE_DIVIDER = /^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;
25
+
26
+ export function isSafeMarkdownHref(href: string): boolean {
27
+ const value = href.trim();
28
+ if (!value) return false;
29
+ if (/^(https?:|mailto:)/i.test(value)) return true;
30
+ return /^(\/|#|\.\/|\.\.\/)/.test(value);
31
+ }
32
+
33
+ export function parseMarkdownInline(value: string): MarkdownInline[] {
34
+ const tokens: MarkdownInline[] = [];
35
+ let cursor = 0;
36
+ let match: RegExpExecArray | null;
37
+ INLINE_PATTERN.lastIndex = 0;
38
+
39
+ while ((match = INLINE_PATTERN.exec(value)) !== null) {
40
+ if (match.index > cursor) tokens.push({ type: 'text', value: value.slice(cursor, match.index) });
41
+ const raw = match[0];
42
+ if (match[1]) {
43
+ tokens.push({ type: 'code', value: raw.slice(1, -1) });
44
+ } else if (match[2]) {
45
+ tokens.push({ type: 'strong', value: raw.slice(2, -2) });
46
+ } else if (match[3]) {
47
+ tokens.push({ type: 'strike', value: raw.slice(2, -2) });
48
+ } else if (match[4]) {
49
+ tokens.push({ type: 'emphasis', value: raw.slice(1, -1) });
50
+ } else if (match[5]) {
51
+ const parsed = raw.match(/^\[([^\[\]]+)\]\(([^\s()]+)(?:\s+"[^"\n]*")?\)$/);
52
+ if (parsed && isSafeMarkdownHref(parsed[2])) {
53
+ tokens.push({ type: 'link', value: parsed[1], href: parsed[2] });
54
+ } else {
55
+ tokens.push({ type: 'text', value: raw });
56
+ }
57
+ } else if (match[6]) {
58
+ tokens.push({ type: 'link', value: raw, href: raw });
59
+ }
60
+ cursor = INLINE_PATTERN.lastIndex;
61
+ }
62
+
63
+ if (cursor < value.length) tokens.push({ type: 'text', value: value.slice(cursor) });
64
+ const merged: MarkdownInline[] = [];
65
+ for (const token of tokens) {
66
+ const previous = merged.at(-1);
67
+ if (token.type === 'text' && previous?.type === 'text') {
68
+ merged[merged.length - 1] = { type: 'text', value: previous.value + token.value };
69
+ } else {
70
+ merged.push(token);
71
+ }
72
+ }
73
+ return merged.length > 0 ? merged : [{ type: 'text', value }];
74
+ }
75
+
76
+ function splitTableRow(line: string): string[] {
77
+ return line
78
+ .trim()
79
+ .replace(/^\|/, '')
80
+ .replace(/\|$/, '')
81
+ .split(/(?<!\\)\|/)
82
+ .map((cell) => cell.trim().replace(/\\\|/g, '|'));
83
+ }
84
+
85
+ function startsBlock(lines: readonly string[], index: number): boolean {
86
+ const line = lines[index] ?? '';
87
+ return /^(?:```|~~~|#{1,6}\s+|>\s?|\s*(?:[-+*]|\d+[.)])\s+|\s*(?:-{3,}|\*{3,}|_{3,})\s*$)/.test(line)
88
+ || (line.includes('|') && TABLE_DIVIDER.test(lines[index + 1] ?? ''));
89
+ }
90
+
91
+ export function parseMarkdown(value: string): MarkdownBlock[] {
92
+ const lines = value.replace(/\r\n?/g, '\n').split('\n');
93
+ const blocks: MarkdownBlock[] = [];
94
+ let index = 0;
95
+
96
+ while (index < lines.length) {
97
+ const line = lines[index];
98
+ if (!line.trim()) {
99
+ index += 1;
100
+ continue;
101
+ }
102
+
103
+ const fence = line.match(/^\s*(```|~~~)\s*([^\s`]*)?.*$/);
104
+ if (fence) {
105
+ const marker = fence[1];
106
+ const language = (fence[2] ?? '').toLowerCase();
107
+ const code: string[] = [];
108
+ let closed = false;
109
+ index += 1;
110
+ while (index < lines.length) {
111
+ if (lines[index].trim() === marker) {
112
+ closed = true;
113
+ index += 1;
114
+ break;
115
+ }
116
+ code.push(lines[index]);
117
+ index += 1;
118
+ }
119
+ blocks.push({ type: 'code', language, value: code.join('\n'), closed });
120
+ continue;
121
+ }
122
+
123
+ const heading = line.match(/^(#{1,6})\s+(.+)$/);
124
+ if (heading) {
125
+ blocks.push({ type: 'heading', level: heading[1].length, content: parseMarkdownInline(heading[2]) });
126
+ index += 1;
127
+ continue;
128
+ }
129
+
130
+ if (/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
131
+ blocks.push({ type: 'rule' });
132
+ index += 1;
133
+ continue;
134
+ }
135
+
136
+ if (/^>\s?/.test(line)) {
137
+ const quoted: string[] = [];
138
+ while (index < lines.length && /^>\s?/.test(lines[index])) {
139
+ quoted.push(lines[index].replace(/^>\s?/, ''));
140
+ index += 1;
141
+ }
142
+ blocks.push({ type: 'quote', content: parseMarkdownInline(quoted.join('\n')) });
143
+ continue;
144
+ }
145
+
146
+ const listMatch = line.match(/^\s*([-+*]|\d+[.)])\s+(.+)$/);
147
+ if (listMatch) {
148
+ const ordered = /^\d/.test(listMatch[1]);
149
+ const items: Array<{ content: MarkdownInline[]; checked?: boolean }> = [];
150
+ while (index < lines.length) {
151
+ const item = lines[index].match(/^\s*([-+*]|\d+[.)])\s+(.+)$/);
152
+ if (!item || /^\d/.test(item[1]) !== ordered) break;
153
+ const task = item[2].match(/^\[([ xX])\]\s+(.+)$/);
154
+ items.push({
155
+ content: parseMarkdownInline(task ? task[2] : item[2]),
156
+ ...(task ? { checked: task[1].toLowerCase() === 'x' } : {}),
157
+ });
158
+ index += 1;
159
+ }
160
+ blocks.push({ type: 'list', ordered, items });
161
+ continue;
162
+ }
163
+
164
+ if (line.includes('|') && TABLE_DIVIDER.test(lines[index + 1] ?? '')) {
165
+ const header = splitTableRow(line).map(parseMarkdownInline);
166
+ const rows: MarkdownInline[][][] = [];
167
+ index += 2;
168
+ while (index < lines.length && lines[index].includes('|') && lines[index].trim()) {
169
+ rows.push(splitTableRow(lines[index]).map(parseMarkdownInline));
170
+ index += 1;
171
+ }
172
+ blocks.push({ type: 'table', header, rows });
173
+ continue;
174
+ }
175
+
176
+ const paragraph = [line];
177
+ index += 1;
178
+ while (index < lines.length && lines[index].trim() && !startsBlock(lines, index)) {
179
+ paragraph.push(lines[index]);
180
+ index += 1;
181
+ }
182
+ blocks.push({ type: 'paragraph', content: parseMarkdownInline(paragraph.join('\n')) });
183
+ }
184
+
185
+ return blocks;
186
+ }
187
+
188
+ const KEYWORDS: Record<string, ReadonlySet<string>> = {
189
+ javascript: new Set(['async', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'default', 'delete', 'do', 'else', 'export', 'extends', 'finally', 'for', 'from', 'function', 'if', 'import', 'in', 'instanceof', 'let', 'new', 'of', 'return', 'static', 'switch', 'throw', 'try', 'typeof', 'var', 'void', 'while', 'yield']),
190
+ typescript: new Set(['abstract', 'any', 'as', 'asserts', 'async', 'await', 'boolean', 'break', 'case', 'catch', 'class', 'const', 'continue', 'declare', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'finally', 'for', 'from', 'function', 'if', 'implements', 'import', 'in', 'infer', 'instanceof', 'interface', 'keyof', 'let', 'namespace', 'never', 'new', 'number', 'object', 'of', 'readonly', 'return', 'satisfies', 'static', 'string', 'switch', 'symbol', 'throw', 'try', 'type', 'typeof', 'undefined', 'unknown', 'var', 'void', 'while', 'yield']),
191
+ python: new Set(['and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']),
192
+ shell: new Set(['case', 'do', 'done', 'elif', 'else', 'esac', 'export', 'fi', 'for', 'function', 'if', 'in', 'local', 'then', 'while']),
193
+ css: new Set(['@import', '@media', '@supports', 'and', 'important', 'not', 'only']),
194
+ };
195
+
196
+ const LANGUAGE_ALIASES: Record<string, string> = {
197
+ js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript',
198
+ ts: 'typescript', tsx: 'typescript', mts: 'typescript', cts: 'typescript',
199
+ py: 'python', bash: 'shell', sh: 'shell', zsh: 'shell', jsonc: 'json',
200
+ };
201
+
202
+ export function highlightCodeLine(line: string, language = ''): CodeToken[] {
203
+ const normalized = LANGUAGE_ALIASES[language] ?? language;
204
+ const keywords = KEYWORDS[normalized] ?? KEYWORDS.javascript;
205
+ const tokens: CodeToken[] = [];
206
+ let index = 0;
207
+
208
+ const push = (kind: CodeTokenKind, value: string) => {
209
+ if (value) tokens.push({ kind, value });
210
+ };
211
+
212
+ while (index < line.length) {
213
+ const rest = line.slice(index);
214
+ const comment = normalized === 'python' || normalized === 'shell'
215
+ ? rest.match(/^#.*/)
216
+ : rest.match(/^\/\/.*|^\/\*.*?\*\//);
217
+ if (comment) {
218
+ push('comment', comment[0]);
219
+ index += comment[0].length;
220
+ continue;
221
+ }
222
+ const string = rest.match(/^(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/);
223
+ if (string) {
224
+ push('string', string[0]);
225
+ index += string[0].length;
226
+ continue;
227
+ }
228
+ const number = rest.match(/^(?:0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)/i);
229
+ if (number) {
230
+ push('number', number[0]);
231
+ index += number[0].length;
232
+ continue;
233
+ }
234
+ const word = rest.match(/^[A-Za-z_$@][\w$-]*/);
235
+ if (word) {
236
+ const literal = /^(?:true|false|null|undefined|None|True|False)$/.test(word[0]);
237
+ push(literal ? 'literal' : keywords.has(word[0]) ? 'keyword' : 'plain', word[0]);
238
+ index += word[0].length;
239
+ continue;
240
+ }
241
+ const plain = rest.match(/^[^A-Za-z_$@'"`\d/#]+/) ?? rest.match(/^./);
242
+ push('plain', plain?.[0] ?? '');
243
+ index += plain?.[0].length ?? 1;
244
+ }
245
+
246
+ return tokens;
247
+ }
@@ -0,0 +1,139 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ import { applyConsoleEvent, idbListInbox } from "./idb-store.js";
4
+
5
+ /**
6
+ * 最小内存 IndexedDB stub:仅实现 idb-store 用到的 open/upgrade/getAll/put 语义,
7
+ * 含版本检查(低版本 open 触发 VersionError)。
8
+ */
9
+ type StoreData = Map<string, Record<string, unknown>>;
10
+ interface DbData {
11
+ version: number;
12
+ stores: Map<string, StoreData>;
13
+ }
14
+
15
+ function createFakeIndexedDB() {
16
+ const dbs = new Map<string, DbData>();
17
+
18
+ function makeRequest<T>(run: (req: IDBRequest<T>) => void): IDBRequest<T> {
19
+ const req = {
20
+ result: undefined as T,
21
+ error: null as unknown,
22
+ onsuccess: null as (() => void) | null,
23
+ onerror: null as (() => void) | null,
24
+ onupgradeneeded: null as (() => void) | null,
25
+ } as unknown as IDBRequest<T>;
26
+ queueMicrotask(() => run(req));
27
+ return req;
28
+ }
29
+
30
+ function makeDb(data: DbData): IDBDatabase {
31
+ return {
32
+ objectStoreNames: {
33
+ contains: (name: string) => data.stores.has(name),
34
+ },
35
+ createObjectStore: (name: string) => {
36
+ data.stores.set(name, new Map());
37
+ },
38
+ transaction: (name: string) => {
39
+ const store = data.stores.get(name);
40
+ const tx = {
41
+ oncomplete: null as (() => void) | null,
42
+ onerror: null as (() => void) | null,
43
+ error: null as unknown,
44
+ objectStore: () => ({
45
+ getAll: () =>
46
+ makeRequest<Record<string, unknown>[]>((req) => {
47
+ (req as { result: unknown }).result = [...(store?.values() ?? [])];
48
+ req.onsuccess?.();
49
+ }),
50
+ put: (record: Record<string, unknown>) => {
51
+ store?.set(String(record.id), record);
52
+ queueMicrotask(() => tx.oncomplete?.());
53
+ },
54
+ }),
55
+ };
56
+ return tx;
57
+ },
58
+ close: () => undefined,
59
+ } as unknown as IDBDatabase;
60
+ }
61
+
62
+ return {
63
+ open(name: string, version = 1) {
64
+ return makeRequest<IDBDatabase>((req) => {
65
+ let data = dbs.get(name);
66
+ if (data && data.version > version) {
67
+ (req as { error: unknown }).error = new Error("VersionError");
68
+ req.onerror?.();
69
+ return;
70
+ }
71
+ const upgrading = !data || data.version < version;
72
+ if (!data) {
73
+ data = { version, stores: new Map() };
74
+ dbs.set(name, data);
75
+ }
76
+ data.version = version;
77
+ (req as { result: unknown }).result = makeDb(data);
78
+ if (upgrading) req.onupgradeneeded?.();
79
+ req.onsuccess?.();
80
+ });
81
+ },
82
+ };
83
+ }
84
+
85
+ const PUSH = {
86
+ type: "message.receive",
87
+ data: { adapter: "icqq", endpointKey: "bot-1", channelId: "1001" },
88
+ };
89
+
90
+ describe("applyConsoleEvent inbox record ids", () => {
91
+ beforeEach(() => {
92
+ vi.stubGlobal("indexedDB", createFakeIndexedDB());
93
+ });
94
+
95
+ afterEach(() => {
96
+ vi.unstubAllGlobals();
97
+ vi.restoreAllMocks();
98
+ });
99
+
100
+ it("keeps two events of the same conversation within one millisecond (no key overwrite)", async () => {
101
+ // 回归:旧主键 `${adapter}:${endpointKey}:${type}:${Date.now()}` 在同毫秒会互相覆盖。
102
+ vi.spyOn(Date, "now").mockReturnValue(1700000000000);
103
+ await applyConsoleEvent(PUSH);
104
+ await applyConsoleEvent(PUSH);
105
+
106
+ const rows = await idbListInbox("icqq", "bot-1", "message");
107
+ expect(rows).toHaveLength(2);
108
+ expect(new Set(rows.map((r) => r.id)).size).toBe(2);
109
+ });
110
+
111
+ it('deduplicates the same resumable event across history and live delivery', async () => {
112
+ const event = { ...PUSH, runtimeId: 'runtime-a', eventId: 7, timestamp: 1700000000000 };
113
+ await applyConsoleEvent(event);
114
+ await applyConsoleEvent(event);
115
+
116
+ const rows = await idbListInbox('icqq', 'bot-1', 'message');
117
+ expect(rows).toHaveLength(1);
118
+ expect(rows[0]?.id).toBe('runtime-a:7');
119
+ expect(rows[0]?.updatedAt).toBe(1700000000000);
120
+ });
121
+
122
+ it("reads legacy records that only carry endpointKey (camelCase)", async () => {
123
+ // 旧版(DB v1 时代)记录只有 endpointKey 字段,升级后仍需能被列出
124
+ const { idbPutInbox } = await import("./idb-store.js");
125
+ const legacy = {
126
+ id: "icqq:bot-1:message:1700000000000:legacy",
127
+ adapter: "icqq",
128
+ endpointKey: "bot-1",
129
+ kind: "message",
130
+ payload: {},
131
+ updatedAt: 1700000000000,
132
+ };
133
+ await idbPutInbox(legacy as unknown as Parameters<typeof idbPutInbox>[0]);
134
+
135
+ const rows = await idbListInbox("icqq", "bot-1", "message");
136
+ expect(rows).toHaveLength(1);
137
+ expect(rows[0].id).toBe(legacy.id);
138
+ });
139
+ });
@@ -1,12 +1,16 @@
1
+ import { parseConsoleInboxEvent } from "@zhin.js/console-protocol";
2
+
1
3
  const DB_NAME = "zhin-console";
2
- const DB_VERSION = 1;
4
+ const DB_VERSION = 2;
3
5
  const STORE_INBOX = "inbox";
4
6
  const STORE_PENDING = "pending";
5
7
 
8
+ let inboxEventSeq = 0;
9
+
6
10
  export type InboxRecord = {
7
11
  id: string;
8
12
  adapter: string;
9
- botId: string;
13
+ endpoint_id: string;
10
14
  kind: "message" | "request" | "notice";
11
15
  payload: unknown;
12
16
  updatedAt: number;
@@ -42,7 +46,7 @@ export async function idbPutInbox(record: InboxRecord): Promise<void> {
42
46
 
43
47
  export async function idbListInbox(
44
48
  adapter: string,
45
- botId: string,
49
+ endpoint_id: string,
46
50
  kind: InboxRecord["kind"],
47
51
  ): Promise<InboxRecord[]> {
48
52
  const db = await openDb();
@@ -53,24 +57,42 @@ export async function idbListInbox(
53
57
  req.onerror = () => reject(req.error);
54
58
  });
55
59
  db.close();
56
- return all.filter((r) => r.adapter === adapter && r.botId === botId && r.kind === kind);
60
+ return all.filter(
61
+ (r) =>
62
+ r.adapter === adapter &&
63
+ (r.endpoint_id === endpoint_id ||
64
+ (r as { endpointKey?: string }).endpointKey === endpoint_id) &&
65
+ r.kind === kind,
66
+ );
57
67
  }
58
68
 
59
- export async function applyConsoleEvent(event: { type: string; data?: unknown }): Promise<void> {
60
- const t = event.type;
61
- if (t === "bot:message" || t === "bot:request" || t === "bot:notice") {
62
- const data = event.data as Record<string, unknown> | undefined;
63
- if (!data) return;
64
- const adapter = String(data.adapter ?? "");
65
- const botId = String(data.botId ?? data.bot ?? "");
66
- const id = `${adapter}:${botId}:${t}:${Date.now()}`;
67
- await idbPutInbox({
68
- id,
69
- adapter,
70
- botId,
71
- kind: t === "bot:message" ? "message" : t === "bot:request" ? "request" : "notice",
72
- payload: data,
73
- updatedAt: Date.now(),
74
- });
75
- }
69
+ export async function applyConsoleEvent(event: {
70
+ type: string;
71
+ data?: unknown;
72
+ runtimeId?: string;
73
+ eventId?: number;
74
+ timestamp?: number;
75
+ }): Promise<void> {
76
+ const parsed = parseConsoleInboxEvent(event);
77
+ if (!parsed) return;
78
+ const updatedAt = typeof event.timestamp === 'number' && Number.isFinite(event.timestamp)
79
+ ? event.timestamp
80
+ : Date.now();
81
+ const resumableId = typeof event.runtimeId === 'string'
82
+ && event.runtimeId
83
+ && Number.isSafeInteger(event.eventId)
84
+ && (event.eventId ?? 0) > 0
85
+ ? `${event.runtimeId}:${event.eventId}`
86
+ : null;
87
+ await idbPutInbox({
88
+ // Resumable Host events are idempotent across history/live redelivery.
89
+ // Legacy/unsequenced sources retain collision-safe append ids.
90
+ id: resumableId
91
+ ?? `${parsed.adapter}:${parsed.endpointKey}:${parsed.type}:${updatedAt}:${inboxEventSeq++}:${Math.random().toString(36).slice(2, 8)}`,
92
+ adapter: parsed.adapter,
93
+ endpoint_id: parsed.endpointKey,
94
+ kind: parsed.kind,
95
+ payload: parsed.payload,
96
+ updatedAt,
97
+ });
76
98
  }
@@ -1,4 +1,4 @@
1
- import type { RuntimeEnv } from "@zhin.js/console-types";
1
+ import type { RuntimeEnv } from "@zhin.js/contract";
2
2
 
3
3
  let runtimeEnvFn: (() => RuntimeEnv) | null = null;
4
4
 
@@ -0,0 +1,16 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { segmentsForAgentPanel, segmentsForImDelivery } from '../client/segments.js';
3
+
4
+ describe('console segmentsForImDelivery', () => {
5
+ it('inbox view strips AI-only segments', () => {
6
+ const full = [
7
+ { type: 'thinking', data: { text: 'plan' } },
8
+ { type: 'text', data: { text: 'hi' } },
9
+ { type: 'tool_call', data: { name: 'bash' } },
10
+ ];
11
+ expect(segmentsForImDelivery(full)).toEqual([
12
+ { type: 'text', data: { text: 'hi' } },
13
+ ]);
14
+ expect(segmentsForAgentPanel(full)).toEqual(full);
15
+ });
16
+ });