Skip to content

Add Rive workflow Maka tool - #1

Merged
likun666661 merged 2 commits into
mainfrom
yunpei/rive-workflow-tool
Jun 8, 2026
Merged

likun666661 merged 2 commits into
mainfrom
yunpei/rive-workflow-tool

Conversation

@likun666661

Copy link
Copy Markdown
Member

Summary

  • Add a permission-gated RiveWorkflow MakaTool registered with the existing builtin tools.
  • Add a main-process Rive CLI bridge with shell-free argv construction, timeout/abort handling, JSON envelope parsing, stdout/stderr tails, and secret redaction.
  • Return/store only Rive projection refs and summaries: workflow_run_id, scheduler_run_id, root_work_node_id, state, protocol/display refs. Rive remains the source of truth.
  • Mark rive_workflow tool results with ok: false as tool errors while keeping the default backend unchanged.

Boundaries

  • MakaTool-first integration only; no RiveBackend, no BackendKind default-path changes.
  • Maka does not read or write .rive SQLite directly.
  • Success is parsed from Rive workflow/scheduler/work protocol projections only; stdout/final answers/debug trace are diagnostic only.
  • Tool remains permissionRequired=true with existing custom_tool category; no new PermissionMode/ToolCategory.

Validation

  • node --test apps/desktop/dist/main/__tests__/rive-workflow-tool.test.js
  • npm --workspace @maka/desktop test
  • npm run typecheck
  • git diff --check
  • Real bridge smoke with local Rive binary: imported sentinel workflow and ran workflow run --no-scheduler, returning wfrun_b22a7014a5964f9590dc5d222f82537e and root work_0dd8e658edaf477c806b4ac4ae209e7f in instantiated state.

@likun666661
likun666661 merged commit 487f9c0 into main Jun 8, 2026
@Astro-Han

Astro-Han commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Rive Workflow: where to take this next

Good integration. The design calls I like most: shell-free argv against injection, commandId for idempotency, and only exposing projection refs instead of the full envelope. That last one is important because it forces the agent to query fresh state instead of acting on whatever's cached in context.

I compared this with Claude Code's built-in Workflow. There are real tradeoffs on both sides, thought it'd be good to talk through them.

Where Rive wins

Durability. State lives in the SQLite ledger and survives across sessions. scheduler_resume picks up after crashes. CC Workflow is in-memory only; session dies, workflow dies.

Multi-runner scheduling. Same workflow can mix opencode/codex workers. CC is locked to Claude subagents.

Idempotency. commandId is a first-class concept. CC uses prompt hash matching for resume, which isn't real idempotency.

Some things I've been thinking about

1. Agent call complexity

The tool has 17 parameters. The full flow is validate → import → run → poll status, 6 steps minimum. CC Workflow's agent(prompt, {schema}) is two parameters, one step.

LLMs are bad at filling complex structured parameters precisely. The more fields and conditional constraints (workers required when scheduler is enabled, commandId required only for mutating actions), the more likely the model gets something wrong. As long as the interface is one tool call with many parameters, agent reliability takes the hit. Not sure if there's a clean way around this on the Rive side, but figured it's worth flagging.

2. Overhead for lightweight tasks

"Scan 5 files for bugs in parallel" doesn't need a template, a ledger, or a 6-step ceremony. First users will probably start with lightweight parallel use cases like this. Rive's durability doesn't buy them anything there.

3. External binary dependency

Requiring a separate Rive binary install is friction CC Workflow doesn't have (it's built-in). Might slow early adoption.

Positioning and priority

We want to position this as the open-source CC Workflow. That's how people will find us and understand what we do. Nobody searches for "lightweight workflow orchestration" — but "open-source Claude Code Workflow" is immediately clear and has viral potential.

That framing sets the technical priority: DX parity with CC Workflow is P0. If we claim the "open-source CC Workflow" tag but the experience is 17 parameters and 6 steps where CC is 2 parameters and 1 step, the comparison hurts us instead of helping us. We need to close that gap before we can credibly own the label.

Rive's durability, multi-runner scheduling, and idempotency become the "and it does more" story on top of CC parity — not the main pitch.

Proposed direction

  1. Add a lightweight in-process orchestration layer inside ai-sdk backend, similar to CC's agent() / parallel(). No external dependency. Covers the lightweight parallel cases out of the box. This is the P0 — it's what makes the "open-source CC Workflow" tag credible.
  2. Simplify the Rive tool parameters with smart defaults so the agent fills fewer fields.
  3. Longer term, smart routing: lightweight tasks stay in-process, long-running or durable tasks escalate to Rive automatically.

Would love to hear how you see this. Especially whether simplifying the Rive parameter surface is feasible on your end and how a lightweight orchestration layer might fit into the current architecture.

@jackwener
jackwener deleted the yunpei/rive-workflow-tool branch June 15, 2026 13:23
jackwener pushed a commit that referenced this pull request Jun 21, 2026
jackwener pushed a commit that referenced this pull request Jun 21, 2026
jackwener added a commit that referenced this pull request Jun 21, 2026
PR77 (message meta) + PR76 follow-ups @kenji flagged:

**Message meta**: replaces the bare role-label `<span>` with a
`MessageMeta` component that renders [avatar][role name][timestamp]
inline. Avatar is a small (22px) tinted circle with the initial
glyph — uses the first non-ASCII codepoint when available, so userLabel
"建文" → 建, "JK" → J, "🦊 fox" → 🦊. Assistant gets a fixed "M". Per
role data-attr the circle uses the matching token (chat-user-bg for
user, accent-tinted for assistant, info-tinted for system).

**Tool output redaction (@kenji PR76 follow-up #1)**: `OverlayPreview`
now runs `redactSecrets` over `text` / `json` payloads and the
`FileDiffPreview` body. `TerminalPreview` redacts cwd-adjacent `cmd`
string + stdout + stderr — `$ curl -H "X-API-Key: ..." …` lines and
provider dumps go through the masker before display. Pairs with the
existing copy-error redaction in ToolErrorBanner (PR58 / PR60); both
display and copy paths are now consistent.

**Tool output truncation (@kenji PR76 follow-up #2)**: introduces
`TOOL_LINE_CAP = 500` + `capLines()`. file_diff body, terminal
stdout, terminal stderr, and plain text all slice to 500 lines and
append a "… N more lines hidden" marker. Prevents a single
megabyte-scale `npm test` failure from creating 10k React elements
and drowning the chat surface.

@maka/ui + desktop typecheck + build + tests green.
jackwener added a commit that referenced this pull request Jun 21, 2026
…doc-merge)

1. **iframe sandbox/CSP language tightened** (@kenji #1):
   - Remove the "separate webContents partition + permissive CSP for
     iframe" promise — DOM `<iframe>` doesn't get an independent
     partition without `<webview>` / BrowserView. Don't promise what
     the DOM can't deliver.
   - Add `allow-forms` and `allow-modals` to the not-allowed list
   - Switch from `src="file://..."` to `srcdoc={await readText()}` so
     content delivery goes through the path-guard read helper
   - Note that global CSP `default-src 'self'` stays locked — sandbox
     attribute carries all isolation

2. **Symlink-aware path guard** (@kenji #2):
   - Both `realpath(artifactRoot)` AND `realpath(target)` required,
     then containment check
   - Mirror PR56 open-path-guard which already has symlink-escape +
     `..` + URL-scheme test coverage

3. **readBinary MIME allow-list** (@kenji #3):
   - Allowlist: image/png/jpeg/gif/webp/svg+xml, application/pdf
   - MIME sniffed at read time, NOT trusted from record.kind or
     record.mimeType
   - Unknown → `reason: 'unsupported_mime'` + UI shows metadata +
     "在 Finder 中打开" / "另存为" actions (no raw bytes to renderer)

4. **Deleted tombstone blocks reads** (@kenji #4):
   - `status: 'deleted'` records immediately return `reason: 'deleted'`
     from readText / readBinary — even if the underlying file still
     exists on disk
   - Surface table updated: deleted row preview shows "此 artifact 已
     删除,预览已停止"
   - Permanent path purge is a separate Settings · 数据 flow

5. **PR108c runtime hook scope** (@kenji #5):
   - First version does NOT do LLM extractor
   - Only deterministic outputs: Write→file record, Edit→diff record,
     Bash with explicit redirect → file record
   - stdout/stderr NOT auto-promoted (noise)
   - LLM extractor (parse ```html``` from assistant message) deferred
     to PR109+

Also: type rename `storagePath` → `relativePath` to enforce contract
in the type system; full reason union widened on both read helpers.

doc total: 1416 lines.
jackwener added a commit that referenced this pull request Jun 21, 2026
Consumes @xuan's PR109c turn-level contract. Splits into three pieces
per @kenji review (smaller PR landing earlier):

**(a) deriveTurnLineageMap test coverage**
@xuan already shipped the helper in @maka/ui/materialize.ts; PR109d
adds 8 invariant cases to the existing test file:
- empty map when no descendants
- retriedTo-only / regeneratedTo-only branches
- multi-retry last-wins (matches current helper shape)
- mixed retry + regenerate
- multiple origins
- bare turn list returns empty map
- helper is pure (input not mutated)

**(b) Turn footer action matrix**
New pure helper `deriveTurnFooterActions()` at
`apps/desktop/src/renderer/turn-footer-actions.ts`. Matrix per @kenji
review gate #1: footer enabled set comes only from `TurnStatus` +
lineage state, NEVER from text content guesses.

Status → enabled set:
- `running`     → 复制
- `completed`   → 重新生成 / 分支 / 复制
- `failed`      → 重试 / 分支 / 复制
- `aborted`     → 重试 / 分支 / 复制

`copy` separately gated on `hasContent` — empty turns disable it
regardless of status.

13 node:test cases lock the matrix + tooltip Chinese-only + enum
non-leakage + `alreadyRetried` hint variation + multi-status
invariants.

New @maka/ui `<TurnFooterActions>` component (icon+text per @kenji
+ @xuan: not pure-icon hover toolbar, so check-a11y stays happy):
buttons render disabled when not enabled but stay visible so the
user sees what actions exist on the turn. Local clipboard write for
`copy`; other actions bubble to `onTurnFooterAction(turnId, actionId)`.

`ChatView` gains `turnFooterActionsByTurn` + `onTurnFooterAction`
props. Renderer (main.tsx) computes the per-turn matrix from
materialized turns + lineage map and routes button clicks to the
new IPCs (`sessions:retryTurn` / `sessions:regenerateTurn` /
`sessions:branchFromTurn`).

**(c) Aborted turn marker**
TurnView renders a small "(已中断)" italic + muted `Ban` icon block
above the assistant message body when `turn.status === 'aborted'`.
Per @kenji gate #2: aborted is dormant history, NOT a destructive
error tone — uses muted styling, not red.

CSS:
- `.maka-turn-aborted-marker` — muted background + Ban icon
- `.maka-turn-footer` + `.maka-turn-footer-action` — pill row of
  icon+text buttons; disabled state via opacity 0.45

Tests: 213 → 226 desktop passing (+13 footer matrix). check-a11y 0
violations.

Deferred to PR109e / PR109f:
- failed turn AlertOctagon + generalizedErrorMessage banner
- lineage badges (forward "重试自 turn X" + reverse derive
  "已重试 → turn Y")
- branched session banner with "从中断前分支" copy
- `turn-control-history` fixture + smoke Path 15
jackwener added a commit that referenced this pull request Jun 21, 2026
Two blocker findings from @kenji's contract-consumer review of A2
addressed:

**Blocker #1: user-facing copy no longer leaks internal PR / IPC
terms.** Every JSX-rendered string referencing `PR-CU-*`, `PR-HC-*`,
`PR-REAL-*`, `typed action IPC`, or `ToolOutputDelta` is replaced
with product language. PR-tracking references survive only in
JSDoc / code comments, where they belong.

  - Permission Center footnote: "正在 PR-CU-0 / PR-CU-1(Computer Use
    原生 helper)路上,落地后会替换这里的只读视图。" →
    "权限引导模块(Computer Use 原生 helper)接入后会替换这里的只读视图。"
  - Permission Center action hint titles:
    "操作入口等 PR-CU-0/1 typed action IPC 接入后可用" →
    "权限引导模块接入后提供"
  - Permission Center audit slot empty state:
    "审计日志将在 PR-REAL-3 接入后显示。" → "审计日志接入后显示。"
  - Health Center hard-rule p tag:
    "凭据测试只属于 validation 层,运行态需要 PR-REAL-4 接入实测探测。" →
    "凭据测试只属于 validation 层,运行态需要运行态探测接入后实测。"
  - Health Center footnote:
    "操作入口等 PR-HC-2 typed action IPC 接入后可用。所有真正的运行态探测
    (PR-REAL-4 ToolOutputDelta + send/stream/abort smoke)落地后会自动
    出现在「运行态探测」层。" →
    "运行态修复操作接入后显示。所有真正的运行态探测落地后会自动出现
    在「运行态探测」层。"

**Blocker #2: CAPABILITY_READINESS_COPY.enabled.detail no longer
overpromises runtime probe.** A2 is a read-only consumer; whether
`runtimeProbe.state` is `not_available` / `not_run` / `passed` is
already shown separately in the per-layer breakdown below the
summary pill. The summary copy must not synthesize a conclusion
the snapshot didn't make.

  - "配置、权限、运行态探测都已通过。" →
    "当前快照标记为可用,具体层级见下方。"

The runtime probe layer remains the single source of truth for
"是否运行态通过"; the summary pill's `detail` now defers to it
rather than asserting it.

@kenji non-blocking follow-up #3 (`toLocaleString()` host-locale
drift) deferred to when Permission/Health pages enter visual smoke
— mirrors the `MAKA_VISUAL_SMOKE_LOCALE` deterministic-formatter
pattern. Not blocking A2 since A2 carries no screenshot baseline.

332 desktop tests pass; typecheck + check-a11y + check-console
clean. No behavior change beyond copy.
jackwener added a commit that referenced this pull request Jun 21, 2026
Two blockers from @kenji's review of B1-a1 fixed:

**Blocker #1 — visual-smoke day-period determinism**

LAYOUT-4's `EmptyChatHero` greeting prefix called
`detectDayPeriod(new Date())`. The visual-smoke renderer freezes
`Date.now()` to a fixture timestamp but does NOT override the
`Date` constructor, so screenshot baselines drifted at the
5/11/14/18-hour boundaries.

Fix: `detectDayPeriod` now accepts `nowMs: number = Date.now()`.
Default arg picks up the visual-smoke clock freeze automatically;
real users continue reading the host clock as before. The function
is exported from `@maka/ui` so the boundary contract is testable.

New test `apps/desktop/src/main/__tests__/empty-hero-day-period.test.ts`
(7 cases) locks the boundary table:
  - 00:00–04:59 → evening
  - flip to morning at 05:00
  - flip to noon at 11:00
  - flip to afternoon at 14:00
  - flip to evening at 18:00
  - `Date.now()` stub flows through default arg (the visual-smoke
    determinism guarantee)
  - same nowMs → same period (referential transparency)

**Blocker #2 — ⌘K palette hint overflow + a11y leak**

LAYOUT-5b introduced `.maka-hero-palette-hint`. Two issues:

  a) `width: fit-content` + `white-space: nowrap` on the inner
     `<span>` caused the chip to overflow on narrow viewports
     (the en/zh hint copy easily exceeds 990px hero width). The
     screenshot matrix gate includes a 990px viewport so this
     would have shipped a layout regression.

  b) Entire `<span>` had `aria-hidden="true"`. The hint
     announces a real keyboard shortcut (⌘K opens command
     palette) and a navigation entrypoint to AT users; hiding it
     strips real info from the AT tree. The original justification
     ("shortcut is exposed via the command palette dialog") only
     holds for AT users who already know about ⌘K — for the
     discovery-mode AT user this is the same hint sighted users
     get, and it should reach them too.

Fixes:
  - CSS: drop `width: fit-content`, add `max-width: 100%`; change
    inner span from `white-space: nowrap` to `normal`; add `min-width: 0`
    + `line-height: 1.4` so wrapping reads clean. `<kbd>` keeps
    `flex: 0 0 auto` so the glyph pair stays on one line even when
    text wraps below. `border-radius` 999px → 14px so a 2-line wrap
    doesn't look like a smashed pill.
  - JSX: remove `aria-hidden="true"` from outer span. Add
    `aria-keyshortcuts="Meta+K"` so AT exposes the chord cleanly.
    Inner `<kbd>` glyphs become `aria-hidden` (they read noisily
    as "command K"); the textual hint stays in the AT tree.

354 desktop tests pass (was 347; +7 new). typecheck + check-a11y
+ check-console clean.

Other B1-a1 review findings (blockquote vs alert / focus-ring /
no contract consumption / SetupHero copy) all passed and are
unchanged.
jackwener added a commit that referenced this pull request Jun 21, 2026
redaction + per-delta/per-session caps for thinking stream

Two trust-boundary blockers from @kenji's C0 review fixed using the
same A3 tool-output pattern:

**Blocker #1: secondary redaction**

The original `thinking_delta` / `thinking_complete` handlers
appended `event.text` directly into `thinkingBySession` state and
the renderer drew it via `<pre>{text}</pre>` (NOT Markdown), so the
PR description's "走 markdown render path 自带 redaction" was
wrong. Model thinking can echo prompt / env / tool stderr / pasted
credentials past the provider's redactor, so the raw text must not
reach React state.

**Blocker #2: unbounded buffer**

Both handlers appended/replaced without any size cap. `<pre>`'s
CSS `max-height: 320px` only bounds visual height; the DOM text /
React state / DevTools snapshot still grow unbounded. A misbehaving
provider could ship multi-MB deltas.

Fix: pure helpers in `packages/ui/src/thinking-stream.ts` exporting
`applyThinkingDelta(prev, rawDelta, opts) -> { text, redacted, truncated }`
and `applyThinkingComplete(rawText, opts) -> { text, redacted, truncated }`:

  - L1 secondary `redactSecrets(raw)` BEFORE state. Raw bearer /
    `sk-...` / API-key text never reaches stored text or `<pre>`.
  - L2 per-delta cap (default 4 KB, matches A3 + runtime
    `TOOL_OUTPUT_DELTA_MAX_CHARS`): tail-keep with `[…单条 delta
    已截断]` marker.
  - L3 per-session total cap (default 32 KB, 2x A3's per-tool
    cap because thinking can run longer): tail-keep most recent
    reasoning with `[…已截断早期 reasoning]` marker so the user
    sees the CURRENT chain of thought, not the start.
  - `redacted` is monotonic: upstream `redacted: true` is never
    downgraded.
  - Defensive: non-string `rawDelta` / `rawText` returns the prev
    state untouched (runtime contract violation, drop silently
    rather than coerce).

Renderer changes in `apps/desktop/src/renderer/main.tsx`:

  - New state `thinkingTruncatedBySession: Record<string, boolean>`
    flag, monotonic per session. Flipped to `true` when the helper
    returns `truncated: true`; cleared with `thinkingBySession` in
    `clearStreaming(sessionId)` so the next turn starts clean.
  - `thinking_delta` handler now calls `applyThinkingDelta`, updates
    both text + truncated flag.
  - `thinking_complete` handler now calls `applyThinkingComplete`,
    same chokepoint.
  - `ChatView` gains `thinkingTruncated?: boolean` prop; renderer
    passes `activeThinkingTruncated`.

UI changes in `packages/ui/src/components.tsx`:

  - `<ReasoningPanel>` props gain `truncated: boolean`.
  - Header renders `已截断` pill (warning-tone, same chrome as A3's
    `<ToolOutputStream>` truncated pill) with title="部分 reasoning
    已截断;显示的是最近的内容" when truncated fires. AT users get
    the title via the cursor:help hover.

CSS additions in `apps/desktop/src/renderer/styles.css`:

  - `.maka-reasoning-panel-truncated[data-truncated="true"]` chrome
    matches the A3 `.maka-tool-output-stream-counts span[data-truncated]`.

Tests in `apps/desktop/src/main/__tests__/thinking-stream.test.ts`
(14 new cases, 368 total):
  - raw `Authorization: Bearer sk-test...` → masked in stored text +
    `redacted: true`
  - raw `sk-ant-...` bare key → masked
  - clean text → `redacted: false`, no truncation
  - non-string input → silently returns prev unchanged
  - single oversize delta → tail-keep with marker, `truncated: true`
  - tail content of oversize delta survives
  - delta at-or-under cap → unchanged
  - sustained ~32KB+ → total cap drops oldest, `[step-0]` gone,
    `[step-11]` survives
  - total-cap fires set `truncated: true`
  - `applyThinkingComplete` replace path: clean / redacted / oversize
  - combined oversize + secret → secret never in stored text

`<ReasoningPanel>` change is renderer-side and exercised through
the screenshot pipeline; no React-test framework added.

368 desktop tests pass (was 354; +14 new). typecheck +
check-a11y + check-console clean.
jackwener added a commit that referenced this pull request Jun 21, 2026
internal probe + explicit safe-scheme external allowlist

Two trust-boundary blockers from @kenji's C2 review fixed:

**Blocker #1: case-variant `maka:` was falling to external `<a>`**

`MarkdownLink` previously gated on `isMakaUri(href)` which is
strictly case-sensitive (`href.startsWith('maka:')`). So
`Maka://settings/account` / `MAKA://compose?text=hi` /
`MaKa://settings/health` were not recognized as internal-looking
URIs and fell through to the external `<a target=_blank>` path —
exactly the case the gate was supposed to catch. A prompt-injected
case-variant `Maka://` would have opened in the OS browser.

Fix: new `isMakaUriCandidate(href) = /^maka:/i.test(href)` for the
renderer's probe. `parseMakaUri` stays strict (only lowercase
`maka:` accepted). The MarkdownLink now does:

  isMakaUriCandidate(href) && parseMakaUri(href) === null
    → broken-link `<span>` with `data-reason="internal-invalid"`
       and `title="内部链接无效"`

**Blocker #2: external path had no safe-scheme gate**

Without an explicit allowlist, `javascript:`, `data:`, `file:`,
`vbscript:` and custom schemes would render as `<a target=_blank>`,
relying on react-markdown's sanitize behavior. The link chokepoint
should not depend on an upstream pipeline.

Fix: new `isSafeExternalScheme(href)` parses via `new URL(href)`
(not naive prefix-match — @kenji msg 73e92ef0 explicitly required
the parser path so `mailto:` matches actual mailto URLs, not
`mailto-info:contact` or bare emails) and accepts ONLY:
  - `http:`
  - `https:`
  - `mailto:`

MarkdownLink falls back to a separate broken-link `<span>` with
`data-reason="unsafe-scheme"` and `title="链接不安全"` for
anything else. Distinct copy + data-reason from the internal-
invalid case so visual-smoke / a11y snapshots can directly see
which gate fired (@kenji msg 73e92ef0).

Updated tests in `apps/desktop/src/main/__tests__/maka-uri.test.ts`
(12 new cases, 440 total):
  - isMakaUriCandidate: lowercase / uppercase / mixed-case accept;
    `makafake://` / `https://` reject; non-string defensive;
    combined gate (candidate=true + parseMakaUri=null) for the
    case-variants
  - isSafeExternalScheme: http / https / mailto accept;
    javascript / data / file / vbscript reject; maka: rejected
    (handled by internal path); custom / unknown schemes rejected;
    garbage / unparseable hrefs rejected; bare emails without
    `mailto:` prefix rejected (locks the parser-path guarantee);
    non-string defensive

`MarkdownLink` JSDoc updated to describe the new 3-way render
tree: candidate-valid → button; candidate-invalid →
internal-invalid `<span>`; safe-scheme external → `<a>`; unsafe →
unsafe-scheme `<span>`.

The dangerous-scheme case (`javascript:alert(1)` etc.) now hits
the unsafe-scheme broken `<span>` instead of `<a>`. Even if
react-markdown's pipeline weakened its sanitizer, the link
chokepoint here would still neutralize it.

440 desktop tests pass (was 428; +12 new). typecheck +
check-a11y + check-console clean.
jackwener added a commit that referenced this pull request Jun 21, 2026
…malizeConnectionBaseUrl + replace IPC validate-only with store-boundary chokepoint

Addresses two blockers @kenji flagged on the v1 validate-only path:

**Blocker 1 (msg 8755ffb3): raw whitespace persists past validate.**

v1's IPC handler called `validateConnectionBaseUrl(input.baseUrl)`
and passed the **raw** input to the store on accept. Since
validate treated whitespace-only as valid (no-override semantics),
the raw `'   '` reached the store on update, which treats truthy
strings as set-override and could persist `'   '` as the baseUrl.
Same for `'  https://api.openai.com  '` — whitespace-padded URL
landed on disk.

The gate's judgment point is the **store boundary**, not "the
helper passes". Solution: a normalize chokepoint that returns the
canonical value the store actually sees.

**Blocker 2 (msg 6b638e08): explicit-clear intent must not collapse to don't-touch.**

Initial fixup design returned `undefined` for whitespace input
("no override"), but the existing store update semantics treat
`patch.baseUrl !== undefined ? patch.baseUrl || undefined :
current.baseUrl` — `undefined` means "don't touch existing
override", which would silently swallow the user's clear intent
(they typed whitespace to remove their custom baseUrl). The fix:
preserve whitespace-input as `''` so the store's existing
`'' → undefined` clear semantics fire.

Final contract (`normalizeConnectionBaseUrl(input: string)`):
- `{ ok: false, error }` — bad scheme / malformed / oversize
- `{ ok: true, value: '<trimmed URL>' }` — set override
- `{ ok: true, value: '' }` — explicit clear (whitespace input)

Trim is the ONLY canonicalization. No URL-lib lowercase/strip-
default-port; users who deliberately typed `https://Example.com:443/V1`
keep it.

IPC handler updates (`apps/desktop/src/main/main.ts`):

  - `connections:create`:
    - Construct `normalizedInput = { ...input, baseUrl: result.value }`
      — copy-not-mutate (per @kenji msg 6b638e08 note #1; avoids
      reference aliasing).
    - For create, `''` value is semantically equivalent to omit
      (store's `input.baseUrl ? ... : {}` ternary skips falsy);
      pass it anyway so the store only sees safe canonical text.
    - All downstream reads (`normalizedInput.apiKey`, etc.) read
      from the normalized copy.

  - `connections:update`:
    - Same copy-not-mutate pattern: `normalizedPatch = { ...patch,
      baseUrl: result.value }`.
    - `''` value is the explicit clear → store's ternary clears
      existing override. `undefined` (patch.baseUrl omitted) is
      "don't touch" and skips normalize entirely.

Tests (`packages/core/src/__tests__/llm-connections.test.ts`,
+15 cases under "normalizeConnectionBaseUrl"):
- Explicit-clear intent: empty / whitespace variants all → `''`
  (NOT undefined; runtime assert + locked via TS shape)
- Set intent: clean URL passes through; surrounding whitespace
  trimmed; NO scheme/host/path canonicalization (mixed-case
  preserved); localhost / 192.168.x / Ollama default URL survives
- Reject: bad scheme / file: / malformed / oversize all flow
  through validate gate
- Store-boundary scenarios (IPC handler simulation): trimmed-URL
  → store sees set; whitespace → store sees `''` (clear); bad
  scheme → throw before store; `undefined` → handler skips
  normalize entirely (type signature `string` enforces caller
  guard)

Gate (all green):
- @maka/core build + tests = 193 pass (was 178 in v1; +15 new for
  normalize)
- @maka/ui build ✅
- @maka/desktop typecheck + tests = 539 pass (no regression)
- check-a11y / check-console ✅

`validateConnectionBaseUrl` stays exported as the pure URL-shape
gate (used by normalize internally; usable in non-IPC contexts).
The IPC site uses normalize exclusively going forward.
jackwener added a commit that referenced this pull request Jun 21, 2026
Lands the shared privacy contract that SEARCH-2.5 / future MEMORY
read gate / VOICE-1 consume so each lane does not re-invent the
incognito flag. Contract-only — no IPC, no renderer, no settings UI,
no storage, no runtime enforcement.

Anchors:
- xuan msg `0f1a3a2b` (lane assignment), `ece30c92` (review pre-conditions
  #1 reject-no-default + #2 authority rule), `0ee0a3b7` (canonical-strip
  named test request).
- kenji msg `64ba21cb` (default-false-is-not-permission + canonical
  strip extra fields).
- Predecessors that consume this contract: PR-SEARCH-1 G3 gate, PR-MEMORY-1
  `MemoryWriteRequestContext.incognitoActive`, PR-VOICE-0 incognito refusal.

== Contract surface ==

`packages/core/src/incognito.ts`:

  export interface WorkspacePrivacyContext {
    incognitoActive: boolean;
  }

  export function defaultWorkspacePrivacyContext(): WorkspacePrivacyContext;
  export function isWorkspacePrivacyContext(value: unknown): value is WorkspacePrivacyContext;
  export function validateWorkspacePrivacyContext(input: unknown): WorkspacePrivacyContextResult;
  export const WORKSPACE_PRIVACY_CONTEXT_INVALID_REASONS = ['not_object', 'incognito_active_invalid'];

v1 has exactly one field. Extending the shape is a contract change
requiring this doc, every consumer lane, and the test catalog to update.

== Authority rules (locked) ==

1. `incognitoActive` source-of-truth is main / session / workspace owner.
2. Renderer can READ or DISPLAY the context but CANNOT submit a context
   to prove its state in either direction. A renderer payload claiming
   `false` is just as unauthoritative as one claiming `true`. Per
   xuan `ece30c92`.
3. Default state is `incognitoActive: false`, produced ONLY by
   `defaultWorkspacePrivacyContext()`. Validator NEVER invents a
   default. Missing or non-boolean `incognitoActive` is a typed reject.
   Per xuan `ece30c92` #1.
4. `default false` does NOT mean "writes allowed". It means "no
   incognito gate fired"; consumers MUST still consult their own
   per-lane policy gates. Per kenji `64ba21cb`.

== Validator pipeline ==

1. typeof object guard (rejects null / array / primitive / function).
2. `incognitoActive` typeof boolean guard.
3. Canonical return strips extra fields — renderer cannot self-attest
   policy via `{ incognitoActive: false, durableWriteAllowed: true }`.
   Per kenji `64ba21cb` + xuan `0ee0a3b7` named test request.

== Tests added (22 new) ==

`packages/core/src/__tests__/incognito.test.ts`:

  - default factory returns { incognitoActive: false } + fresh refs +
    validator does NOT produce default.
  - validate accepts {incognitoActive: true} and {incognitoActive: false}.
  - validate rejects missing incognitoActive (per xuan #1).
  - validate rejects non-boolean incognitoActive (8 values: 0, 1,
    'true', 'false', null, undefined, [], {}, () => false).
  - validate rejects null / undefined / array / 4 primitive payloads.
  - canonical-strip: shadowPolicy + forcedFalse + __proto__ stripped.
  - named test (xuan `0ee0a3b7`): `{incognitoActive:false,
    durableWriteAllowed:true}` returns exactly `{incognitoActive:false}`.
  - canonical false consumers consult own policy (no writeAllowed /
    durableWriteAllowed exists on contract).
  - isWorkspacePrivacyContext type guard accepts/rejects matrix.
  - closed reason enum exact.
  - cross-lane shape pins: exactly one field on default, exactly one
    field on canonical return.

== Threat model doc ==

`docs/workspace-privacy-context.md`:

- Authority rules (4 enumerated).
- Validator pipeline.
- Closed reason enum.
- Consumer obligations: SEARCH (PR-SEARCH-2.5), MEMORY, VOICE (PR-VOICE-1
  deferred), TELEMETRY, LOGS.
- "default false != permission grant" paragraph (kenji `64ba21cb`).
- Out-of-scope: settings UI / storage / IPC / runtime enforcement /
  per-session scoping / time-bounded / additional privacy variants.
- Forbidden source-grep surfaces.
- Migration path for downstream consumers (MEMORY-2 alignment,
  SEARCH-2.5 wiring, VOICE-1 wiring).

== Source hygiene ==

`incognito.ts` is plain ASCII UTF-8. No regex character classes, no
control bytes, no String.fromCharCode trickery (not needed for a
single-boolean contract).

== Source gate self-check ==

- No `ipcMain.handle` / `BrowserWindow` / `fetch(` / `XMLHttpRequest` /
  `new WebSocket` / `electron` import in `incognito.ts` or its test.
- No storage repo names referenced.
- No settings shape additions; `AppSettings` is not touched.
- No IPC channel registered; no preload binding; no `global.d.ts` change.
- No consumer lane wired in this packet — each consumes in its own
  future PR.

== Test sweep ==

  core: 390 pass (+22 from PR-INCOGNITO-0; was 368).
  storage: 50 pass (unchanged).
  runtime: 103 pass (unchanged).
  desktop: 599 pass (unchanged).
  total: 1142 pass.

All workspace typechecks pass. All workspace builds pass.

== Files (5 changed) ==

  packages/core/src/incognito.ts                       (NEW, ~140 lines)
  packages/core/src/__tests__/incognito.test.ts        (NEW, ~190 lines)
  docs/workspace-privacy-context.md                    (NEW, ~120 lines)
  packages/core/src/index.ts                           (+12 barrel)
  packages/core/package.json                           (+1 subpath)

== Out of scope (separate sign-off required) ==

- Settings UI toggle for entering/leaving incognito.
- Storage representation of incognito mode.
- IPC channels for renderer subscription.
- Runtime enforcement at consumer lanes (PR-SEARCH-2.5 / future MEMORY
  read gate / PR-VOICE-1 — those each wire separately).
- Per-session vs workspace-wide scoping.
- Time-bounded incognito.
- Privacy-mode variants beyond `incognitoActive`.
jackwener added a commit that referenced this pull request Jun 21, 2026
…ist filter input

Addresses WAWQAQ msg `e0dbad11` blocker #1 + #2 and kenji msg
`2844f64f` blocker #1 + #2:

1. **Sidebar `? 快捷键` chip removed entirely.**
   - WAWQAQ called the position "很蠢"; kenji noted sidebar footer
     is for product nav/state, not help affordances.
   - Discoverability is now solely via Command Palette's existing
     `查看键盘快捷键` entry (`command-palette.tsx` line 113) + the
     global `?` keydown listener that has always existed.
   - Removed: `.maka-session-panel-help-chip` JSX + CSS,
     `onOpenKeyboardHelp` prop on SessionListPanel,
     `onOpenKeyboardHelp={openHelp}` wiring in main.tsx.
   - Retained: `useKeyboardHelp()` 3-tuple return — Command Palette
     `onOpenShortcuts` now uses the `openHelp` callback directly
     instead of dispatching a synthetic `KeyboardEvent`. Same effect,
     clearer intent, no risk of swallowing real `?` keypresses
     typed in text inputs.

2. **`筛选会话` in-list filter input removed entirely.**
   - WAWQAQ said earlier this input is unnecessary (he reminded
     us in `e0dbad11`); my P0 fixup v3 only renamed the placeholder
     instead of removing the input — that was a misread.
   - All search capability lives in the top-level `搜索` modal.
     Commit 5 (this PR, next commit) wires that modal to real
     `window.maka.search.thread()` so the global entry actually
     works.
   - Removed: `searchQuery` state, `searchInputRef`, the
     `useMemo` filter, the ⌘F/Ctrl+F focus binding `useEffect`,
     the `.maka-session-search` JSX block + clear button, the
     `.maka-session-search` + `.maka-session-search-clear` CSS,
     the "没有匹配的会话" empty state (only fired when input had
     content + no name matches).
   - `.maka-session-panel` grid-template-rows: 5 rows → 4 rows
     (header / module-nav / list / footer). Existing
     `sidebar-scroll-contract.test.ts` still passes because the
     `minmax(0, 1fr)` row is still present.

Gates:
- typecheck clean, UI + renderer build clean
- desktop tests: 647 pass / 0 fail
- core tests: 392 pass

Next commit (commit 5, this same PR):
- Wire Search modal to real `window.maka.search.thread()` per
  kenji `2844f64f` SEARCH gate: no query persistence, no
  `maka://session` fallback, incognito blocked state, plain text
  snippet (no markdown/image/path leaks), no Command Palette
  wiring, selection navigates + scrolls to message.
jackwener pushed a commit that referenced this pull request Jun 21, 2026
jackwener added a commit that referenced this pull request Jun 21, 2026
PR77 (message meta) + PR76 follow-ups @kenji flagged:

**Message meta**: replaces the bare role-label `<span>` with a
`MessageMeta` component that renders [avatar][role name][timestamp]
inline. Avatar is a small (22px) tinted circle with the initial
glyph — uses the first non-ASCII codepoint when available, so userLabel
"建文" → 建, "JK" → J, "🦊 fox" → 🦊. Assistant gets a fixed "M". Per
role data-attr the circle uses the matching token (chat-user-bg for
user, accent-tinted for assistant, info-tinted for system).

**Tool output redaction (@kenji PR76 follow-up #1)**: `OverlayPreview`
now runs `redactSecrets` over `text` / `json` payloads and the
`FileDiffPreview` body. `TerminalPreview` redacts cwd-adjacent `cmd`
string + stdout + stderr — `$ curl -H "X-API-Key: ..." …` lines and
provider dumps go through the masker before display. Pairs with the
existing copy-error redaction in ToolErrorBanner (PR58 / PR60); both
display and copy paths are now consistent.

**Tool output truncation (@kenji PR76 follow-up #2)**: introduces
`TOOL_LINE_CAP = 500` + `capLines()`. file_diff body, terminal
stdout, terminal stderr, and plain text all slice to 500 lines and
append a "… N more lines hidden" marker. Prevents a single
megabyte-scale `npm test` failure from creating 10k React elements
and drowning the chat surface.

@maka/ui + desktop typecheck + build + tests green.
jackwener added a commit that referenced this pull request Jun 21, 2026
…doc-merge)

1. **iframe sandbox/CSP language tightened** (@kenji #1):
   - Remove the "separate webContents partition + permissive CSP for
     iframe" promise — DOM `<iframe>` doesn't get an independent
     partition without `<webview>` / BrowserView. Don't promise what
     the DOM can't deliver.
   - Add `allow-forms` and `allow-modals` to the not-allowed list
   - Switch from `src="file://..."` to `srcdoc={await readText()}` so
     content delivery goes through the path-guard read helper
   - Note that global CSP `default-src 'self'` stays locked — sandbox
     attribute carries all isolation

2. **Symlink-aware path guard** (@kenji #2):
   - Both `realpath(artifactRoot)` AND `realpath(target)` required,
     then containment check
   - Mirror PR56 open-path-guard which already has symlink-escape +
     `..` + URL-scheme test coverage

3. **readBinary MIME allow-list** (@kenji #3):
   - Allowlist: image/png/jpeg/gif/webp/svg+xml, application/pdf
   - MIME sniffed at read time, NOT trusted from record.kind or
     record.mimeType
   - Unknown → `reason: 'unsupported_mime'` + UI shows metadata +
     "在 Finder 中打开" / "另存为" actions (no raw bytes to renderer)

4. **Deleted tombstone blocks reads** (@kenji #4):
   - `status: 'deleted'` records immediately return `reason: 'deleted'`
     from readText / readBinary — even if the underlying file still
     exists on disk
   - Surface table updated: deleted row preview shows "此 artifact 已
     删除,预览已停止"
   - Permanent path purge is a separate Settings · 数据 flow

5. **PR108c runtime hook scope** (@kenji #5):
   - First version does NOT do LLM extractor
   - Only deterministic outputs: Write→file record, Edit→diff record,
     Bash with explicit redirect → file record
   - stdout/stderr NOT auto-promoted (noise)
   - LLM extractor (parse ```html``` from assistant message) deferred
     to PR109+

Also: type rename `storagePath` → `relativePath` to enforce contract
in the type system; full reason union widened on both read helpers.

doc total: 1416 lines.
jackwener added a commit that referenced this pull request Jun 21, 2026
Two blocker findings from @kenji's contract-consumer review of A2
addressed:

**Blocker #1: user-facing copy no longer leaks internal PR / IPC
terms.** Every JSX-rendered string referencing `PR-CU-*`, `PR-HC-*`,
`PR-REAL-*`, `typed action IPC`, or `ToolOutputDelta` is replaced
with product language. PR-tracking references survive only in
JSDoc / code comments, where they belong.

  - Permission Center footnote: "正在 PR-CU-0 / PR-CU-1(Computer Use
    原生 helper)路上,落地后会替换这里的只读视图。" →
    "权限引导模块(Computer Use 原生 helper)接入后会替换这里的只读视图。"
  - Permission Center action hint titles:
    "操作入口等 PR-CU-0/1 typed action IPC 接入后可用" →
    "权限引导模块接入后提供"
  - Permission Center audit slot empty state:
    "审计日志将在 PR-REAL-3 接入后显示。" → "审计日志接入后显示。"
  - Health Center hard-rule p tag:
    "凭据测试只属于 validation 层,运行态需要 PR-REAL-4 接入实测探测。" →
    "凭据测试只属于 validation 层,运行态需要运行态探测接入后实测。"
  - Health Center footnote:
    "操作入口等 PR-HC-2 typed action IPC 接入后可用。所有真正的运行态探测
    (PR-REAL-4 ToolOutputDelta + send/stream/abort smoke)落地后会自动
    出现在「运行态探测」层。" →
    "运行态修复操作接入后显示。所有真正的运行态探测落地后会自动出现
    在「运行态探测」层。"

**Blocker #2: CAPABILITY_READINESS_COPY.enabled.detail no longer
overpromises runtime probe.** A2 is a read-only consumer; whether
`runtimeProbe.state` is `not_available` / `not_run` / `passed` is
already shown separately in the per-layer breakdown below the
summary pill. The summary copy must not synthesize a conclusion
the snapshot didn't make.

  - "配置、权限、运行态探测都已通过。" →
    "当前快照标记为可用,具体层级见下方。"

The runtime probe layer remains the single source of truth for
"是否运行态通过"; the summary pill's `detail` now defers to it
rather than asserting it.

@kenji non-blocking follow-up #3 (`toLocaleString()` host-locale
drift) deferred to when Permission/Health pages enter visual smoke
— mirrors the `MAKA_VISUAL_SMOKE_LOCALE` deterministic-formatter
pattern. Not blocking A2 since A2 carries no screenshot baseline.

332 desktop tests pass; typecheck + check-a11y + check-console
clean. No behavior change beyond copy.
jackwener added a commit that referenced this pull request Jun 21, 2026
Two blockers from @kenji's review of B1-a1 fixed:

**Blocker #1 — visual-smoke day-period determinism**

LAYOUT-4's `EmptyChatHero` greeting prefix called
`detectDayPeriod(new Date())`. The visual-smoke renderer freezes
`Date.now()` to a fixture timestamp but does NOT override the
`Date` constructor, so screenshot baselines drifted at the
5/11/14/18-hour boundaries.

Fix: `detectDayPeriod` now accepts `nowMs: number = Date.now()`.
Default arg picks up the visual-smoke clock freeze automatically;
real users continue reading the host clock as before. The function
is exported from `@maka/ui` so the boundary contract is testable.

New test `apps/desktop/src/main/__tests__/empty-hero-day-period.test.ts`
(7 cases) locks the boundary table:
  - 00:00–04:59 → evening
  - flip to morning at 05:00
  - flip to noon at 11:00
  - flip to afternoon at 14:00
  - flip to evening at 18:00
  - `Date.now()` stub flows through default arg (the visual-smoke
    determinism guarantee)
  - same nowMs → same period (referential transparency)

**Blocker #2 — ⌘K palette hint overflow + a11y leak**

LAYOUT-5b introduced `.maka-hero-palette-hint`. Two issues:

  a) `width: fit-content` + `white-space: nowrap` on the inner
     `<span>` caused the chip to overflow on narrow viewports
     (the en/zh hint copy easily exceeds 990px hero width). The
     screenshot matrix gate includes a 990px viewport so this
     would have shipped a layout regression.

  b) Entire `<span>` had `aria-hidden="true"`. The hint
     announces a real keyboard shortcut (⌘K opens command
     palette) and a navigation entrypoint to AT users; hiding it
     strips real info from the AT tree. The original justification
     ("shortcut is exposed via the command palette dialog") only
     holds for AT users who already know about ⌘K — for the
     discovery-mode AT user this is the same hint sighted users
     get, and it should reach them too.

Fixes:
  - CSS: drop `width: fit-content`, add `max-width: 100%`; change
    inner span from `white-space: nowrap` to `normal`; add `min-width: 0`
    + `line-height: 1.4` so wrapping reads clean. `<kbd>` keeps
    `flex: 0 0 auto` so the glyph pair stays on one line even when
    text wraps below. `border-radius` 999px → 14px so a 2-line wrap
    doesn't look like a smashed pill.
  - JSX: remove `aria-hidden="true"` from outer span. Add
    `aria-keyshortcuts="Meta+K"` so AT exposes the chord cleanly.
    Inner `<kbd>` glyphs become `aria-hidden` (they read noisily
    as "command K"); the textual hint stays in the AT tree.

354 desktop tests pass (was 347; +7 new). typecheck + check-a11y
+ check-console clean.

Other B1-a1 review findings (blockquote vs alert / focus-ring /
no contract consumption / SetupHero copy) all passed and are
unchanged.
jackwener added a commit that referenced this pull request Jun 21, 2026
internal probe + explicit safe-scheme external allowlist

Two trust-boundary blockers from @kenji's C2 review fixed:

**Blocker #1: case-variant `maka:` was falling to external `<a>`**

`MarkdownLink` previously gated on `isMakaUri(href)` which is
strictly case-sensitive (`href.startsWith('maka:')`). So
`Maka://settings/account` / `MAKA://compose?text=hi` /
`MaKa://settings/health` were not recognized as internal-looking
URIs and fell through to the external `<a target=_blank>` path —
exactly the case the gate was supposed to catch. A prompt-injected
case-variant `Maka://` would have opened in the OS browser.

Fix: new `isMakaUriCandidate(href) = /^maka:/i.test(href)` for the
renderer's probe. `parseMakaUri` stays strict (only lowercase
`maka:` accepted). The MarkdownLink now does:

  isMakaUriCandidate(href) && parseMakaUri(href) === null
    → broken-link `<span>` with `data-reason="internal-invalid"`
       and `title="内部链接无效"`

**Blocker #2: external path had no safe-scheme gate**

Without an explicit allowlist, `javascript:`, `data:`, `file:`,
`vbscript:` and custom schemes would render as `<a target=_blank>`,
relying on react-markdown's sanitize behavior. The link chokepoint
should not depend on an upstream pipeline.

Fix: new `isSafeExternalScheme(href)` parses via `new URL(href)`
(not naive prefix-match — @kenji msg 73e92ef0 explicitly required
the parser path so `mailto:` matches actual mailto URLs, not
`mailto-info:contact` or bare emails) and accepts ONLY:
  - `http:`
  - `https:`
  - `mailto:`

MarkdownLink falls back to a separate broken-link `<span>` with
`data-reason="unsafe-scheme"` and `title="链接不安全"` for
anything else. Distinct copy + data-reason from the internal-
invalid case so visual-smoke / a11y snapshots can directly see
which gate fired (@kenji msg 73e92ef0).

Updated tests in `apps/desktop/src/main/__tests__/maka-uri.test.ts`
(12 new cases, 440 total):
  - isMakaUriCandidate: lowercase / uppercase / mixed-case accept;
    `makafake://` / `https://` reject; non-string defensive;
    combined gate (candidate=true + parseMakaUri=null) for the
    case-variants
  - isSafeExternalScheme: http / https / mailto accept;
    javascript / data / file / vbscript reject; maka: rejected
    (handled by internal path); custom / unknown schemes rejected;
    garbage / unparseable hrefs rejected; bare emails without
    `mailto:` prefix rejected (locks the parser-path guarantee);
    non-string defensive

`MarkdownLink` JSDoc updated to describe the new 3-way render
tree: candidate-valid → button; candidate-invalid →
internal-invalid `<span>`; safe-scheme external → `<a>`; unsafe →
unsafe-scheme `<span>`.

The dangerous-scheme case (`javascript:alert(1)` etc.) now hits
the unsafe-scheme broken `<span>` instead of `<a>`. Even if
react-markdown's pipeline weakened its sanitizer, the link
chokepoint here would still neutralize it.

440 desktop tests pass (was 428; +12 new). typecheck +
check-a11y + check-console clean.
jackwener pushed a commit that referenced this pull request Jun 21, 2026
jackwener added a commit that referenced this pull request Jun 24, 2026
…#213)

Kenji aesthetic-audit reminder 9 (msg `bacde601` 2026-06-24,
finding #1): composer micro-interaction scales drifted way past
the global `button:active { scale(0.97) }` press range.

Before:
- `.maka-composer-tool-button:hover` — `scale(1.08)`
- `.maka-composer-tool-button:active` — `scale(0.94)`
- `.maka-composer-send-button:hover` — `scale(1.06)`
- `.maka-composer-send-button:active` — `scale(0.96)`

Tool buttons are quiet utility affordances (mic, attach) at the
bottom of the composer; they don't deserve CTA-sized travel. 1.08
hover + 0.94 active reads as bouncy and tugs the eye away from the
composer text input. The send button is a real CTA so it gets a
hair more than the tool buttons but still inside the tactile range.

After:
- tool button: hover `scale(1.02)`, active `scale(0.97)`
- send button: hover `scale(1.03)`, active `scale(0.97)`

All within the global tactile press range. Single file, 4 value
tweaks. No overlap with PR #211 (live-dot keyframes at lines 2231 /
11645 / 12634, far from this composer block at 6655-6706).
jackwener added a commit that referenced this pull request Jun 24, 2026
… reminder 4-6 #1) (#218)

Kenji's aesthetic audit reminder 4-6 finding #1
(msg `6cc0e04d` 2026-06-24): `packages/ui/src/ui.tsx` is a motion /
design contract blind spot. The PR-MOTION-TOKEN-CONVERGE-0 contract
scans `packages/ui/src/primitives/` and `apps/desktop/src/renderer/`
but NOT the aggregate UI re-export layer at ui.tsx. That file
inlines Tailwind utilities that would otherwise be caught:

- `z-40` (×2): dialog + sheet backdrop scrim
- `z-50` (×5): dialog popup, sheet popup, tooltip, select popup, popover
- `backdrop-blur-sm` (×2): dialog + sheet backdrop
- `transition-[height]` (×1): accordion content panel

Without a contract, future primitive PRs can quietly add a sixth or
seventh escape hatch without going through design-system review.

## Approach

Greenfield contract test pinning the EXACT set + count of escape
hatches. Three checks:

1. Each allowlisted pattern appears exactly the expected number of
   times — adding new sites OR removing old ones (stale allowlist)
   both fail.

2. No other bare Tailwind z-index utilities (z-0 / z-10 / z-20 / z-30)
   have crept in.

3. No other bare backdrop-blur intensity variants beyond `sm` have
   crept in (md / lg / xl / 2xl / 3xl / none).

## Intentionally NOT removing the escape hatches in this PR

Removing them would touch Base UI primitive wrappers (Dialog, Sheet,
Tooltip, Select, Popover, Accordion) and risk visual breakage. Each
removal needs WAWQAQ / kenji review on what to tokenize to. The
contract locks the perimeter; future PRs can replace one at a time.

The accordion `transition-[height]` is documented as intentional —
content panels are variable-height; transform-based scaling would
distort children. That one stays even after full tokenization.

## Diff

1 new file: ~110 lines test. No source change, no visual change.
No overlap with any open PR.

## Verification

Disk still ~100%, couldn't run `pnpm install && pnpm test`. The
contract is greenfield and self-validating — first run will confirm
all four allowlist counts match the file as it stands.
liuxiaocs7 added a commit to liuxiaocs7/maka that referenced this pull request Sep 3, 2026
…pache#4164)

Integrate the editable Pricing Settings surface (apache#2015) into the migrated
`features/usage` feature (apache#4425), replacing the read-only pricing tab with a
full add/edit/reset editor over the CAS + reconciliation protocol.

Renderer (feature-owned, ratchet-clean):
- Add the pricing controller, view-model, copy, and editor UI under
  `features/usage/`, rendered as the Usage "pricing" tab in place of the old
  read-only `UsagePricingPanel`.
- Give pricing its own services seam — `UsagePricingServices` port +
  `UsagePricingServicesProvider` + a `platform/desktop` adapter — wired through
  `composition/desktop-feature-services.tsx`. This keeps the sole
  `window.maka.settings.pricing` bridge access in the platform zone, so no new
  bridge path lands in a frozen legacy-AppShell closure file. The controller
  reloads on the Usage scope's `generationKey` (host:epoch) change.
- Hide the Usage range/summary toolbar on the Pricing tab (apache#2015 acceptance apache#2):
  the tab is not time-scoped, so the date range cannot be read as a Pricing
  scope. Restores gating the read-only tab had before the feature migration.

Main / preload:
- Add the CAS pricing IPC (`usage:pricing:load` / `usage:pricing:mutate`) over
  the existing `DesktopRuntimeHostClient` snapshot/mutation methods, and expose
  a public `reconcilePricingMutation` for the reconciled-control path (reload
  fresh authority + compare intent; never replay).
- Retire the interim, unreachable `usage:pricing:list/put/reset` handlers (and
  their base-synthesizing helper) so a single CAS surface owns pricing writes.
- Split the cross-boundary pricing types into a declaration-only
  `desktop-pricing.d.ts` (kept out of the renderer closure) plus a main-only
  `desktop-pricing-decode.ts` runtime guard.

Core:
- Remove the now-orphaned `UsageStats.pricing` field and the usage-stats IPC
  projection that fed it: the read-only pricing table it served is gone, and the
  editor reads the effective snapshot directly through the pricing IPC.

Tests: pricing view-model, the load/mutate IPC (base pass-through, malformed
base, reconcile-no-replay), and a `PricingEditor` render suite covering the
saved / refresh-failed / conflict / reconcile-unavailable / invalid-draft
states. Add a Desktop E2E (`e2e/settings-pricing.spec.ts`) that drives 设置 →
使用统计 → 定价配置 against the real embedded Runtime Host — the Host-backed
effective table with a 内置-labelled row (apache#2015 apache#1), the absent range/summary
toolbar (apache#2), and editor focus restore (apache#11) — plus `Product/Settings/Pricing`
Storybook stories (populated / empty / loading / load-failed). Regenerate the
Astryx surface inventory.

Refs apache#4164 apache#2015 apache#4425

Generated-by: Claude Code
liuxiaocs7 added a commit to liuxiaocs7/maka that referenced this pull request Sep 3, 2026
…pache#4164)

Integrate the editable Pricing Settings surface (apache#2015) into the migrated
`features/usage` feature (apache#4425), replacing the read-only pricing tab with a
full add/edit/reset editor over the CAS + reconciliation protocol.

Renderer (feature-owned, ratchet-clean):
- Add the pricing controller, view-model, copy, and editor UI under
  `features/usage/`, rendered as the Usage "pricing" tab in place of the old
  read-only `UsagePricingPanel`.
- Give pricing its own services seam — `UsagePricingServices` port +
  `UsagePricingServicesProvider` + a `platform/desktop` adapter — wired through
  `composition/desktop-feature-services.tsx`. This keeps the sole
  `window.maka.settings.pricing` bridge access in the platform zone, so no new
  bridge path lands in a frozen legacy-AppShell closure file. The controller
  reloads on the Usage scope's `generationKey` (host:epoch) change.
- Hide the Usage range/summary toolbar on the Pricing tab (apache#2015 acceptance apache#2):
  the tab is not time-scoped, so the date range cannot be read as a Pricing
  scope. Restores gating the read-only tab had before the feature migration.
- Search + paginate the effective table. It is the Host's full built-in model
  set (~1.4k rows) ∪ overrides, so the panel filters by model key and paginates
  (Astryx Pagination, 50 rows/page) and only one page is ever materialised — an
  unbounded render blocked/exhausted the renderer (a real Electron E2E failure
  under CI). Adds `filterPricingRows`/`pricingPageSlice` view-model helpers and
  optional `rowIndexStart`/`rowCount` on the shared usage table so the paged
  view keeps correct `aria-rowindex`/`aria-rowcount`.

Main / preload:
- Add the CAS pricing IPC (`usage:pricing:load` / `usage:pricing:mutate`) over
  the existing `DesktopRuntimeHostClient` snapshot/mutation methods, and expose
  a public `reconcilePricingMutation` for the reconciled-control path (reload
  fresh authority + compare intent; never replay).
- Retire the interim, unreachable `usage:pricing:list/put/reset` handlers (and
  their base-synthesizing helper) so a single CAS surface owns pricing writes.
- Split the cross-boundary pricing types into a declaration-only
  `desktop-pricing.d.ts` (kept out of the renderer closure) plus a main-only
  `desktop-pricing-decode.ts` runtime guard.

Core:
- Remove the now-orphaned `UsageStats.pricing` field and the usage-stats IPC
  projection that fed it: the read-only pricing table it served is gone, and the
  editor reads the effective snapshot directly through the pricing IPC.

Tests: pricing view-model (incl. filter + pagination slicing), the load/mutate
IPC (base pass-through, malformed base, reconcile-no-replay), and a
`PricingEditor` render suite covering the saved / refresh-failed / conflict /
reconcile-unavailable / invalid-draft states plus the one-page render bound and
search-narrowing. A Desktop E2E (`e2e/settings-pricing.spec.ts`) drives 设置 →
使用统计 → 定价配置 against the real embedded Runtime Host: searching for a
built-in row (来源 = 内置, apache#2015 apache#1) keeps the render light, the range/summary
toolbar is absent (apache#2), and editor focus is restored (apache#11). Adds
`Product/Settings/Pricing` Storybook stories (populated / paginated / empty /
loading / load-failed) and regenerates the Astryx surface inventory.

Refs apache#4164 apache#2015 apache#4425

Generated-by: Claude Code
M4n5ter added a commit that referenced this pull request Nov 20, 2026
… WebAssembly, SharedArrayBuffer, and Atomics in plugin/engine.rs\n runtime_base so neither Pure nor Scoped plugin isolates can allocate\n unmetered page-allocator backing stores; add pure/scoped integration tests.\n- Replace ReadQueue's VecDeque+HashMap pair with a single BTreeMap<u64, ReadJob>\n so repeated cancellations while another read stays pending leave zero stale IDs.\n- Tighten Scenario H to verify >= 50 wave-1 runs actively working via agent/observe\n immediately before SIGKILL #1 (observed 100/100) with no post-check sleep.\n- Tighten Scenario L so total_active_deleted only counts runs where agent/stop\n  returned requested=true, settlement succeeded, and changeSession removed the session.\n- Replace the racy 40-Write cell stop test with a deterministic Rig test pausing\n  inside PreparedTool::prepare before committing StopRequested so\n  NativeCellPort::commit(ChildAdmitted) deterministically hits view.stopped and\n  records ChildRejected without poisoning cleanup.
M4n5ter added a commit that referenced this pull request Nov 20, 2026
- Strip WebAssembly, SharedArrayBuffer, and Atomics in plugin/engine.rs
  runtime_base so neither Pure nor Scoped plugin isolates can allocate
  unmetered page-allocator backing stores; add pure/scoped integration tests.
- Replace ReadQueue's VecDeque+HashMap pair with a single BTreeMap<u64, ReadJob>
  so repeated cancellations while another read stays pending leave zero stale IDs.
- Tighten Scenario H to verify >= 50 wave-1 runs actively working via agent/observe
  immediately before SIGKILL #1 (observed 100/100) with no post-check sleep.
- Tighten Scenario L so total_active_deleted only counts runs where agent/stop
  returned requested=true, settlement succeeded, and changeSession removed the session.
- Replace the racy 40-Write cell stop test with a deterministic Rig test pausing
  inside PreparedTool::prepare before committing StopRequested so
  NativeCellPort::commit(ChildAdmitted) deterministically hits view.stopped and
  records ChildRejected without poisoning cleanup.
M4n5ter added a commit that referenced this pull request Nov 20, 2026
…Buffers, and remove SQLite hot-path bottlenecks (#7100)

* fix(event-log,agent-state): fix concurrent fresh-workspace creation race and remove SQLite hot-path bottlenecks

* fix(js-runtime): bound V8 ArrayBuffer backing stores to cell heap limit

* fix(agent): preserve frozen cut in SummaryRepair and deduplicate per-step cell child knowledge

* test(cli): add opt-in Hell-Tier Host stress suite (Scenarios H-L)

* fix(event-log,js-runtime,agent): address review findings and fix cell stop-race cleanup

- P1-1 (js-runtime): disable resizable ArrayBuffer and growable SharedArrayBuffer across all three isolate entry points so backing stores cannot bypass ArrayBufferBudget; replace infinite-loop test with finite in-budget, over-budget, and resizable-rejection assertions.
- P1-2 (agent-state): switch RunSlot.current to tokio::sync::RwLock so contested takeover waits are natively cancel-safe and swap+retirement occur within the same poll; add contested cancelled-takeover regression test.
- P1-3 (event-log): replace runtime sqlite3_config(SQLITE_CONFIG_MEMSTATUS, 0) with compile-time LIBSQLITE3_FLAGS=SQLITE_DEFAULT_MEMSTATUS=0 in .cargo/config.toml and verify PRAGMA compile_options.
- P1-4 (agent-engine, agent-native): introduce preparation::OutputBudget (Compute vs Frozen) so materialize and SummaryRepair preserve the frozen max_output_tokens instead of re-applying the default 200k Summary 4% floor; assert dispatched max_tokens == 4096 in compaction test.
- P2-1 (event-log): make queued ReadDispatcher jobs cancel-on-drop to release closure/custody immediately and skip cancelled jobs before authority validation or connection open.
- P2-2..5 (cli stress): tighten Scenario H/I/J/K/L assertions (wave-1 messageIds & in-flight load, UI/background reader error & sample counts, canary fixture_0 content & strict 80/80 archive readback, durable agent/goal status, active runId stop + kind==removed).
- Bonus Bug #8 (agent-native): use original_frontier() in driver_cells.rs (quarantine, NativeCellPort::new, NativeCellPort::commit) so stopping a Run mid-Cell cleanly rejects new child admission instead of triggering Run is no longer executable -> failed quarantine -> CleanupUnconfirmed; log error detail in cleanup.rs::observe_tool and add unit regression test.

* fix(js-runtime,event-log,agent): close round-2 review gaps

- Strip WebAssembly, SharedArrayBuffer, and Atomics in plugin/engine.rs
  runtime_base so neither Pure nor Scoped plugin isolates can allocate
  unmetered page-allocator backing stores; add pure/scoped integration tests.
- Replace ReadQueue's VecDeque+HashMap pair with a single BTreeMap<u64, ReadJob>
  so repeated cancellations while another read stays pending leave zero stale IDs.
- Tighten Scenario H to verify >= 50 wave-1 runs actively working via agent/observe
  immediately before SIGKILL #1 (observed 100/100) with no post-check sleep.
- Tighten Scenario L so total_active_deleted only counts runs where agent/stop
  returned requested=true, settlement succeeded, and changeSession removed the session.
- Replace the racy 40-Write cell stop test with a deterministic Rig test pausing
  inside PreparedTool::prepare before committing StopRequested so
  NativeCellPort::commit(ChildAdmitted) deterministically hits view.stopped and
  records ChildRejected without poisoning cleanup.
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.

2 participants