Skip to content

feat(message): wire the inbound chain end to end (B2/B3/B4/B5) - #6

Closed
TyperBody wants to merge 6 commits into
feat/project-review-and-pr-qafrom
agent/wgc/p0-message-chain
Closed

TyperBody wants to merge 6 commits into
feat/project-review-and-pr-qafrom
agent/wgc/p0-message-chain

Conversation

@TyperBody

@TyperBody TyperBody commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

What changed

Wires the inbound chain that the review found built-but-uncalled. One commit, on
top of feat/project-review-and-pr-qa (base of PR #3) — nothing from PR #3 is
merged in, only added.

  • B3 ingest: POST /api/v1/messages stores and routes. 201 new, 200 replayed
    key, 400 on missing fields.
  • B4 idempotency (same batch, as required — the route alone makes message VOKO 原生支持A2A协议,让不同类型的 Agent 跨域跨平台进行即时通信(IM)与协作的本地运行时。 #2
    fail): IdempotencyKey is *string, Create generates a fallback key when
    none is supplied, and a concurrent duplicate re-reads instead of returning the
    constraint error. migrations/003 rewrites existing '' to NULL and is
    re-runnable.
  • B2 WebSocket wiring: Services owns a Hub. /ws/app hands the socket to
    the dispatcher's read/write pumps; /ws/adapter uses a register-only path
    because that handler already owns its reader and single writer, so a second
    pump pair would race the socket. Frames are persisted then routed, and the
    outcome is stored (received / routed / delivered).
  • B5 command dispatch: create → claim → send → MarkSent, or MarkFailed
    into retrying, plus a 30s retry sweep. The frame is the flat bridge protocol
    (command_type + payload.cid/toid/text), not a v3 envelope — bridges drop
    envelopes as 指令缺少 cid/toid.
  • m1: rules load into the hub at startup and re-sync on every write, so an
    edit takes effect on the next message rather than the next restart.

Why

internal/message had zero importers; both sockets only echoed; /messages had
no POST so MessageService.Create was unreachable. The pieces were reachable
individually and worthless together.

Evidence

Before, on a build of the base commit: POST /messages → 404, and a second
row with an empty idempotency_key → UNIQUE constraint failed. After, against a
running server:

POST /messages x3 (no key)      -> 201 201 201
POST /messages (same key) x2    -> 201 then 200, one row
bridging frame -> app socket    -> app receives message.received
stored status                   -> delivered
POST /commands, nobody there    -> retrying, retry_count 1
POST /commands, bridge there    -> sent, sent_at set, bridge receives the frame

Each test was confirmed to fail with the fix reverted (B4 → two rows collapse to
one; B2 → app socket times out; B5 → stays created).

Verification

  • CGO_ENABLED=1 go test ./... — all pass
  • go vet ./... clean
  • gofmt -l empty
  • golangci-lint run — 0 issues
  • migration applied to a pre-fix database and re-applied (3 keyless messages afterwards, all 201)

Docs

api-reference.md gains the endpoint and status table; bridge-protocol.md
records the command frame shape; functional-review.md marks B2–B5 and m1 fixed.

Protocol impact

No v3 envelope or signing change. The command frame written to bridges matches the
existing bridge protocol document and both reference bridges.

Known, not fixed here

M1 (per-user data isolation) is still open and out of scope. The adapter handler
still takes instance_id from the query string without verifying it — that is M4.

CI

All four jobs green on the head commit (backend, frontend, generated, format-lint).

One wrinkle worth recording: this PR opened with zero workflow runs. on.pull_request.branches matches the base, and CI was still limited to main, so every PR stacked on the integration branch silently had no checks at all — a green by not running. 8e764e7 on the base branch added feat/project-review-and-pr-qa to the trigger list; the second commit here is an empty retrigger so the checks actually execute against this diff.

TyperBody and others added 2 commits November 7, 2026 18:12
Three P2 correctness items from the functional review, plus the handler tests
that pin them.

M11 — deleting/acking a missing resource answered 200. Eight repository
Deletes and the two UpdateStatus methods now return gorm.ErrRecordNotFound when
RowsAffected is 0, so "it said deleted but nothing happened" is gone. Live
before/after: DELETE /routes/nope, POST /messages/nope/ack, DELETE
/platforms/nope all 200 -> 404; deleting a row that exists still 200.

M12 — every service error collapsed into 400 (or 500 on delete). Added
ErrNotFound / ErrConflict / ErrValidation sentinels and a single handler
respondError mapping to 404/409/400/500. Wrapped the raw gorm error instead of
echoing "record not found" as a 400 body; 404 and 500 answer generic text,
409/400 keep the specific reason ("username already exists"). Registration and
admin user-create duplicates now 409.

M10 — Monitoring mapped instance.last_heartbeat / message_count / error_count
while AdapterInstance had none of them, so the page was permanently 0. Added
the three columns (migration 003, backfilled from adapter_sessions for the
heartbeat), maintained message/error counters on WS ingest and gateway
persistence, and refreshed the heartbeat on handshake and process start.

M13 — internal/handler had no tests at all. Added sqlite-backed httptest cases
for the 404/409/400 contract and the metric field round-trip; removing the
respondError mapping fails four of them.

Docs: api-reference error-code rules and instance fields, functional-review
fix markers.

Co-authored-by: multica-agent <github@multica.ai>
The layers existed but nothing called them: `internal/message` had zero
importers, both WebSocket routes only echoed, `/messages` had no POST so
`MessageService.Create` was unreachable, and `CreateCommand` was a write-only
log. Fixing the ingest route alone would have made the second keyless message
500, so B3 and B4 land together.

- B3: `POST /api/v1/messages` persists and routes. 201 for a new event, 200 for
  a replayed `idempotency_key`, 400 on missing fields.
- B4: `IdempotencyKey` becomes `*string` and `Create` generates a fallback key
  when the caller supplies none — a UNIQUE index allows one `''` but many NULLs.
  A concurrent duplicate re-reads instead of surfacing the constraint error.
  `migrations/003` rewrites existing `''` rows to NULL; verified re-runnable.
- B2: `Services` owns a `Hub`; `/ws/app` hands the socket to the dispatcher's
  pumps, `/ws/adapter` uses a register-only path because it already has its own
  reader and single writer. Frames are persisted then routed; the routing
  outcome lands on the row (`received`/`routed`/`delivered`).
- B5: `CreateCommand` claims the row (`ClaimForDispatch`, which stops the retry
  sweep from double-sending it), dispatches, then `MarkSent`, or `MarkFailed`
  into `retrying` with a 30s sweep. The frame is the flat bridge protocol
  (`command_type` + `payload.cid/toid/text`), not a v3 envelope — bridges drop
  envelopes as "指令缺少 cid/toid".
- m1: rules load into the hub at startup and re-sync after every write.

Tests fail without the fix, verified by reverting each piece: two keyless
messages store two rows, a bridge frame reaches a different app socket and the
row says `delivered`, and a command is `sent` with `sent_at` set or `retrying`.

Docs: api-reference gains the endpoint and its status codes, bridge-protocol
records the command frame shape, functional-review marks B2-B5/m1 fixed.

Co-authored-by: multica-agent <github@multica.ai>
@TyperBody TyperBody closed this Nov 7, 2026
@TyperBody TyperBody reopened this Nov 7, 2026
TyperBody and others added 4 commits November 7, 2026 19:36
…opened)

Co-authored-by: multica-agent <github@multica.ai>
Closes the review's P1 set (M2, M3, M4, M15) on top of the PR QA branch.

M2 — CORS echoed a fixed `*` alongside `Allow-Credentials: true`, which is
unusable: a wildcard origin forbids credentials. The configured Origin is now
echoed back (plus `Vary: Origin`), and only when it is in the allowlist, so
`Allow-Credentials` becomes meaningful and a future Cookie session keeps
working.

M4 — the WebSocket upgraders accepted any origin and the two /ws routes sat
behind no middleware at all, so knowing an instance_id or app_id was enough to
open a socket. Handshakes now require a valid JWT before the upgrade (401
otherwise) and check the same Origin allowlist as CORS (403 for a foreign
origin). The adapter gateway upgrader takes the list through
GatewayConfig.AllowedOrigin. Tokens are accepted via ?token= (Python bridges,
updated here), Authorization: Bearer, or the `espl` subprotocol, which is the
only header a browser can set on a WebSocket. Requests without an Origin are
non-browser clients and pass.

M3 — the shipped JWT secret was used with no check. Startup now WARNs while the
placeholder (or an empty secret) is in place, with a fix hint. A prefix
comparison would misfire, so a secret that merely contains the placeholder text
still counts as rotated.

M15 — http.Server had only Addr and Handler. All four timeouts are wired from
config, and a global MaxBodyBytes middleware caps request bodies: a declared
oversize is refused with 413 up front, an undeclared one is caught by
http.MaxBytesReader.

One `security.allowed_origins` list drives CORS, both socket upgraders and the
gateway, so they cannot drift; ESP_SECURITY_ALLOWED_ORIGINS overrides it
without editing the file. Every item has a test, including the cases that used
to pass silently (garbage token accepted, foreign origin accepted).

Docs touched: api-reference (WS auth table, CORS, limits, 413),
SECURITY, CONTRIBUTING, and the review's own status marks.

Co-authored-by: multica-agent <github@multica.ai>
P0 (#6) and P2 (#4) both branch off the integration branch and touch
overlapping files, so whichever merges second hits conflicts. Resolving
them here rather than in a second PR keeps the pair mergeable.

Three conflicts, plus one the CI-only view would have missed:

- internal/service/route.go — keep P2's ErrNotFound wrap AND P0's
  notifyChange(), so a delete still 404s and still refreshes the rule cache
- internal/service/message.go — union: P2's RecordInbound/RecordHeartbeat/
  RecordError sit alongside P0's CreateAndRoute, and the missing brace at
  the junction is fixed
- migrations — P2's counters migration keeps 003, P0's idempotency
  rebuild becomes 004, README table renumbered
- internal/handler — both PRs added an identical TestMain and the package
  failed with "multiple definitions of TestMain"; kept one, dropped the
  now-unused imports

Verified on the merged tree: three keyless POSTs 201/201/201 with four
distinct keys in the table, same key twice 201 then 200 with one row,
missing field 400, all migrations apply in order on a fresh DB and the
idempotency rebuild still applies over an already-migrated one.
go vet, golangci-lint (0 issues), gofmt and the full test suite pass.
Third stacked PR; P1 (#5) and P0 (#6) both touch websocket.go and its
test, so the pair only merges with resolution. Same treatment as the P2
merge: union the two sides rather than pick.

- websocket.go: both imports (P0 needs message, P1 needs middleware);
  both sockets keep the pre-upgrade authenticateWS check
- websocket_test.go: keep P0's hub fixtures and P1's handshake-auth and
  Origin cases in one file, with P1's helper renamed to dialPlain to
  avoid the method-name collision, and one TestMain
- P0's fixture dials now carry a token, since the handshake refuses an
  unauthenticated upgrade; the separator is & because the path already
  has a query string
- functional-review.md: combine the P2 and P1 fix-list annotations

Verified on one build with all three PRs: three keyless ingests 201/201/
201, duplicate register 409, delete-missing 404, cross-origin preflight
without Allow-Origin, 8 MB body 413, WS without token 401.
go vet, gofmt (0), golangci-lint (0 issues) and the full suite pass.
@TyperBody TyperBody closed this Nov 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant