ework-web 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/package.json +1 -1
- package/src/coordination.ts +32 -0
- package/src/index.ts +27 -2
- package/src/opencode.ts +58 -1
- package/src/views/users.ts +1 -0
- package/src/views/webhookDeliveries.ts +92 -0
- package/src/webhooks.ts +17 -0
package/package.json
CHANGED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { getDB } from "./db";
|
|
2
|
+
import { log } from "./logger";
|
|
3
|
+
|
|
4
|
+
export interface DaemonInfo {
|
|
5
|
+
id: number;
|
|
6
|
+
displayName: string;
|
|
7
|
+
endpoint: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const HEARTBEAT_STALE_MS = 120_000;
|
|
11
|
+
|
|
12
|
+
export async function getActiveDaemons(): Promise<DaemonInfo[]> {
|
|
13
|
+
const stale = new Date(Date.now() - HEARTBEAT_STALE_MS);
|
|
14
|
+
const staleStr = stale.toISOString().slice(0, 19).replace("T", " ");
|
|
15
|
+
try {
|
|
16
|
+
const rows = await getDB().all<{ id: number; display_name: string; internal_endpoint: string }>(
|
|
17
|
+
`SELECT id, display_name, internal_endpoint FROM {{d_daemons}} WHERE status = 'active' AND last_heartbeat > ?`,
|
|
18
|
+
[staleStr],
|
|
19
|
+
);
|
|
20
|
+
return rows
|
|
21
|
+
.filter((r): r is { id: number; display_name: string; internal_endpoint: string } =>
|
|
22
|
+
r.internal_endpoint !== null && r.internal_endpoint !== undefined && r.internal_endpoint !== "")
|
|
23
|
+
.map((r) => ({
|
|
24
|
+
id: r.id,
|
|
25
|
+
displayName: r.display_name ?? `daemon-${r.id}`,
|
|
26
|
+
endpoint: r.internal_endpoint,
|
|
27
|
+
}));
|
|
28
|
+
} catch (e) {
|
|
29
|
+
log.info(`coordination: query failed (${e instanceof Error ? e.message : String(e)}) — assuming single-machine`);
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -6,10 +6,11 @@ import { homedir } from "os";
|
|
|
6
6
|
import { loadConfig, DB_OVERRIDABLE, parseOverride, resolveTtsBackend } from "./config";
|
|
7
7
|
import type { Config } from "./config";
|
|
8
8
|
import { setConfig, initDB } from "./db";
|
|
9
|
+
import { getActiveDaemons } from "./coordination";
|
|
9
10
|
import { testMysqlConnection, migrateSqliteToMysql, writeMysqlEnv, migrateMysqlToSqlite, writeSqliteEnv, migrateDaemonSqliteToMysql } from "./db-admin";
|
|
10
11
|
import type { MysqlTargetOpts } from "./db-admin";
|
|
11
12
|
import { checkAuth, makeAuthCookieHeader, clearAuthCookieHeader, loginHTML, sanitizeNext, ensureBootstrapAdmin, ensureBootstrapSystem, isReservedSystemLogin } from "./auth";
|
|
12
|
-
import { OpencodeError, createOpencodeClient } from "./opencode";
|
|
13
|
+
import { OpencodeError, createOpencodeClient, MultiDaemonOpencodeClient, RemoteOpencodeClient, isLocalhost, type OpencodeClientInterface } from "./opencode";
|
|
13
14
|
import { renderMarkdown } from "./render/markdown";
|
|
14
15
|
import { log, uptimeSeconds, version } from "./logger";
|
|
15
16
|
import { buildIssueThread, fetchIssuePage, fetchIssueSince, errorPage } from "./views/issueThread";
|
|
@@ -81,10 +82,12 @@ import {
|
|
|
81
82
|
setWebhookActive,
|
|
82
83
|
getWebhook,
|
|
83
84
|
listDeliveries,
|
|
85
|
+
listAllRecentDeliveries,
|
|
84
86
|
type WebhookEventName,
|
|
85
87
|
} from "./webhooks";
|
|
86
88
|
import { classifyActor, type CommentView } from "./render/components";
|
|
87
89
|
import { buildWebhooksPage } from "./views/webhooks";
|
|
90
|
+
import { buildWebhookDeliveriesPage } from "./views/webhookDeliveries";
|
|
88
91
|
import { buildProjectMembersPage } from "./views/projectMembers";
|
|
89
92
|
import { buildProjectUpstreamsPage, trySetUpstreamUrls } from "./views/projectUpstreams";
|
|
90
93
|
import { buildProjectModelPage } from "./views/projectModel";
|
|
@@ -95,7 +98,24 @@ const STATIC_DIR = join(__dirname, "static");
|
|
|
95
98
|
|
|
96
99
|
await initDB();
|
|
97
100
|
const cfg: Config = await loadConfig();
|
|
98
|
-
|
|
101
|
+
let opencode: OpencodeClientInterface = createOpencodeClient(cfg, cfg.daemonWebhookUrl);
|
|
102
|
+
|
|
103
|
+
async function refreshOpencodeClient(): Promise<void> {
|
|
104
|
+
const daemons = await getActiveDaemons();
|
|
105
|
+
const remote = daemons.filter((d) => !isLocalhost(d.endpoint));
|
|
106
|
+
if (remote.length > 1) {
|
|
107
|
+
opencode = new MultiDaemonOpencodeClient(remote.map((d) => d.endpoint));
|
|
108
|
+
log.info(`opencode client: multi-daemon (${remote.length} remotes)`);
|
|
109
|
+
} else if (remote.length === 1) {
|
|
110
|
+
opencode = new RemoteOpencodeClient(remote[0]!.endpoint);
|
|
111
|
+
log.info(`opencode client: single remote (${remote[0]!.endpoint})`);
|
|
112
|
+
} else {
|
|
113
|
+
opencode = createOpencodeClient(cfg, cfg.daemonWebhookUrl);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
await refreshOpencodeClient();
|
|
118
|
+
setInterval(refreshOpencodeClient, 10_000);
|
|
99
119
|
|
|
100
120
|
async function autoWireDaemon(projectId: number, origin: string): Promise<void> {
|
|
101
121
|
if (!cfg.autowireActive) {
|
|
@@ -921,6 +941,11 @@ async function handle(req: Request, url: URL, ip: string, ctx: { authed: boolean
|
|
|
921
941
|
return html(buildAdminTokensPage(ctx.user!, await listAllPatsWithUsers(), flash));
|
|
922
942
|
}
|
|
923
943
|
|
|
944
|
+
if (url.pathname === "/admin/deliveries") {
|
|
945
|
+
const deliveries = await listAllRecentDeliveries(100);
|
|
946
|
+
return html(buildWebhookDeliveriesPage(ctx.user!, deliveries));
|
|
947
|
+
}
|
|
948
|
+
|
|
924
949
|
const adminPatRevoke = url.pathname.match(/^\/admin\/tokens\/(\d+)\/revoke$/);
|
|
925
950
|
if (adminPatRevoke && req.method === "POST") {
|
|
926
951
|
const id = Number(adminPatRevoke[1]);
|
package/src/opencode.ts
CHANGED
|
@@ -293,11 +293,68 @@ export class RemoteOpencodeClient implements OpencodeClientInterface {
|
|
|
293
293
|
}
|
|
294
294
|
}
|
|
295
295
|
|
|
296
|
-
function isLocalhost(endpoint: string): boolean {
|
|
296
|
+
export function isLocalhost(endpoint: string): boolean {
|
|
297
297
|
const host = endpoint.replace(/^https?:\/\//, "").split(":")[0] ?? "";
|
|
298
298
|
return /^(127\.|localhost$|0\.0\.0\.0$|::1$|\[::1\]$)/.test(host);
|
|
299
299
|
}
|
|
300
300
|
|
|
301
|
+
export class MultiDaemonOpencodeClient implements OpencodeClientInterface {
|
|
302
|
+
private readonly clients: RemoteOpencodeClient[];
|
|
303
|
+
|
|
304
|
+
constructor(endpoints: string[]) {
|
|
305
|
+
this.clients = endpoints.map((ep) => new RemoteOpencodeClient(ep));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async listSessions(limit: number): Promise<SessionListItem[]> {
|
|
309
|
+
const results = await Promise.allSettled(
|
|
310
|
+
this.clients.map((c) => c.listSessions(limit)),
|
|
311
|
+
);
|
|
312
|
+
const all: SessionListItem[] = [];
|
|
313
|
+
const seen = new Set<string>();
|
|
314
|
+
for (const r of results) {
|
|
315
|
+
if (r.status === "fulfilled") {
|
|
316
|
+
for (const s of r.value) {
|
|
317
|
+
if (s.id && !seen.has(s.id)) {
|
|
318
|
+
seen.add(s.id);
|
|
319
|
+
all.push(s);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
all.sort((a, b) => b.updated - a.updated);
|
|
325
|
+
return all.slice(0, limit);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async exportSession(id: string): Promise<SessionExport> {
|
|
329
|
+
try {
|
|
330
|
+
return await Promise.any(this.clients.map((c) => c.exportSession(id)));
|
|
331
|
+
} catch {
|
|
332
|
+
throw new OpencodeError(`session ${id} not found on any daemon`, 404);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async exportSessionRaw(id: string): Promise<string> {
|
|
337
|
+
try {
|
|
338
|
+
return await Promise.any(this.clients.map((c) => c.exportSessionRaw(id)));
|
|
339
|
+
} catch {
|
|
340
|
+
throw new OpencodeError(`session ${id} not found on any daemon`, 404);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async listModels(): Promise<string[]> {
|
|
345
|
+
const results = await Promise.allSettled(
|
|
346
|
+
this.clients.map((c) => c.listModels()),
|
|
347
|
+
);
|
|
348
|
+
const models = new Set<string>();
|
|
349
|
+
for (const r of results) {
|
|
350
|
+
if (r.status === "fulfilled") {
|
|
351
|
+
for (const m of r.value) models.add(m);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return [...models];
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
301
358
|
export function createOpencodeClient(cfg: Config, daemonEndpoint?: string): OpencodeClientInterface {
|
|
302
359
|
if (daemonEndpoint && !isLocalhost(daemonEndpoint)) {
|
|
303
360
|
return new RemoteOpencodeClient(daemonEndpoint);
|
package/src/views/users.ts
CHANGED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { type DeliveryWithWebhookRow } from "../webhooks";
|
|
2
|
+
import { type UserRow } from "../store";
|
|
3
|
+
import { THEME_CSS, escapeHtml, escapeAttr, tabNavHTML } from "../render/layout";
|
|
4
|
+
|
|
5
|
+
function statusClass(status: number | null): string {
|
|
6
|
+
if (status === null) return "err";
|
|
7
|
+
if (status >= 200 && status < 300) return "ok";
|
|
8
|
+
if (status >= 400 && status < 500) return "warn";
|
|
9
|
+
return "err";
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function deliveryRowHtml(d: DeliveryWithWebhookRow): string {
|
|
13
|
+
const status = d.response_status === null ? "—" : String(d.response_status);
|
|
14
|
+
const cls = statusClass(d.response_status);
|
|
15
|
+
const project = d.project_owner
|
|
16
|
+
? `<a href="/${escapeAttr(d.project_owner)}/${escapeAttr(d.project_name ?? "")}">${escapeHtml(d.project_owner + "/" + (d.project_name ?? ""))}</a>`
|
|
17
|
+
: "<em>(deleted)</em>";
|
|
18
|
+
const url = d.webhook_url ? `<code class="url">${escapeHtml(d.webhook_url)}</code>` : "<em>(deleted)</em>";
|
|
19
|
+
const err = d.error ? `<div class="derr">${escapeHtml(d.error)}</div>` : "";
|
|
20
|
+
const body = d.response_body
|
|
21
|
+
? `<details class="dbody"><summary>响应</summary><pre>${escapeHtml(d.response_body)}</pre></details>`
|
|
22
|
+
: "";
|
|
23
|
+
const payload = `<details class="dpl"><summary>payload</summary><pre>${escapeHtml(d.payload)}</pre></details>`;
|
|
24
|
+
return `<tr>
|
|
25
|
+
<td class="ts">${escapeHtml(d.created_at)}</td>
|
|
26
|
+
<td class="proj">${project}</td>
|
|
27
|
+
<td class="ev">${escapeHtml(d.event)}</td>
|
|
28
|
+
<td class="url">${url}</td>
|
|
29
|
+
<td class="st ${cls}">${status}</td>
|
|
30
|
+
<td class="ms">${d.duration_ms === null ? "—" : d.duration_ms + "ms"}</td>
|
|
31
|
+
<td class="act">${payload}${body}${err}</td>
|
|
32
|
+
</tr>`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function buildWebhookDeliveriesPage(viewer: UserRow, deliveries: DeliveryWithWebhookRow[]): string {
|
|
36
|
+
const rows = deliveries.length > 0
|
|
37
|
+
? deliveries.map(deliveryRowHtml).join("")
|
|
38
|
+
: `<tr><td colspan="7" class="empty">暂无投递记录</td></tr>`;
|
|
39
|
+
|
|
40
|
+
const ok = deliveries.filter((d) => d.response_status !== null && d.response_status >= 200 && d.response_status < 300).length;
|
|
41
|
+
const fail = deliveries.filter((d) => d.response_status === null || d.response_status >= 400).length;
|
|
42
|
+
const summary = deliveries.length > 0
|
|
43
|
+
? `<div class="summary"><span class="badge ok">${ok} 成功</span> <span class="badge ${fail > 0 ? "err" : ""}">${fail} 失败</span> <span class="muted">最近 ${deliveries.length} 条</span></div>`
|
|
44
|
+
: "";
|
|
45
|
+
|
|
46
|
+
return `<!doctype html>
|
|
47
|
+
<html lang="zh"><head><meta charset="utf-8">
|
|
48
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
49
|
+
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
50
|
+
<title>ework-web · Webhook 投递记录</title>
|
|
51
|
+
<style>${THEME_CSS}
|
|
52
|
+
.nav{display:flex;align-items:center;gap:.5rem;padding:.55rem 1rem;background:var(--header-bg);color:var(--header-text);font-size:13px}
|
|
53
|
+
.nav a{color:var(--header-text);opacity:.95}
|
|
54
|
+
.wrap{max-width:1100px;margin:0 auto;padding:1rem}
|
|
55
|
+
h1{font-size:18px;margin:0 0 .3rem}
|
|
56
|
+
.hint{color:var(--text-muted);font-size:13px;margin:0 0 1rem}
|
|
57
|
+
.summary{margin-bottom:.8rem;display:flex;gap:.5rem;align-items:center}
|
|
58
|
+
.badge{padding:2px 8px;border-radius:10px;font-size:12px;font-weight:600}
|
|
59
|
+
.badge.ok{background:#3fb95033;color:#3fb950}
|
|
60
|
+
.badge.err{background:#f8514933;color:#f85149}
|
|
61
|
+
.muted{color:var(--text-muted);font-size:12px}
|
|
62
|
+
.dtable{width:100%;border-collapse:collapse;font-size:12px}
|
|
63
|
+
.dtable th,.dtable td{border:1px solid var(--border);padding:.3rem .4rem;text-align:left;vertical-align:top}
|
|
64
|
+
.dtable th{background:var(--bg);color:var(--text-muted);font-weight:600;position:sticky;top:0}
|
|
65
|
+
.dtable .ts{white-space:nowrap;font-family:ui-monospace,monospace}
|
|
66
|
+
.dtable .proj{white-space:nowrap}
|
|
67
|
+
.dtable .proj a{color:var(--accent)}
|
|
68
|
+
.dtable .ev{white-space:nowrap;font-family:ui-monospace,monospace}
|
|
69
|
+
.dtable .url{max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
70
|
+
.dtable .url code{font-family:ui-monospace,monospace;font-size:11px;color:var(--text-muted)}
|
|
71
|
+
.dtable .st.ok{color:#3fb950;font-weight:600}
|
|
72
|
+
.dtable .st.warn{color:#d29922;font-weight:600}
|
|
73
|
+
.dtable .st.err{color:#f85149;font-weight:600}
|
|
74
|
+
.dtable .ms{color:var(--text-muted);white-space:nowrap}
|
|
75
|
+
.dbody pre,.dpl pre{font-size:11px;max-height:240px;overflow:auto;background:var(--bg);padding:.4rem;border-radius:5px;border:1px solid var(--border);white-space:pre-wrap;word-break:break-all}
|
|
76
|
+
.derr{color:#f85149;font-size:11px;margin-top:.2rem}
|
|
77
|
+
.empty{color:var(--text-muted);text-align:center;padding:.6rem}
|
|
78
|
+
.tabs{display:flex;gap:.3rem;padding:.5rem 1rem;border-bottom:1px solid var(--border);font-size:13px}
|
|
79
|
+
.tab{padding:.3rem .7rem;border-radius:6px 6px 0 0;text-decoration:none;color:var(--text-muted)}
|
|
80
|
+
.tab.active{background:var(--accent);color:#fff}
|
|
81
|
+
</style></head><body>
|
|
82
|
+
<header class="nav"><a href="/" style="color:var(--header-text)">🏠 ework-web</a></header>
|
|
83
|
+
${tabNavHTML("projects", viewer)}
|
|
84
|
+
<main class="wrap">
|
|
85
|
+
<h1>Webhook 投递记录</h1>
|
|
86
|
+
<p class="hint">所有项目的 webhook 投递历史。用于排查 "AI 没回应" 类问题 — 如果投递失败(红色状态码),daemon 根本没收到事件。</p>
|
|
87
|
+
${summary}
|
|
88
|
+
<table class="dtable"><thead><tr>
|
|
89
|
+
<th>时间</th><th>项目</th><th>事件</th><th>目标 URL</th><th>状态</th><th>耗时</th><th>详情</th>
|
|
90
|
+
</tr></thead><tbody>${rows}</tbody></table>
|
|
91
|
+
</main></body></html>`;
|
|
92
|
+
}
|
package/src/webhooks.ts
CHANGED
|
@@ -177,6 +177,23 @@ export async function listDeliveries(webhookId: number, limit = 50): Promise<Web
|
|
|
177
177
|
);
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
+
export interface DeliveryWithWebhookRow extends WebhookDeliveryRow {
|
|
181
|
+
webhook_url: string;
|
|
182
|
+
project_owner: string;
|
|
183
|
+
project_name: string;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function listAllRecentDeliveries(limit = 100): Promise<DeliveryWithWebhookRow[]> {
|
|
187
|
+
return await getDB().all<DeliveryWithWebhookRow>(
|
|
188
|
+
`SELECT d.*, w.url AS webhook_url, p.owner AS project_owner, p.name AS project_name
|
|
189
|
+
FROM {{webhook_deliveries}} d
|
|
190
|
+
LEFT JOIN {{webhooks}} w ON w.id = d.webhook_id
|
|
191
|
+
LEFT JOIN {{projects}} p ON p.id = w.project_id
|
|
192
|
+
ORDER BY d.id DESC LIMIT ?`,
|
|
193
|
+
[limit]
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
180
197
|
// ─── Payload builders (Gitea-compatible shape) ───────────────
|
|
181
198
|
//
|
|
182
199
|
// We populate the fields downstream consumers actually read (see Gitea's
|