@allbluecn/web-app 0.28.11 → 0.28.13
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 +5 -5
- package/public/dev-gallery.html +19 -0
- package/src/__tests__/bench/baselines/format-timestamp.json +44 -0
- package/src/__typeprobe__.d.ts +4 -0
- package/src/components/harness/extension-panel/panels/terminal/__tests__/terminal-instance.test.tsx +93 -4
- package/src/components/harness/extension-panel/panels/terminal/sse-transport.ts +28 -5
- package/src/components/harness/extension-panel/panels/terminal/terminal-instance.tsx +53 -10
- package/src/components/harness/extension-panel/panels/terminal/transport.ts +10 -3
- package/src/components/harness/extension-panel/panels/terminal/ws-transport.ts +13 -2
- package/src/components/settings/harness/connectors-card.tsx +5 -0
- package/src/components/story/detail/story-detail-toolbar/associated-attachments-panel.tsx +2 -1
- package/src/dev/gallery-entry.tsx +38 -0
- package/src/dev/gallery.tsx +610 -0
- package/src/lib/changelog/sdk-versions.ts +4 -4
- package/src/lib/session.ts +10 -0
- package/src/paraglide/README.md +1 -1
- package/src/paraglide/messages/_index.d.ts +9 -0
- package/src/paraglide/messages/_index.js +9 -0
- package/src/paraglide/messages/capabilities_webhook.d.ts +16 -0
- package/src/paraglide/messages/capabilities_webhook.js +29 -0
- package/src/paraglide/messages/capabilities_workflow.d.ts +16 -0
- package/src/paraglide/messages/capabilities_workflow.js +29 -0
- package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.d.ts +17 -0
- package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.js +30 -0
- package/src/paraglide/messages/harness_panel_terminal_restarted.d.ts +16 -0
- package/src/paraglide/messages/harness_panel_terminal_restarted.js +29 -0
- package/src/paraglide/messages/settings_harness_connectors_needsauth1.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_connectors_needsauth1.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphenabled1.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphenabled1.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphenabled_description1.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphenabled_description1.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds2.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds2.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.js +30 -0
- package/src/routeTree.gen.ts +21 -0
- package/src/routes/api/auth/desktop-callback.ts +9 -0
- package/src/routes/api/chat.ts +8 -1
- package/src/routes/api/harness/browser/proxy.ts +41 -12
- package/src/routes/api/harness/terminal/$.ts +32 -13
- package/src/routes/api/harness/terminal/__tests__/route.test.ts +41 -0
- package/src/routes/api/harness/webhook/$token.ts +23 -0
- package/src/routes/api/sync/__tests__/bootstrap.test.ts +32 -1
- package/src/routes/api/sync/bootstrap.ts +11 -0
- package/src/server/ai-gateway/adapter.ts +7 -3
- package/src/server/ai-gateway/connectivity-check.ts +3 -2
- package/src/server/ai-gateway/durability/__tests__/sse-resume-frames.test.ts +123 -0
- package/src/server/ai-gateway/embedding.ts +3 -2
- package/src/server/ai-gateway/model-fetch.ts +3 -2
- package/src/server/ai-gateway/sandbox/__tests__/provider.test.ts +12 -1
- package/src/server/ai-gateway/sandbox/policy.ts +27 -1
- package/src/server/ai-gateway/sandbox/provider.ts +10 -0
- package/src/server/ai-gateway/tools/definitions.ts +1 -1
- package/src/server/ai-gateway/tools/server.ts +4 -2
- package/src/server/harness/__tests__/agent-terminal-sandbox.test.ts +23 -4
- package/src/server/harness/__tests__/agent-terminal.server.test.ts +118 -2
- package/src/server/harness/__tests__/credentials.server.test.ts +25 -2
- package/src/server/harness/__tests__/host-schedule-worker.test.ts +43 -0
- package/src/server/harness/__tests__/runtime-without-providers.test.ts +11 -0
- package/src/server/harness/__tests__/sticky-route.test.ts +86 -0
- package/src/server/harness/__tests__/terminal-foreground.server.test.ts +80 -0
- package/src/server/harness/__tests__/terminal-manager.server.test.ts +75 -1
- package/src/server/harness/__tests__/tool-entitlements.test.ts +6 -2
- package/src/server/harness/agent-terminal.server.ts +25 -4
- package/src/server/harness/agents/__tests__/agent-control.test.ts +1 -0
- package/src/server/harness/agents/run-view.server.ts +55 -2
- package/src/server/harness/capabilities/__tests__/__snapshots__/matrix.test.ts.snap +92 -0
- package/src/server/harness/capabilities/__tests__/execution-plane-denials.test.ts +3 -1
- package/src/server/harness/capabilities/__tests__/p3-matrix.test.ts +3 -3
- package/src/server/harness/capabilities/__tests__/p5-matrix.test.ts +293 -0
- package/src/server/harness/capabilities/__tests__/validate.test.ts +8 -2
- package/src/server/harness/capabilities/execution-plane-denials.ts +9 -3
- package/src/server/harness/capabilities/manifests/agent-terminal.ts +3 -2
- package/src/server/harness/capabilities/manifests/webhook.ts +45 -0
- package/src/server/harness/capabilities/manifests/workflow.ts +40 -0
- package/src/server/harness/capabilities/registry.ts +4 -0
- package/src/server/harness/connectors/__tests__/connector-accounts.test.ts +22 -1
- package/src/server/harness/connectors/connector-accounts.server.ts +7 -0
- package/src/server/harness/credentials.server.ts +3 -1
- package/src/server/harness/define.server.ts +11 -0
- package/src/server/harness/mcp/mcp-config.server.ts +3 -1
- package/src/server/harness/outbox/outbox-dispatcher.server.ts +9 -0
- package/src/server/harness/outbox/outbox-store.server.ts +7 -0
- package/src/server/harness/persistence/__tests__/log-store.server.test.ts +4 -1
- package/src/server/harness/plugins/__tests__/tool-risk-audit.test.ts +5 -1
- package/src/server/harness/plugins/builtin/agent-terminal.plugin.ts +12 -2
- package/src/server/harness/providers/contracts.ts +16 -0
- package/src/server/harness/schedule/schedule-dispatcher.server.ts +3 -0
- package/src/server/harness/search/__tests__/indexer.test.ts +4 -1
- package/src/server/harness/search/__tests__/lifecycle.test.ts +4 -1
- package/src/server/harness/search/__tests__/search.test.ts +4 -1
- package/src/server/harness/sticky-route.server.ts +72 -0
- package/src/server/harness/terminal-foreground.server.ts +90 -0
- package/src/server/harness/terminal-manager.server.ts +78 -3
- package/src/server/harness/tool-entitlements.server.ts +5 -0
- package/src/server/harness/webhook/__tests__/body.test.ts +73 -0
- package/src/server/harness/webhook/__tests__/payload.test.ts +215 -0
- package/src/server/harness/webhook/__tests__/signature.test.ts +170 -0
- package/src/server/harness/webhook/__tests__/webhook-dispatcher.test.ts +212 -0
- package/src/server/harness/webhook/__tests__/webhook.plugin.test.ts +195 -0
- package/src/server/harness/webhook/__tests__/webhook.service.test.ts +354 -0
- package/src/server/harness/webhook/body.server.ts +56 -0
- package/src/server/harness/webhook/payload.server.ts +169 -0
- package/src/server/harness/webhook/signature.server.ts +118 -0
- package/src/server/harness/webhook/types.ts +57 -0
- package/src/server/harness/webhook/webhook-dispatcher.server.ts +495 -0
- package/src/server/harness/webhook/webhook-store.server.ts +115 -0
- package/src/server/harness/webhook/webhook.plugin.ts +273 -0
- package/src/server/harness/webhook/webhook.service.server.ts +577 -0
- package/src/server/harness/worker/__tests__/worker-http.test.ts +8 -1
- package/src/server/harness/worker/worker-health.server.ts +4 -1
- package/src/server/harness/worker/worker-runtime.server.ts +43 -1
- package/src/server/harness/workflow/__tests__/engine.test.ts +195 -0
- package/src/server/harness/workflow/__tests__/settings.test.ts +125 -0
- package/src/server/harness/workflow/__tests__/validate.test.ts +151 -0
- package/src/server/harness/workflow/engine.server.ts +155 -0
- package/src/server/harness/workflow/settings.ts +84 -0
- package/src/server/harness/workflow/store.server.ts +147 -0
- package/src/server/harness/workflow/types.ts +80 -0
- package/src/server/harness/workflow/validate.ts +130 -0
- package/src/server/harness/workflow/workflow.plugin.ts +261 -0
- package/src/server/knowledge/search-scope.ts +8 -1
- package/src/server/middlewares/security-headers.ts +1 -0
- package/src/server/serverFns/__tests__/link-preview.test.ts +2 -2
- package/src/server/serverFns/collab.ts +4 -0
- package/src/server/serverFns/design/versions.ts +6 -0
- package/src/server/serverFns/harness/__tests__/fork-thread.test.ts +14 -1
- package/src/server/serverFns/harness/fork-thread.ts +17 -0
- package/src/server/serverFns/story/link-preview.ts +3 -2
- package/src/server-entry.ts +13 -1
- package/src/start.ts +15 -1
- package/vite.shared.ts +0 -13
|
@@ -59,6 +59,12 @@ export async function claim(input: {
|
|
|
59
59
|
workerId: string
|
|
60
60
|
userId?: string
|
|
61
61
|
plane: ScheduleExecutionPlane
|
|
62
|
+
/**
|
|
63
|
+
* 只领取这些 kind 的行(P5 任务 3 引入:schedule 与 webhook 共用一张 outbox 表,
|
|
64
|
+
* 各自 dispatcher 必须按 kind 隔离,否则会互相抢走对方待投递行并误标 skipped)。
|
|
65
|
+
* 省略 = 不按 kind 过滤(保留既有调用语义)。
|
|
66
|
+
*/
|
|
67
|
+
kinds?: readonly string[]
|
|
62
68
|
limit?: number
|
|
63
69
|
now?: Date
|
|
64
70
|
signal?: AbortSignal
|
|
@@ -66,10 +72,12 @@ export async function claim(input: {
|
|
|
66
72
|
if (input.signal?.aborted) return []
|
|
67
73
|
const now = input.now ?? new Date()
|
|
68
74
|
const limit = Math.max(1, Math.min(input.limit ?? 100, 1000))
|
|
75
|
+
const kindFilter = input.kinds && input.kinds.length > 0 ? { kind: { in: [...input.kinds] } } : {}
|
|
69
76
|
const candidates = await prisma.harnessOutbox.findMany({
|
|
70
77
|
where: {
|
|
71
78
|
...(input.userId ? { userId: input.userId } : {}),
|
|
72
79
|
executionPlane: input.plane,
|
|
80
|
+
...kindFilter,
|
|
73
81
|
OR: [
|
|
74
82
|
{ state: 'pending', nextAttemptAt: { lte: now } },
|
|
75
83
|
{ state: 'claimed', leaseUntil: { lt: now } },
|
|
@@ -99,6 +107,7 @@ export async function claim(input: {
|
|
|
99
107
|
id: candidate.id,
|
|
100
108
|
...(input.userId ? { userId: input.userId } : {}),
|
|
101
109
|
executionPlane: input.plane,
|
|
110
|
+
...kindFilter,
|
|
102
111
|
...snapshot,
|
|
103
112
|
},
|
|
104
113
|
data: {
|
|
@@ -6,6 +6,13 @@ import { prisma, type Prisma } from '@allbluecn/database'
|
|
|
6
6
|
|
|
7
7
|
export type ScheduleExecutionPlane = 'local' | 'cloud'
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* outbox 行的 kind 取值。schedule 与 webhook 共用 harness_outbox 表,
|
|
11
|
+
* 各自 dispatcher 必须按 kind 隔离领取(P5 任务 3)。
|
|
12
|
+
*/
|
|
13
|
+
export const OUTBOX_KIND_SCHEDULE = 'schedule.wake'
|
|
14
|
+
export const OUTBOX_KIND_WEBHOOK = 'webhook.delivery'
|
|
15
|
+
|
|
9
16
|
export interface ScheduleWakePayload {
|
|
10
17
|
scheduleId: string
|
|
11
18
|
occurrenceId: string
|
|
@@ -16,13 +16,16 @@ import { createPrismaLogStore, flushLogStoreCallbacks } from '../log-store.serve
|
|
|
16
16
|
let client: PrismaClient
|
|
17
17
|
let dataDir: string
|
|
18
18
|
|
|
19
|
+
// 钩子超时 180s(原 60s):createPglite 会把 migrations/ 下全部迁移逐条 exec(当前 115 条),
|
|
20
|
+
// 每条都带 WAL fsync——磁盘吃紧/负载高的机器上单条可达 ~1s,60s 会稳定假红(实测 121s 才过)。
|
|
21
|
+
// 这是测试装置的时间假设问题,不是被测代码慢。
|
|
19
22
|
beforeAll(async () => {
|
|
20
23
|
const requireFromHere = createRequire(import.meta.url)
|
|
21
24
|
const databaseRoot = dirname(requireFromHere.resolve('@allbluecn/database/pg-client'))
|
|
22
25
|
dataDir = mkdtempSync(join(tmpdir(), 'harness-log-callbacks-'))
|
|
23
26
|
const { createPglite } = await import('@allbluecn/database/pglite-init')
|
|
24
27
|
client = (await createPglite({ dataDir, migrationsDir: join(databaseRoot, 'migrations') })).prisma
|
|
25
|
-
},
|
|
28
|
+
}, 180_000)
|
|
26
29
|
|
|
27
30
|
afterAll(async () => {
|
|
28
31
|
await flushLogStoreCallbacks()
|
|
@@ -37,6 +37,8 @@ import { jobsToolNames } from '../../jobs/jobs.plugin'
|
|
|
37
37
|
import { mcpResourceToolNames } from '../../mcp/mcp.plugin'
|
|
38
38
|
import { goalToolNames } from '../../goal/goal-tools.server'
|
|
39
39
|
import { teamToolNames } from '../../team/team.plugin'
|
|
40
|
+
import { webhookToolNames } from '../../webhook/webhook.plugin'
|
|
41
|
+
import { workflowToolNames } from '../../workflow/workflow.plugin'
|
|
40
42
|
import { agentControlToolNames } from '../../agents/agent-control.plugin'
|
|
41
43
|
import { codeModeToolNames } from '../../code-mode/code-mode.plugin'
|
|
42
44
|
import { shellToolNames } from '../../shell/shell.plugin'
|
|
@@ -72,6 +74,8 @@ const allTools: ReadonlyArray<{ name: string; needsApproval?: unknown }> = [
|
|
|
72
74
|
...mcpResourceToolNames.map((name) => ({ name })),
|
|
73
75
|
...goalToolNames.map((name) => ({ name })),
|
|
74
76
|
...teamToolNames.map((name) => ({ name })),
|
|
77
|
+
...workflowToolNames.map((name) => ({ name })),
|
|
78
|
+
...webhookToolNames.map((name) => ({ name })),
|
|
75
79
|
...agentControlToolNames.map((name) => ({ name })),
|
|
76
80
|
...codeModeToolNames.map((name) => ({ name })),
|
|
77
81
|
...shellToolNames.map((name) => ({ name })),
|
|
@@ -84,7 +88,7 @@ const allTools: ReadonlyArray<{ name: string; needsApproval?: unknown }> = [
|
|
|
84
88
|
]
|
|
85
89
|
|
|
86
90
|
describe('harness 工具风险分类审计(F4-6 §1.3/§1.4,Ruling P7)', () => {
|
|
87
|
-
it(`分类表双向精确覆盖:${allTools.length} 个工具全部登记,无残留键(含 team、agents 与 question)`, () => {
|
|
91
|
+
it(`分类表双向精确覆盖:${allTools.length} 个工具全部登记,无残留键(含 team、workflow、webhook、agents 与 question)`, () => {
|
|
88
92
|
const toolNames = allTools.map((t) => t.name).sort()
|
|
89
93
|
const classified = Object.keys(getDeclaredHarnessToolRisk()).sort()
|
|
90
94
|
expect(classified).toHaveLength(allTools.length)
|
|
@@ -183,6 +183,10 @@ const terminalSendDef = toolDefinition({
|
|
|
183
183
|
waitReason: z.enum(['idle', 'timeout', 'session_exit']),
|
|
184
184
|
sessionStatus: z.enum(['running', 'exited', 'failed']),
|
|
185
185
|
truncated: z.boolean().describe('viewport 超过 256KiB 被裁剪(最旧行丢弃)'),
|
|
186
|
+
awaitingInput: z
|
|
187
|
+
.boolean()
|
|
188
|
+
.optional()
|
|
189
|
+
.describe('前台命令可能在等 stdin 输入(交互提示/REPL/分页器);启发式提示,非保证'),
|
|
186
190
|
}),
|
|
187
191
|
})
|
|
188
192
|
|
|
@@ -210,11 +214,17 @@ const terminalSignalDef = toolDefinition({
|
|
|
210
214
|
sessionId: z.string().describe('terminal_open 返回的终端会话 ID'),
|
|
211
215
|
signal: z
|
|
212
216
|
.enum(['SIGINT', 'SIGTSTP', 'SIGTERM', 'SIGKILL', 'SIGHUP'])
|
|
213
|
-
.describe(
|
|
217
|
+
.describe(
|
|
218
|
+
'SIGINT/SIGTSTP 作为控制字符送达(同用户按键);SIGTERM/SIGKILL/SIGHUP 只发给前台命令的进程组,' +
|
|
219
|
+
'不影响 shell 与后台作业(前台无命令时会被拒绝,改用 terminal_close)',
|
|
220
|
+
),
|
|
214
221
|
}),
|
|
215
222
|
outputSchema: z.object({
|
|
216
223
|
delivered: z.literal(true),
|
|
217
|
-
method: z
|
|
224
|
+
method: z
|
|
225
|
+
.enum(['control-char', 'foreground-group'])
|
|
226
|
+
.describe('control-char = 控制字符送达;foreground-group = 定向到前台进程组'),
|
|
227
|
+
pgid: z.number().int().optional().describe('foreground-group 时命中的进程组 id'),
|
|
218
228
|
}),
|
|
219
229
|
})
|
|
220
230
|
|
|
@@ -58,6 +58,22 @@ export type ProviderErrorCode =
|
|
|
58
58
|
| 'agent_calls_exceeded'
|
|
59
59
|
| 'agent_unavailable'
|
|
60
60
|
| 'RUN_NOT_FOUND'
|
|
61
|
+
| /** workflow 定义无效(P5 任务 1):阶段 id 重复/缺 prompt/引用未知/自依赖等。 */
|
|
62
|
+
'workflow_invalid'
|
|
63
|
+
| /** workflow 阶段依赖成环(P5 任务 1)。 */
|
|
64
|
+
'workflow_cycle'
|
|
65
|
+
| /** workflow 阶段数或定义体量超限(P5 任务 1)。 */
|
|
66
|
+
'workflow_too_large'
|
|
67
|
+
| /** workflow run 不存在或不属于当前用户(P5 任务 1)。 */
|
|
68
|
+
'workflow_not_found'
|
|
69
|
+
| /** workflow run 已结束,不能再推进/取消(P5 任务 1)。 */
|
|
70
|
+
'workflow_not_running'
|
|
71
|
+
| /** workflow 当前运行缺少线程或用户上下文(P5 任务 1)。 */
|
|
72
|
+
'workflow_forbidden'
|
|
73
|
+
| /** Ralph 未在设置中开启,但定义要求 ralph 模式(P5 任务 2)。 */
|
|
74
|
+
'workflow_ralph_disabled'
|
|
75
|
+
| /** Ralph 轮数超过线程级设置上限(P5 任务 2)。 */
|
|
76
|
+
'workflow_ralph_over_limit'
|
|
61
77
|
| 'run_not_running'
|
|
62
78
|
| 'budget'
|
|
63
79
|
| 'HARNESS_CONTRIBUTION_INVALID'
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
} from '../outbox/outbox-dispatcher.server'
|
|
18
18
|
import {
|
|
19
19
|
createScheduleOccurrenceOutbox,
|
|
20
|
+
OUTBOX_KIND_SCHEDULE,
|
|
20
21
|
type ScheduleExecutionPlane,
|
|
21
22
|
} from '../outbox/outbox-store.server'
|
|
22
23
|
import { materializeDueSchedules } from './schedule-materializer.server'
|
|
@@ -541,6 +542,8 @@ export function createScheduleDispatcher(options: ScheduleDispatcherOptions) {
|
|
|
541
542
|
workerId,
|
|
542
543
|
userId: options.userId,
|
|
543
544
|
plane,
|
|
545
|
+
// 与 webhook dispatcher 隔离:共用 outbox 表,只领自己的 kind(P5 任务 3)。
|
|
546
|
+
kinds: [OUTBOX_KIND_SCHEDULE],
|
|
544
547
|
limit,
|
|
545
548
|
now: new Date(nowMs),
|
|
546
549
|
signal: controller.signal,
|
|
@@ -38,6 +38,9 @@ import { createPrismaLogStore, flushLogStoreCallbacks } from '../../persistence/
|
|
|
38
38
|
let client: PrismaClient
|
|
39
39
|
let dataDir: string
|
|
40
40
|
|
|
41
|
+
// 钩子超时 180s(原 60s):createPglite 会把 migrations/ 下全部迁移逐条 exec(当前 115 条),
|
|
42
|
+
// 每条都带 WAL fsync——磁盘吃紧/负载高的机器上单条可达 ~1s,60s 会稳定假红(实测 121s 才过)。
|
|
43
|
+
// 这是测试装置的时间假设问题,不是被测代码慢。
|
|
41
44
|
beforeAll(async () => {
|
|
42
45
|
const requireFromHere = createRequire(import.meta.url)
|
|
43
46
|
const databaseRoot = dirname(requireFromHere.resolve('@allbluecn/database/pg-client'))
|
|
@@ -45,7 +48,7 @@ beforeAll(async () => {
|
|
|
45
48
|
const { createPglite } = await import('@allbluecn/database/pglite-init')
|
|
46
49
|
const handle = await createPglite({ dataDir, migrationsDir: join(databaseRoot, 'migrations') })
|
|
47
50
|
client = handle.prisma
|
|
48
|
-
},
|
|
51
|
+
}, 180_000)
|
|
49
52
|
|
|
50
53
|
afterAll(async () => {
|
|
51
54
|
await flushLogStoreCallbacks()
|
|
@@ -28,13 +28,16 @@ import { createSessionSearchProvider } from '../../providers/session-search.serv
|
|
|
28
28
|
let client: PrismaClient
|
|
29
29
|
let dataDir: string
|
|
30
30
|
|
|
31
|
+
// 钩子超时 180s(原 60s):createPglite 会把 migrations/ 下全部迁移逐条 exec(当前 115 条),
|
|
32
|
+
// 每条都带 WAL fsync——磁盘吃紧/负载高的机器上单条可达 ~1s,60s 会稳定假红(实测 121s 才过)。
|
|
33
|
+
// 这是测试装置的时间假设问题,不是被测代码慢。
|
|
31
34
|
beforeAll(async () => {
|
|
32
35
|
const requireFromHere = createRequire(import.meta.url)
|
|
33
36
|
const databaseRoot = dirname(requireFromHere.resolve('@allbluecn/database/pg-client'))
|
|
34
37
|
dataDir = mkdtempSync(join(tmpdir(), 'harness-search-lifecycle-'))
|
|
35
38
|
const { createPglite } = await import('@allbluecn/database/pglite-init')
|
|
36
39
|
client = (await createPglite({ dataDir, migrationsDir: join(databaseRoot, 'migrations') })).prisma
|
|
37
|
-
},
|
|
40
|
+
}, 180_000)
|
|
38
41
|
|
|
39
42
|
afterAll(async () => {
|
|
40
43
|
await flushSessionSearchTasks()
|
|
@@ -18,13 +18,16 @@ import { searchSessionSearch } from '../session-search.service.server'
|
|
|
18
18
|
let client: PrismaClient
|
|
19
19
|
let dataDir: string
|
|
20
20
|
|
|
21
|
+
// 钩子超时 180s(原 60s):createPglite 会把 migrations/ 下全部迁移逐条 exec(当前 115 条),
|
|
22
|
+
// 每条都带 WAL fsync——磁盘吃紧/负载高的机器上单条可达 ~1s,60s 会稳定假红(实测 121s 才过)。
|
|
23
|
+
// 这是测试装置的时间假设问题,不是被测代码慢。
|
|
21
24
|
beforeAll(async () => {
|
|
22
25
|
const requireFromHere = createRequire(import.meta.url)
|
|
23
26
|
const databaseRoot = dirname(requireFromHere.resolve('@allbluecn/database/pg-client'))
|
|
24
27
|
dataDir = mkdtempSync(join(tmpdir(), 'harness-search-query-'))
|
|
25
28
|
const { createPglite } = await import('@allbluecn/database/pglite-init')
|
|
26
29
|
client = (await createPglite({ dataDir, migrationsDir: join(databaseRoot, 'migrations') })).prisma
|
|
27
|
-
},
|
|
30
|
+
}, 180_000)
|
|
28
31
|
|
|
29
32
|
afterAll(async () => {
|
|
30
33
|
await client?.$disconnect()
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// AllBlue - 理想之海
|
|
3
|
+
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
+
//
|
|
5
|
+
// 多实例 sticky 路由的**应用侧契约**(P5 任务 8,母规格 §5.2.1 / §6.5)。
|
|
6
|
+
//
|
|
7
|
+
// 边界先说清楚:sticky 是 **ingress/LB 的路由语义**,不是应用状态。终端 PTY 活在某个
|
|
8
|
+
// 进程内存里,跨实例无法迁移;能否粘住由 ingress 决定,应用能做的是三件事:
|
|
9
|
+
//
|
|
10
|
+
// 1. **给出可哈希的粘性键**:终端的每个请求(create / SSE events / input / ack / kill /
|
|
11
|
+
// WS upgrade)都带 `?threadId=`——ingress 直接按 `$arg_threadId` 做一致性哈希即可,
|
|
12
|
+
// 不需要新的头/新字段,也不需要客户端额外配合(见 `stickyKeyForThread` 与下方契约)。
|
|
13
|
+
// 2. **暴露实例身份**:`x-allblue-instance` 响应头 + `/healthz.instanceId`,让运维能验证
|
|
14
|
+
// 分布、让客户端能区分「换了实例」与「同一实例上终端没了」。
|
|
15
|
+
// 3. **路由漂移时可自愈且不误导**:落到别的实例必得 404(那台机器没有这个 PTY);客户端
|
|
16
|
+
// 据 `instanceId` 判定「换实例」→ 静默重建(不是故障,不该弹「服务重启」)。
|
|
17
|
+
//
|
|
18
|
+
// **不新增任何分布式终端表**(母规格 §6.5 明令):一旦把「哪个实例持有哪个 PTY」写进
|
|
19
|
+
// 数据库,就变成了需要 TTL/心跳/脑裂处理的第二份运行态事实,而它随时会因进程崩溃而失真。
|
|
20
|
+
// 桌面单实例形态连这条路径都不需要。
|
|
21
|
+
//
|
|
22
|
+
// ingress 契约(SaaS 部署方按此配):
|
|
23
|
+
// upstream harness_ingress { server platform-1:7080; server platform-2:7080; }
|
|
24
|
+
// # threadId 查询参数 = 粘性键;`consistent` 避免实例增减时的全量重排
|
|
25
|
+
// hash $arg_threadId consistent;
|
|
26
|
+
// # WS/SSE 需要长 idle + upgrade 直通
|
|
27
|
+
// proxy_read_timeout 3600s; proxy_buffering off;
|
|
28
|
+
|
|
29
|
+
import { hostname } from 'node:os'
|
|
30
|
+
|
|
31
|
+
/** 响应头:本次请求落在哪个实例(诊断 / 客户端分流用,不参与鉴权)。 */
|
|
32
|
+
export const INSTANCE_HEADER = 'x-allblue-instance'
|
|
33
|
+
|
|
34
|
+
/** 响应头:本线程的粘性键(与 ingress 的哈希输入一致,便于排障比对)。 */
|
|
35
|
+
export const STICKY_KEY_HEADER = 'x-allblue-sticky-key'
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 进程实例标识:`<hostname>:<pid>`。
|
|
39
|
+
*
|
|
40
|
+
* 刻意**不含随机段**:容器重启后 hostname 通常不变但 pid 会变,故「同 hostname 不同 pid」
|
|
41
|
+
* 仍判为不同实例(正是我们想要的);随机段则会让同一进程在多次读取间「变脸」,破坏
|
|
42
|
+
* 客户端「同一实例」的比对语义。
|
|
43
|
+
*/
|
|
44
|
+
let cachedInstanceId: string | undefined
|
|
45
|
+
|
|
46
|
+
export function getInstanceId(): string {
|
|
47
|
+
if (cachedInstanceId === undefined) cachedInstanceId = `${hostname()}:${process.pid}`
|
|
48
|
+
return cachedInstanceId
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 仅测试用:重置实例标识缓存(模拟「换了实例」)。 */
|
|
52
|
+
export function __resetInstanceIdForTests(): void {
|
|
53
|
+
cachedInstanceId = undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 线程的粘性键。
|
|
58
|
+
*
|
|
59
|
+
* 形状与 ingress 的哈希输入保持一致(`thread:<id>`),且**只由 threadId 派生**——不含
|
|
60
|
+
* 实例信息、不含随机量,否则同一线程在不同请求上会算出不同的键,哈希立刻失效。
|
|
61
|
+
*/
|
|
62
|
+
export function stickyKeyForThread(threadId: string): string {
|
|
63
|
+
return `thread:${threadId}`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 终端/流式响应用的 sticky 头(诊断 + 排障;不被客户端当作鉴权依据)。 */
|
|
67
|
+
export function stickyHeadersForThread(threadId: string): Record<string, string> {
|
|
68
|
+
return {
|
|
69
|
+
[STICKY_KEY_HEADER]: stickyKeyForThread(threadId),
|
|
70
|
+
[INSTANCE_HEADER]: getInstanceId(),
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// AllBlue - 理想之海
|
|
3
|
+
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
+
//
|
|
5
|
+
// 终端前台进程组探测(P5 任务 4,母规格 §6.5 O2/O3)。
|
|
6
|
+
//
|
|
7
|
+
// node-pty 的 JS 面**没有** TIOCGPGRP ioctl(设计稿 O3 偏离的根因),因此拿不到内核
|
|
8
|
+
// 记录的「终端前台进程组」。这里用 `ps` 做只读探测:
|
|
9
|
+
// `ps -o tpgid=,pgid= -p <ptyPid>` → tpgid(该进程控制终端的前台进程组)
|
|
10
|
+
// `ps -o stat= -p <pgid>` → 前台组 leader 的状态字(S/R/T…)
|
|
11
|
+
//
|
|
12
|
+
// 两个用途:
|
|
13
|
+
// ① O3 —— 终止型信号只发给**前台进程组**(`kill(-pgid)`),绝不发给 shell 自身或
|
|
14
|
+
// 后台作业;tpgid 与 shell 进程组相同时(shell 在前台)一律拒(那等于关终端,
|
|
15
|
+
// 引导用户走 terminal_close)。
|
|
16
|
+
// ② O2 —— stdin readiness:前台命令处于可中断睡眠(STAT 首字母 S/I)时,说明它
|
|
17
|
+
// 大概率阻塞在读 stdin(交互提示、REPL、分页器)。**这是启发式提示,不是保证**
|
|
18
|
+
// (`sleep 10` 同样是 S),工具出参文案必须按「可能」表述。
|
|
19
|
+
//
|
|
20
|
+
// 安全取向:任何一步失败(ps 不存在/超时/输出异常/Windows)→ `unknown`,调用方
|
|
21
|
+
// fail-closed(O3 拒发信号、O2 不给提示),绝不回落到「猜一个 pgid 发下去」。
|
|
22
|
+
//
|
|
23
|
+
// 进程组语义注意:比较用的是 **pty 子进程的 pgid** 而非它的 pid——沙箱包装
|
|
24
|
+
// (sandbox-exec/bwrap)若未 exec 而 fork,pid 是包装器、进程组才是 shell 的;用
|
|
25
|
+
// tpgid===pgid 判定「shell 在前台」对这两种情形都成立。
|
|
26
|
+
|
|
27
|
+
import { execFile } from 'node:child_process'
|
|
28
|
+
|
|
29
|
+
/** 单次 ps 调用上限(探测是旁路信息,绝不拖慢终端操作)。 */
|
|
30
|
+
const PS_TIMEOUT_MS = 1_000
|
|
31
|
+
|
|
32
|
+
export interface ForegroundProbe {
|
|
33
|
+
/** shell = 前台就是 shell 自身;command = 有子进程在前台;unknown = 探测不可用。 */
|
|
34
|
+
kind: 'shell' | 'command' | 'unknown'
|
|
35
|
+
/** 前台进程组 id(kind='command' 时有值)。 */
|
|
36
|
+
pgid?: number
|
|
37
|
+
/** 前台组 leader 的 ps STAT(如 'S+'、'R'、'T');可能缺失(leader 已退出)。 */
|
|
38
|
+
state?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 可注入的探测器(测试替身;生产用 probeForeground)。 */
|
|
42
|
+
export type ForegroundProber = (ptyPid: number) => Promise<ForegroundProbe>
|
|
43
|
+
|
|
44
|
+
/** ps 执行器(测试注入替身;生产走 execFile)。 */
|
|
45
|
+
export type PsRunner = (args: readonly string[]) => Promise<string | null>
|
|
46
|
+
|
|
47
|
+
const UNKNOWN: ForegroundProbe = { kind: 'unknown' }
|
|
48
|
+
|
|
49
|
+
async function runPs(args: readonly string[]): Promise<string | null> {
|
|
50
|
+
return new Promise((resolve) => {
|
|
51
|
+
execFile('ps', [...args], { timeout: PS_TIMEOUT_MS }, (error, stdout) => {
|
|
52
|
+
if (error) {
|
|
53
|
+
resolve(null)
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
resolve(stdout)
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 探测终端(pty 子进程)的前台进程组。
|
|
63
|
+
*
|
|
64
|
+
* 返回 kind='shell' 表示 shell 在前台(可用控制字符安全交互,但终止型信号会打死
|
|
65
|
+
* shell 本身);kind='command' 表示有前台命令,pgid 可安全定向发信号。
|
|
66
|
+
*/
|
|
67
|
+
export async function probeForeground(ptyPid: number, run: PsRunner = runPs): Promise<ForegroundProbe> {
|
|
68
|
+
if (!Number.isInteger(ptyPid) || ptyPid <= 0) return UNKNOWN
|
|
69
|
+
|
|
70
|
+
const head = await run(['-o', 'tpgid=,pgid=', '-p', String(ptyPid)])
|
|
71
|
+
if (head === null) return UNKNOWN
|
|
72
|
+
const [tpgid, pgid] = head.trim().split(/\s+/).map((token) => Number.parseInt(token, 10))
|
|
73
|
+
if (!Number.isFinite(tpgid) || !Number.isFinite(pgid)) return UNKNOWN
|
|
74
|
+
// tpgid = -1 表示没有控制终端;<=1 是不可定向的非法组(1 = init/launchd)。
|
|
75
|
+
if (tpgid <= 1) return UNKNOWN
|
|
76
|
+
if (tpgid === pgid) return { kind: 'shell', pgid }
|
|
77
|
+
|
|
78
|
+
const statText = await run(['-o', 'stat=', '-p', String(tpgid)])
|
|
79
|
+
const state = statText?.trim().split(/\s+/)[0]
|
|
80
|
+
return state ? { kind: 'command', pgid: tpgid, state } : { kind: 'command', pgid: tpgid }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* stdin readiness 启发式:前台组 leader 处于可中断睡眠(S)或空闲(I)→ 大概率在等输入。
|
|
85
|
+
* unknown / shell 在前台 / 状态缺失 一律 false(不猜)。
|
|
86
|
+
*/
|
|
87
|
+
export function isAwaitingInput(probe: ForegroundProbe | undefined): boolean {
|
|
88
|
+
if (!probe || probe.kind !== 'command' || !probe.state) return false
|
|
89
|
+
return probe.state.startsWith('S') || probe.state.startsWith('I')
|
|
90
|
+
}
|
|
@@ -52,6 +52,7 @@ import type { SerializeAddon } from '@xterm/addon-serialize'
|
|
|
52
52
|
|
|
53
53
|
import type { WorkspaceRootResolution } from '@/server/harness/workspace-binder.server'
|
|
54
54
|
import { buildSubprocessEnv } from './subprocess-env.server'
|
|
55
|
+
import { probeForeground, type ForegroundProbe, type ForegroundProber } from './terminal-foreground.server'
|
|
55
56
|
import type { SandboxLaunch } from './sandbox/exec-backed-handle.server'
|
|
56
57
|
|
|
57
58
|
/**
|
|
@@ -388,6 +389,11 @@ export interface TerminalManagerOptions {
|
|
|
388
389
|
/** agent 终端并发上限(默认 4,设计 §5.4):仅 running ∧ agent-control 占额。 */
|
|
389
390
|
maxAgentTerminalsPerThread?: number
|
|
390
391
|
maxInputBytes?: number
|
|
392
|
+
/**
|
|
393
|
+
* 前台进程组探测器(P5 任务 4,§6.5 O2/O3):缺省用 `ps` 只读探测
|
|
394
|
+
* (terminal-foreground.server.ts);测试注入替身,避免依赖真实进程树。
|
|
395
|
+
*/
|
|
396
|
+
probeForeground?: ForegroundProber
|
|
391
397
|
}
|
|
392
398
|
|
|
393
399
|
/** globalThis 单例槽位(HMR 重复构造防护,模式同 host.server.ts)。 */
|
|
@@ -799,6 +805,7 @@ export function createTerminalManager(options: TerminalManagerOptions = {}): Ter
|
|
|
799
805
|
export class TerminalManager {
|
|
800
806
|
private readonly instances = new Map<string, TerminalInstance>()
|
|
801
807
|
private readonly spawnPty: TerminalManagerOptions['spawnPty']
|
|
808
|
+
private readonly probeForegroundOf: ForegroundProber
|
|
802
809
|
private readonly now: () => number
|
|
803
810
|
private readonly pollIntervalMs: number
|
|
804
811
|
private readonly idleKillMs: number
|
|
@@ -810,6 +817,7 @@ export class TerminalManager {
|
|
|
810
817
|
|
|
811
818
|
constructor(options: TerminalManagerOptions = {}) {
|
|
812
819
|
this.spawnPty = options.spawnPty ?? createDefaultSpawnPty()
|
|
820
|
+
this.probeForegroundOf = options.probeForeground ?? probeForeground
|
|
813
821
|
this.now = options.now ?? (() => Date.now())
|
|
814
822
|
this.pollIntervalMs = options.pollIntervalMs ?? ACTIVITY_POLL_MS
|
|
815
823
|
this.idleKillMs = options.idleKillMs ?? IDLE_KILL_MS
|
|
@@ -1102,9 +1110,10 @@ export class TerminalManager {
|
|
|
1102
1110
|
}
|
|
1103
1111
|
|
|
1104
1112
|
/**
|
|
1105
|
-
* agent 信号(§5.3 / §6.2
|
|
1106
|
-
*
|
|
1107
|
-
*
|
|
1113
|
+
* agent 信号(§5.3 / §6.2,O3 偏离已收口——见 agentSignalForeground,P5 任务 4):
|
|
1114
|
+
* SIGINT→\x03、SIGTSTP→\x1a(控制字符送达)。终止型 SIGTERM/SIGKILL/SIGHUP **不再**
|
|
1115
|
+
* 在这里统一拒——由 agentSignalForeground 定向到前台进程组;本方法对它们的拒绝
|
|
1116
|
+
* 保留为兜底(直接调用方仍拿不到「乱发信号」的路径)。
|
|
1108
1117
|
*/
|
|
1109
1118
|
agentSignal(terminalId: string, signal: TerminalAgentSignal): { delivered: true; method: 'control-char' } {
|
|
1110
1119
|
const inst = this.requireAgentControl(terminalId)
|
|
@@ -1124,6 +1133,72 @@ export class TerminalManager {
|
|
|
1124
1133
|
return { delivered: true, method: 'control-char' }
|
|
1125
1134
|
}
|
|
1126
1135
|
|
|
1136
|
+
/**
|
|
1137
|
+
* 前台进程组探测(P5 任务 4 / §6.5 O2):只读,供 stdin readiness 提示与 UI 展示。
|
|
1138
|
+
* 终端不存在/已退出 → undefined(不抛:这是旁路信息,不参与控制流)。
|
|
1139
|
+
*/
|
|
1140
|
+
async foregroundOf(terminalId: string): Promise<ForegroundProbe | undefined> {
|
|
1141
|
+
const inst = this.instances.get(terminalId)
|
|
1142
|
+
if (!inst || inst.exitCode !== null || inst.closing) return undefined
|
|
1143
|
+
const pid = (inst.pty as { pid?: unknown }).pid
|
|
1144
|
+
if (typeof pid !== 'number') return undefined
|
|
1145
|
+
try {
|
|
1146
|
+
return await this.probeForegroundOf(pid)
|
|
1147
|
+
} catch {
|
|
1148
|
+
return undefined
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/**
|
|
1153
|
+
* 终止型信号定向送达(P5 任务 4 / §6.5 O3 收口):只发给**前台进程组**
|
|
1154
|
+
* (`kill(-pgid)`),绝不发给 shell 自身或后台作业。
|
|
1155
|
+
*
|
|
1156
|
+
* 判定与拒发(一律 fail-closed,错误码沿用 invalid_signal 供工具层映射):
|
|
1157
|
+
* - 前台就是 shell → 拒(那等价于关终端;引导 terminal_close);
|
|
1158
|
+
* - 探测不可用(ps 缺失/超时/无控制终端)→ 拒(绝不猜一个 pgid 发下去);
|
|
1159
|
+
* - 组已消失(ESRCH)→ not-running(进程已不在);
|
|
1160
|
+
* - 无权限(EPERM)→ 拒并保留原引导。
|
|
1161
|
+
*
|
|
1162
|
+
* 这不是 TIOCGPGRP(node-pty JS 面无 ioctl):pgid 由 `ps -o tpgid=` 读出,语义等价
|
|
1163
|
+
* 但依赖 ps 可用性——因此探测失败即拒,而不是退回控制字符。
|
|
1164
|
+
*/
|
|
1165
|
+
async agentSignalForeground(
|
|
1166
|
+
terminalId: string,
|
|
1167
|
+
signal: TerminalAgentSignal,
|
|
1168
|
+
): Promise<{ delivered: true; method: 'foreground-group'; pgid: number }> {
|
|
1169
|
+
const inst = this.requireAgentControl(terminalId)
|
|
1170
|
+
const pid = (inst.pty as { pid?: unknown }).pid
|
|
1171
|
+
const probe = typeof pid === 'number' ? await this.probeForegroundOf(pid) : { kind: 'unknown' as const }
|
|
1172
|
+
if (probe.kind !== 'command' || typeof probe.pgid !== 'number') {
|
|
1173
|
+
throw new TerminalManagerError(
|
|
1174
|
+
'invalid_signal',
|
|
1175
|
+
probe.kind === 'shell'
|
|
1176
|
+
? `信号 ${signal} 只能定向到前台命令;当前前台是 shell 自身(发信号等于关闭终端)。请改用 terminal_close,或先在前台运行命令。`
|
|
1177
|
+
: `信号 ${signal} 需要定位终端前台进程组,但当前无法探测(无控制终端或 ps 不可用)。请改用 SIGINT(控制字符)或 terminal_close。`,
|
|
1178
|
+
)
|
|
1179
|
+
}
|
|
1180
|
+
try {
|
|
1181
|
+
process.kill(-probe.pgid, signal)
|
|
1182
|
+
} catch (err: unknown) {
|
|
1183
|
+
const code = (err as { code?: string }).code
|
|
1184
|
+
if (code === 'ESRCH') {
|
|
1185
|
+
throw new TerminalControlError(
|
|
1186
|
+
'terminal/control-unavailable',
|
|
1187
|
+
'not-running',
|
|
1188
|
+
`前台进程组已不存在(命令可能刚退出):${terminalId}`,
|
|
1189
|
+
)
|
|
1190
|
+
}
|
|
1191
|
+
if (code === 'EPERM') {
|
|
1192
|
+
throw new TerminalManagerError(
|
|
1193
|
+
'invalid_signal',
|
|
1194
|
+
`无权向该终端前台进程组发送 ${signal}(权限不足)。请改用 SIGINT,或用 terminal_close 关闭终端。`,
|
|
1195
|
+
)
|
|
1196
|
+
}
|
|
1197
|
+
throw err
|
|
1198
|
+
}
|
|
1199
|
+
return { delivered: true, method: 'foreground-group', pgid: probe.pgid }
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1127
1202
|
/**
|
|
1128
1203
|
* agent 关闭(§5.3,DSH §5.4 三态):调用开始查一次 control——已接管(或用户终端)不杀、
|
|
1129
1204
|
* 实例保留(进程留给用户,control='user' 已自然从 agent 可见集合除名)返回
|
|
@@ -60,6 +60,11 @@ export const HARNESS_TOOL_FEATURE_MAP: Record<string, FeatureKey> = {
|
|
|
60
60
|
send_message: 'customAgents',
|
|
61
61
|
wait_agent: 'customAgents',
|
|
62
62
|
interrupt_agent: 'customAgents',
|
|
63
|
+
// P5 任务 1:workflow 派发子代理,与 team/subagent 同口径复用 customAgents。
|
|
64
|
+
workflow_start: 'customAgents',
|
|
65
|
+
workflow_list: 'customAgents',
|
|
66
|
+
workflow_view: 'customAgents',
|
|
67
|
+
workflow_cancel: 'customAgents',
|
|
63
68
|
}
|
|
64
69
|
|
|
65
70
|
/**
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { readBoundedBody } from '../body.server'
|
|
4
|
+
import { WEBHOOK_MAX_BODY_BYTES } from '../types'
|
|
5
|
+
|
|
6
|
+
function requestWithLengthCheck(body: string, declaredLength: string): Request {
|
|
7
|
+
const request = new Request('http://localhost/api/harness/webhook/token', {
|
|
8
|
+
method: 'POST',
|
|
9
|
+
body,
|
|
10
|
+
})
|
|
11
|
+
// 覆盖 content-length 以模拟伪造/缺失声明
|
|
12
|
+
const headers = new Headers(request.headers)
|
|
13
|
+
headers.set('content-length', declaredLength)
|
|
14
|
+
return new Request(request.url, { method: 'POST', body: request.body, headers, duplex: 'half' } as RequestInit)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('有界 body 摄取', () => {
|
|
18
|
+
it('正常体读取完整字节', async () => {
|
|
19
|
+
const payload = '{"ok":true}'
|
|
20
|
+
const result = await readBoundedBody(
|
|
21
|
+
new Request('http://localhost/hook', { method: 'POST', body: payload }),
|
|
22
|
+
)
|
|
23
|
+
expect(result.ok).toBe(true)
|
|
24
|
+
if (!result.ok) return
|
|
25
|
+
expect(new TextDecoder().decode(result.bytes)).toBe(payload)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('声明长度超限即拒(不读 body)', async () => {
|
|
29
|
+
const result = await readBoundedBody(
|
|
30
|
+
requestWithLengthCheck('{}', String(WEBHOOK_MAX_BODY_BYTES + 1)),
|
|
31
|
+
)
|
|
32
|
+
expect(result).toEqual({ ok: false, reason: 'too_large' })
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('流式累计超限即拒(伪造小 content-length 也拦下)', async () => {
|
|
36
|
+
const chunk = new Uint8Array(64 * 1024)
|
|
37
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
38
|
+
start(controller) {
|
|
39
|
+
// 20 × 64KiB = 1.25 MiB,超过 1 MiB 上限
|
|
40
|
+
for (let index = 0; index < 20; index += 1) controller.enqueue(chunk)
|
|
41
|
+
controller.close()
|
|
42
|
+
},
|
|
43
|
+
})
|
|
44
|
+
const request = new Request('http://localhost/hook', {
|
|
45
|
+
method: 'POST',
|
|
46
|
+
body: stream,
|
|
47
|
+
duplex: 'half',
|
|
48
|
+
} as RequestInit)
|
|
49
|
+
const result = await readBoundedBody(request, WEBHOOK_MAX_BODY_BYTES)
|
|
50
|
+
expect(result).toEqual({ ok: false, reason: 'too_large' })
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('恰好等于上限时放行(边界含等号)', async () => {
|
|
54
|
+
const size = 1024
|
|
55
|
+
const result = await readBoundedBody(
|
|
56
|
+
new Request('http://localhost/hook', { method: 'POST', body: new Uint8Array(size) }),
|
|
57
|
+
size,
|
|
58
|
+
)
|
|
59
|
+
expect(result.ok).toBe(true)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('非法 content-length 视为不可读', async () => {
|
|
63
|
+
const result = await readBoundedBody(requestWithLengthCheck('{}', 'not-a-number'))
|
|
64
|
+
expect(result).toEqual({ ok: false, reason: 'unreadable' })
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('空 body 返回空字节(不报错)', async () => {
|
|
68
|
+
const result = await readBoundedBody(new Request('http://localhost/hook', { method: 'POST' }))
|
|
69
|
+
expect(result.ok).toBe(true)
|
|
70
|
+
if (!result.ok) return
|
|
71
|
+
expect(result.bytes.byteLength).toBe(0)
|
|
72
|
+
})
|
|
73
|
+
})
|