cortico-world-self-awareness 0.5.0 → 0.6.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ **能自己测接口了,状态灯也不再误导。**
6
+
7
+ - **时间线页面加了「测接口」按钮**:点一下发一句「在吗」,几秒内告诉你通不通、多快、用的哪个模型。
8
+ 失败会说清是 401、连不上、还是超时。
9
+ **不写文件、不占今天的次数、不动 `lastError`**——手点失败是查询行为,不该让状态灯一直红着。
10
+ 10 秒内只允许一次,防狂点烧额度。
11
+ - **状态灯改成四态**:`在跑` / `睡着了` / `出错` / `已关闭`。
12
+ 以前「她睡了」和「她挂了」在界面上是同一个样子——**这才是会让人怀疑接口的原因**。
13
+ 睡着用 `loading` 而不是 `error`:不是故障。
14
+ - 新增开关**「启动时测一次接口」**(默认开):重启顺手 ping 一下,配错了立刻在灯上看到,
15
+ 不用等她想第一件事。代价是每次重启多约 30–100 token。
16
+ - 错误信息带上底层原因:`fetch failed` → `fetch failed(ECONNREFUSED:连不上这个地址)`。
17
+ - 加固:记忆核心目录探测现在同级和内部都试(`../memory-core` 与 `./memory-core`)。
18
+ 这一条**不是修 bug**——原来的路径是对的,只是多一条回退。
19
+
20
+ 测试 45–54(10 项),共 54 项。
21
+
22
+ ## 0.5.0
3
23
  ## 0.5.0
4
24
 
5
25
  **她自己定下次什么时候想、想什么。**
package/README.md CHANGED
@@ -118,7 +118,8 @@
118
118
  - 按时间倒序,每条标:时间、模式(回看 / 走神 / 打算 / 琢磨)、重要度点
119
119
  - 接着上次想下去的会单独标出来
120
120
  - 底部是「她对自己的看法」——几条碎念攒够重要度后自动收成的一句
121
- - 顶部:今天几次、花了多少 token、下次什么时候、现在是跑着还是关着
121
+ - 顶部:今天几次、花了多少 token、下次什么时候、现在是**在跑 / 睡着了 / 出错 / 已关闭**
122
+ - 一个「测接口」按钮:点一下就知道模型配得对不对,不用等她想第一件事
122
123
 
123
124
  只绑 `127.0.0.1`,不对外,也没有写操作。
124
125
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-self-awareness",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "桌宠自己的内在时间线:没人说话的时候她也在想事情——想起旧事、走神、反复琢磨一件没想明白的。\n\n它只负责「想」:想到的写在本机一个文件里,不发消息,也不占对话的 token。配合「记忆核心」使用——你开口时,记忆核心会挑一条带进上下文,标明时间,并说清那不一定是你现在的想法。单独装也能跑,但那是一本她自己不会翻的日记。\n\n模型自选,OpenAI 兼容接口就行;默认一天最多 12 次,一次几分钱。\n\nQQ 交流群:745879632",
6
6
  "keywords": [
package/src/config.ts CHANGED
@@ -24,6 +24,8 @@ export interface SelfAwarenessConfig {
24
24
  temperature: number;
25
25
  /** 一句话交代她是谁,写进思考的上下文。留空就只按记忆来。 */
26
26
  personaNote: string;
27
+ /** 启动时 ping 一次接口,配完立刻知道对不对 */
28
+ probeOnStart: boolean;
27
29
  /** 本地时间线页面 */
28
30
  siteEnabled: boolean;
29
31
  sitePort: number;
@@ -54,6 +56,7 @@ export const SELF_AWARENESS_DEFAULTS: SelfAwarenessConfig = {
54
56
  maxOutputTokens: 220,
55
57
  temperature: 0.95,
56
58
  personaNote: '',
59
+ probeOnStart: true,
57
60
  siteEnabled: true,
58
61
  sitePort: 7802,
59
62
  memoryCoreDir: '',
@@ -169,6 +172,12 @@ const RAW_GROUP: ConfigGroup = {
169
172
  default: '',
170
173
  'x-hot': true,
171
174
  } as never,
175
+ 'worlds.self-awareness.probeOnStart': {
176
+ type: 'boolean',
177
+ title: '启动时测一次接口',
178
+ description: 'World 重启时顺手 ping 一下模型,配错了立刻能在状态灯上看到,不用等她想第一件事。一次约 30-100 token。',
179
+ default: true,
180
+ },
172
181
  'worlds.self-awareness.siteEnabled': {
173
182
  type: 'boolean',
174
183
  title: '本地时间线页面',
@@ -209,6 +218,7 @@ const SETTINGS_ORDER = [
209
218
  'worlds.self-awareness.maxOutputTokens',
210
219
  'worlds.self-awareness.temperature',
211
220
  'worlds.self-awareness.personaNote',
221
+ 'worlds.self-awareness.probeOnStart',
212
222
  'worlds.self-awareness.siteEnabled',
213
223
  'worlds.self-awareness.sitePort',
214
224
  'worlds.self-awareness.memoryCoreDir',
package/src/site.ts CHANGED
@@ -1,123 +1,165 @@
1
- /**
2
- * 她的时间线:一个只读的本地页面。
3
- *
4
- * 只绑 127.0.0.1,不对外。没有写操作,没有令牌——它只把 thoughts.jsonl
5
- * 和 reflections.jsonl 摊开给人看。
6
- */
7
- import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
8
- import { readFileSync } from 'node:fs';
9
- import { fileURLToPath } from 'node:url';
10
-
11
- const PAGE_FILE = fileURLToPath(new URL('../webui/index.html', import.meta.url));
12
- const HOST = '127.0.0.1';
13
- /** 端口被占就往后找几个,别让插件因为端口冲突起不来。 */
14
- const PORT_TRIES = 12;
15
-
16
- export interface SiteHooks {
17
- data(): unknown;
18
- }
19
-
20
- export class ThoughtSite {
21
- private server: Server | null = null;
22
- private listening = 0;
23
- private readonly hooks: SiteHooks;
24
-
25
- constructor(hooks: SiteHooks) {
26
- this.hooks = hooks;
27
- }
28
-
29
- get port(): number {
30
- return this.listening;
31
- }
32
-
33
- get origin(): string | null {
34
- return this.listening ? `http://${HOST}:${this.listening}` : null;
35
- }
36
-
37
- async start(preferred: number): Promise<string | null> {
38
- if (this.server) return this.origin;
39
- const base = Math.max(1024, Math.min(65_535, Number(preferred) || 7802));
40
- for (let i = 0; i < PORT_TRIES; i += 1) {
41
- const port = base + i;
42
- const ok = await this.tryListen(port);
43
- if (ok) {
44
- this.listening = port;
45
- return this.origin;
46
- }
47
- }
48
- return null;
49
- }
50
-
51
- private tryListen(port: number): Promise<boolean> {
52
- return new Promise((resolve) => {
53
- const server = createServer((req, rsp) => this.handle(req, rsp));
54
- const onError = () => {
55
- server.removeListener('listening', onListening);
56
- server.close();
57
- resolve(false);
58
- };
59
- const onListening = () => {
60
- server.removeListener('error', onError);
61
- this.server = server;
62
- resolve(true);
63
- };
64
- server.once('error', onError);
65
- server.once('listening', onListening);
66
- try {
67
- server.listen(port, HOST);
68
- } catch {
69
- resolve(false);
70
- }
71
- });
72
- }
73
-
74
- async stop(): Promise<void> {
75
- const server = this.server;
76
- this.server = null;
77
- this.listening = 0;
78
- if (!server) return;
79
- await new Promise<void>((resolve) => server.close(() => resolve()));
80
- }
81
-
82
- private handle(req: IncomingMessage, rsp: ServerResponse): void {
83
- // 只许本机访问:Host 头不是 127.0.0.1/localhost 的一律拒掉(防 DNS rebinding)
84
- const host = String(req.headers.host ?? '').replace(/:\d+$/, '');
85
- if (host !== HOST && host !== 'localhost') {
86
- rsp.writeHead(403).end('forbidden');
87
- return;
88
- }
89
- const url = new URL(req.url ?? '/', `http://${HOST}`);
90
- if (url.pathname === '/api/data') {
91
- let body = '';
92
- try {
93
- body = JSON.stringify(this.hooks.data());
94
- } catch (error) {
95
- body = JSON.stringify({ error: error instanceof Error ? error.message : String(error) });
96
- }
97
- rsp.writeHead(200, {
98
- 'content-type': 'application/json; charset=utf-8',
99
- 'cache-control': 'no-store',
100
- });
101
- rsp.end(body);
102
- return;
103
- }
104
- if (url.pathname === '/' || url.pathname === '/index.html') {
105
- let html = '';
106
- try {
107
- html = readFileSync(PAGE_FILE, 'utf8');
108
- } catch {
109
- rsp.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
110
- rsp.end('页面文件丢了,重装一下插件。');
111
- return;
112
- }
113
- rsp.writeHead(200, {
114
- 'content-type': 'text/html; charset=utf-8',
115
- 'cache-control': 'no-store',
116
- });
117
- rsp.end(html);
118
- return;
119
- }
120
- rsp.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
121
- rsp.end('not found');
122
- }
123
- }
1
+ /**
2
+ * 她的时间线:一个只读的本地页面。
3
+ *
4
+ * 只绑 127.0.0.1,不对外。没有写操作,没有令牌——它只把 thoughts.jsonl
5
+ * 和 reflections.jsonl 摊开给人看。
6
+ */
7
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
8
+ import { readFileSync } from 'node:fs';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ const PAGE_FILE = fileURLToPath(new URL('../webui/index.html', import.meta.url));
12
+ const HOST = '127.0.0.1';
13
+ /** 端口被占就往后找几个,别让插件因为端口冲突起不来。 */
14
+ const PORT_TRIES = 12;
15
+
16
+ export interface ProbeResult {
17
+ ok: boolean;
18
+ ms: number;
19
+ model?: string;
20
+ error?: string;
21
+ }
22
+
23
+ export interface SiteHooks {
24
+ data(): unknown;
25
+ /** 手点「测接口」时调。不写文件、不占额度。 */
26
+ probe?(): Promise<ProbeResult>;
27
+ }
28
+
29
+ /** 手点测接口的最小间隔:防止狂点把额度烧了。 */
30
+ const PROBE_GAP_MS = 10_000;
31
+
32
+ export class ThoughtSite {
33
+ private server: Server | null = null;
34
+ private listening = 0;
35
+ private lastProbe = 0;
36
+ private readonly hooks: SiteHooks;
37
+
38
+ constructor(hooks: SiteHooks) {
39
+ this.hooks = hooks;
40
+ }
41
+
42
+ get port(): number {
43
+ return this.listening;
44
+ }
45
+
46
+ get origin(): string | null {
47
+ return this.listening ? `http://${HOST}:${this.listening}` : null;
48
+ }
49
+
50
+ async start(preferred: number): Promise<string | null> {
51
+ if (this.server) return this.origin;
52
+ const base = Math.max(1024, Math.min(65_535, Number(preferred) || 7802));
53
+ for (let i = 0; i < PORT_TRIES; i += 1) {
54
+ const port = base + i;
55
+ const ok = await this.tryListen(port);
56
+ if (ok) {
57
+ this.listening = port;
58
+ return this.origin;
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+
64
+ private tryListen(port: number): Promise<boolean> {
65
+ return new Promise((resolve) => {
66
+ const server = createServer((req, rsp) => this.handle(req, rsp));
67
+ const onError = () => {
68
+ server.removeListener('listening', onListening);
69
+ server.close();
70
+ resolve(false);
71
+ };
72
+ const onListening = () => {
73
+ server.removeListener('error', onError);
74
+ this.server = server;
75
+ resolve(true);
76
+ };
77
+ server.once('error', onError);
78
+ server.once('listening', onListening);
79
+ try {
80
+ server.listen(port, HOST);
81
+ } catch {
82
+ resolve(false);
83
+ }
84
+ });
85
+ }
86
+
87
+ async stop(): Promise<void> {
88
+ const server = this.server;
89
+ this.server = null;
90
+ this.listening = 0;
91
+ if (!server) return;
92
+ await new Promise<void>((resolve) => server.close(() => resolve()));
93
+ }
94
+
95
+ private handle(req: IncomingMessage, rsp: ServerResponse): void {
96
+ // 只许本机访问:Host 头不是 127.0.0.1/localhost 的一律拒掉(防 DNS rebinding)
97
+ const host = String(req.headers.host ?? '').replace(/:\d+$/, '');
98
+ if (host !== HOST && host !== 'localhost') {
99
+ rsp.writeHead(403).end('forbidden');
100
+ return;
101
+ }
102
+ const url = new URL(req.url ?? '/', `http://${HOST}`);
103
+ if (url.pathname === '/api/probe') {
104
+ if (req.method !== 'POST') {
105
+ rsp.writeHead(405, { allow: 'POST' }).end('只接受 POST');
106
+ return;
107
+ }
108
+ const now = Date.now();
109
+ if (now - this.lastProbe < PROBE_GAP_MS) {
110
+ rsp.writeHead(429, { 'content-type': 'application/json; charset=utf-8' });
111
+ rsp.end(JSON.stringify({ ok: false, ms: 0, error: '刚测过,等几秒再来' }));
112
+ return;
113
+ }
114
+ this.lastProbe = now;
115
+ const probe = this.hooks.probe;
116
+ if (!probe) {
117
+ rsp.writeHead(501, { 'content-type': 'application/json; charset=utf-8' });
118
+ rsp.end(JSON.stringify({ ok: false, ms: 0, error: '这个版本不支持自检' }));
119
+ return;
120
+ }
121
+ void probe()
122
+ .then((result) => {
123
+ rsp.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
124
+ rsp.end(JSON.stringify(result));
125
+ })
126
+ .catch((error: unknown) => {
127
+ rsp.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
128
+ rsp.end(JSON.stringify({ ok: false, ms: 0, error: error instanceof Error ? error.message : String(error) }));
129
+ });
130
+ return;
131
+ }
132
+ if (url.pathname === '/api/data') {
133
+ let body = '';
134
+ try {
135
+ body = JSON.stringify(this.hooks.data());
136
+ } catch (error) {
137
+ body = JSON.stringify({ error: error instanceof Error ? error.message : String(error) });
138
+ }
139
+ rsp.writeHead(200, {
140
+ 'content-type': 'application/json; charset=utf-8',
141
+ 'cache-control': 'no-store',
142
+ });
143
+ rsp.end(body);
144
+ return;
145
+ }
146
+ if (url.pathname === '/' || url.pathname === '/index.html') {
147
+ let html = '';
148
+ try {
149
+ html = readFileSync(PAGE_FILE, 'utf8');
150
+ } catch {
151
+ rsp.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
152
+ rsp.end('页面文件丢了,重装一下插件。');
153
+ return;
154
+ }
155
+ rsp.writeHead(200, {
156
+ 'content-type': 'text/html; charset=utf-8',
157
+ 'cache-control': 'no-store',
158
+ });
159
+ rsp.end(html);
160
+ return;
161
+ }
162
+ rsp.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
163
+ rsp.end('not found');
164
+ }
165
+ }
package/src/think.ts CHANGED
@@ -160,7 +160,19 @@ export async function callModel(opts: ModelOptions, messages: { role: string; co
160
160
  };
161
161
  } catch (error) {
162
162
  const msg = error instanceof Error ? error.message : String(error);
163
- return { ok: false, reason: controller.signal.aborted ? '超时' : msg };
163
+ if (controller.signal.aborted) return { ok: false, reason: '超时' };
164
+ // fetch 的 message 常常只有「fetch failed」,真正的原因在 cause.code 里
165
+ const code = (error as { cause?: { code?: string; message?: string } })?.cause?.code;
166
+ const detail = (error as { cause?: { message?: string } })?.cause?.message;
167
+ const hint = code === 'ECONNREFUSED'
168
+ ? '连不上这个地址(服务没开或端口不对)'
169
+ : code === 'ENOTFOUND'
170
+ ? '域名解析不了(地址写错了)'
171
+ : code === 'ETIMEDOUT' || code === 'UND_ERR_CONNECT_TIMEOUT'
172
+ ? '连不上(超时)'
173
+ : '';
174
+ const tail = [code, hint].filter(Boolean).join(':');
175
+ return { ok: false, reason: tail ? `${msg}(${tail})` : (detail ? `${msg}(${clip(detail, 60)})` : msg) };
164
176
  } finally {
165
177
  clearTimeout(timer);
166
178
  }
package/src/world.ts CHANGED
@@ -102,7 +102,10 @@ export class SelfAwarenessWorld implements World {
102
102
  const base = typeof ctx.dataDir === 'string' && ctx.dataDir ? ctx.dataDir : '.';
103
103
  this.dataDir = join(base, 'self-awareness');
104
104
  this.pool = new ThoughtPool(this.dataDir);
105
- this.site = new ThoughtSite({ data: () => this.siteData() });
105
+ this.site = new ThoughtSite({
106
+ data: () => this.siteData(),
107
+ probe: () => this.probe(),
108
+ });
106
109
  this.budget = loadBudget(this.dataDir);
107
110
  const last = this.pool.all().slice(-1)[0];
108
111
  if (last) this.lastSnapshot = { ts: last.ts, text: last.text, mode: last.mode };
@@ -126,23 +129,29 @@ export class SelfAwarenessWorld implements World {
126
129
  const cfg = this.cfg();
127
130
  const endpoint = resolveEndpoint(cfg);
128
131
  const next = this.budget.nextDueAt ? formatLocal(this.budget.nextDueAt, this.tz()).slice(11, 16) : '未安排';
129
- const last = this.lastSnapshot ? clip(this.lastSnapshot.text, 18) : '';
132
+ const core = this.readCoreState();
133
+ // 睡着不是错误,但也别显示成「在跑」——不然分不清她是睡了还是挂了
134
+ const dozing = Boolean(cfg.sleepSilent && core?.sleeping);
135
+ const bad = this.lastError ?? this.startupNote;
136
+ const state: 'online' | 'loading' | 'error' | 'offline' = bad
137
+ ? 'error'
138
+ : dozing
139
+ ? 'loading'
140
+ : cfg.enabled && endpoint.model
141
+ ? 'online'
142
+ : 'offline';
143
+ const hint = bad
144
+ ? clip(bad, 40)
145
+ : !cfg.enabled
146
+ ? '已关闭'
147
+ : !endpoint.model
148
+ ? '还没配模型'
149
+ : dozing
150
+ ? `睡着了(精力 ${Math.round(Number(core?.energy) || 0)}),醒了接着想`
151
+ : `今天想过 ${this.budget.count} 次`;
130
152
  return {
131
153
  label: '自我意识',
132
- lamps: [
133
- {
134
- label: '自我意识',
135
- // 出错要能一眼看见:不然 key 失效了还以为它在正常工作
136
- state: this.lastError ? 'offline' : cfg.enabled && endpoint.model ? 'online' : 'offline',
137
- hint: this.lastError
138
- ? `出错:${clip(this.lastError, 30)}`
139
- : !cfg.enabled
140
- ? '已关闭'
141
- : !endpoint.model
142
- ? '还没配模型'
143
- : `今天想过 ${this.budget.count} 次`,
144
- },
145
- ],
154
+ lamps: [{ label: '自我意识', state, hint }],
146
155
  badges: [
147
156
  { label: '今天想过', value: `${this.budget.count} 次` },
148
157
  { label: '下次', value: next },
@@ -177,6 +186,21 @@ export class SelfAwarenessWorld implements World {
177
186
  } catch {
178
187
  // 日志失败不影响挂载
179
188
  }
189
+ if (cfg.probeOnStart) {
190
+ // 不 await:启动不该为了一个 ping 卡住
191
+ void this.probe().then((r) => {
192
+ this.startupNote = r.ok ? null : `启动自检失败:${r.error}`;
193
+ if (!r.ok) {
194
+ try {
195
+ host.log?.warn?.(`[self-awareness] 启动自检失败:${r.error}`);
196
+ } catch {
197
+ // ignore
198
+ }
199
+ }
200
+ }).catch(() => {
201
+ this.startupNote = null;
202
+ });
203
+ }
180
204
  if (cfg.siteEnabled) {
181
205
  const origin = await this.site.start(cfg.sitePort).catch(() => null);
182
206
  if (origin) {
@@ -441,8 +465,12 @@ export class SelfAwarenessWorld implements World {
441
465
  if (explicit) return existsSync(explicit) ? explicit : null;
442
466
  const base = typeof this.ctx.dataDir === 'string' ? this.ctx.dataDir : '';
443
467
  if (!base) return null;
444
- const guess = join(base, 'memory-core');
445
- return existsSync(guess) ? guess : null;
468
+ // 宿主给的 dataDir 是 <botData>/self-awareness,记忆核心在 **同级** 的 memory-core。
469
+ // 但测试和手工跑时常常直接传 <botData>,所以两条都试——只认一条会静默读不到卡片。
470
+ for (const guess of [join(base, '..', 'memory-core'), join(base, 'memory-core')]) {
471
+ if (existsSync(guess)) return guess;
472
+ }
473
+ return null;
446
474
  }
447
475
 
448
476
  private cards(): CardLite[] {
@@ -620,6 +648,36 @@ export class SelfAwarenessWorld implements World {
620
648
 
621
649
  // ---- 给状态页看 ----
622
650
 
651
+ /**
652
+ * 手测一次接口通不通。
653
+ *
654
+ * 只发一句「在吗」拿一个回复——**不写任何文件、不占次数、不动 lastError**。
655
+ * 手点测试失败是查询行为,不该让状态灯一直红着。
656
+ */
657
+ async probe(): Promise<{ ok: boolean; ms: number; model?: string; error?: string }> {
658
+ const cfg = this.cfg();
659
+ const endpoint = resolveEndpoint(cfg);
660
+ if (!endpoint.model) return { ok: false, ms: 0, error: '还没选模型' };
661
+ if (endpoint.needsKey && !String(cfg.apiKey ?? '').trim()) return { ok: false, ms: 0, error: '还没填密钥' };
662
+ const started = Date.now();
663
+ const res = await callModel(
664
+ {
665
+ baseUrl: endpoint.baseUrl,
666
+ model: endpoint.model,
667
+ apiKey: String(cfg.apiKey ?? '').trim(),
668
+ maxTokens: 400,
669
+ temperature: 0,
670
+ },
671
+ [
672
+ { role: 'system', content: '只回一个字:好' },
673
+ { role: 'user', content: '在吗' },
674
+ ],
675
+ );
676
+ const ms = Date.now() - started;
677
+ if (!res.ok) return { ok: false, ms, error: res.reason ?? '未知错误' };
678
+ return { ok: true, ms, model: endpoint.model };
679
+ }
680
+
623
681
  /** 时间线页面要的数据:倒序、只给最近 60 条。 */
624
682
  private siteData(): Record<string, unknown> {
625
683
  const cfg = this.cfg();
package/webui/index.html CHANGED
@@ -40,6 +40,17 @@
40
40
  .stat b { display: block; font-size: 19px; font-weight: 500; font-variant-numeric: tabular-nums; }
41
41
  .stat span { color: var(--dim); font-size: 11.5px; }
42
42
  .warn { color: #ffb3a7; }
43
+ .toolbar { display: flex; align-items: center; gap: 10px; margin: -8px 0 22px; flex-wrap: wrap; }
44
+ .btn {
45
+ background: transparent; border: 1px solid var(--line); color: var(--text);
46
+ padding: 5px 13px; border-radius: 7px; font-size: 12px; cursor: pointer;
47
+ font-family: inherit; transition: border-color .15s, color .15s;
48
+ }
49
+ .btn:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
50
+ .btn:disabled { opacity: .45; cursor: default; }
51
+ .probe { font-size: 12px; color: var(--dim); }
52
+ .probe.ok { color: var(--accent); }
53
+ .probe.bad { color: #ffb3a7; }
43
54
  .err {
44
55
  margin: 0 0 20px; padding: 10px 14px; border-radius: 8px;
45
56
  border: 1px solid rgba(255, 120, 100, 0.3); background: rgba(255, 90, 70, 0.07);
@@ -93,6 +104,10 @@
93
104
  </header>
94
105
 
95
106
  <div class="stats" id="stats"></div>
107
+ <div class="toolbar">
108
+ <button class="btn" id="probe">测接口</button>
109
+ <span class="probe" id="probeResult"></span>
110
+ </div>
96
111
  <div id="err"></div>
97
112
 
98
113
  <h2>想过的事</h2>
@@ -180,6 +195,27 @@ async function load() {
180
195
 
181
196
  load();
182
197
  setInterval(load, 30000);
198
+
199
+ const probeBtn = document.getElementById('probe');
200
+ const probeOut = document.getElementById('probeResult');
201
+ probeBtn.addEventListener('click', async () => {
202
+ probeBtn.disabled = true;
203
+ probeOut.className = 'probe';
204
+ probeOut.textContent = '测中…';
205
+ try {
206
+ const rsp = await fetch('/api/probe', { method: 'POST' });
207
+ const r = await rsp.json();
208
+ probeOut.className = 'probe ' + (r.ok ? 'ok' : 'bad');
209
+ probeOut.textContent = r.ok
210
+ ? `通了 · ${r.model} · ${r.ms}ms`
211
+ : `失败 · ${r.error}`;
212
+ } catch (e) {
213
+ probeOut.className = 'probe bad';
214
+ probeOut.textContent = '请求发不出去';
215
+ } finally {
216
+ setTimeout(() => { probeBtn.disabled = false; }, 3000);
217
+ }
218
+ });
183
219
  </script>
184
220
  </body>
185
221
  </html>