Compare commits
182 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7d9cf99f6c | |||
| 0a3e32e7f6 | |||
| b1ede48319 | |||
| d4d05c8e8b | |||
| 351860ba4b | |||
| 795dde463b | |||
| 0392566af9 | |||
| f43696a1c4 | |||
| 8971912d9e | |||
| 588596fb2f | |||
| ba94def3c8 | |||
| e1b8f81b15 | |||
| 45478098f5 | |||
| 62b818bb36 | |||
| b7c16dc634 | |||
| da952ca536 | |||
| 1458e3e152 | |||
| 13a333632a | |||
| 344b9723b2 | |||
| d57392b5af | |||
| a86e5f409f | |||
| 33d22ff164 | |||
| b861266ff8 | |||
| 8b99b70d73 | |||
| b3d4922efa | |||
| 49c7c4bb64 | |||
| d9517ff3f1 | |||
| 48c1ec46f7 | |||
| cd539558ed | |||
| b62db917de | |||
| ec542a924b | |||
| a9da8f7f15 | |||
| 7c0664d2b3 | |||
| a32fba63ec | |||
| 808a5c70df | |||
| 0210faabea | |||
| 17003fbbc1 | |||
| 0df6242128 | |||
| 36b3539571 | |||
| a63efa6920 | |||
| ccd38152ab | |||
| 8f95c5808e | |||
| 6f7d439811 | |||
| 88d96c41b5 | |||
| ef16743406 | |||
| 6c208a965f | |||
| 3f7d96e09d | |||
| d218b3a39e | |||
| f0778cb85a | |||
| 8f7da77939 | |||
| e6a861bdaf | |||
| 5b835fc185 | |||
| 86c1307ed2 | |||
| f720151c63 | |||
| cec50c3ce4 | |||
| f36a2def73 | |||
| 0968ea97d2 | |||
| 4af21494af | |||
| 2d30ad1fa2 | |||
| e648771ab8 | |||
| 4d8315da5c | |||
| 3f7e1bdc7b | |||
| d89650a45e | |||
| b1e48d3765 | |||
| 67dca8c10e | |||
| 5d45f5a85e | |||
| 293348f9dc | |||
| 330837cfa6 | |||
| 320b200ac8 | |||
| 916b24e3ff | |||
| ecf022ffca | |||
| 62af116271 | |||
| e9d5d493d3 | |||
| db9ed51e01 | |||
| 963822bd28 | |||
| c452902432 | |||
| 731a4f0dca | |||
| 895173b176 | |||
| 45d5ae1601 | |||
| 539512c4c8 | |||
| edc5dae103 | |||
| ec30e6c08a | |||
| 67fa0d1a28 | |||
| 91d674fea6 | |||
| db9f29c16b | |||
| bb5bb52244 | |||
| fa439d7c7b | |||
| f9cd3e6318 | |||
| c838fdeebe | |||
| 82411f8707 | |||
| af481d401a | |||
| affa32cbaa | |||
| f2d12fd2cd | |||
| b349676eae | |||
| 438ef091f9 | |||
| 768d135a19 | |||
| fcc9ae0c24 | |||
| e4ff146ab0 | |||
| c39fab70c1 | |||
| c7e034cab9 | |||
| 123e981808 | |||
| 7abce93543 | |||
| 0750a6fd34 | |||
| d833e5adb1 | |||
| f3dbcec0fd | |||
| 63f948df10 | |||
| fbaaa84419 | |||
| 32cb9eb1e3 | |||
| b47751349f | |||
| b7e5cb6970 | |||
| 906733b5c8 | |||
| f020739bfd | |||
| 22e3fcdeba | |||
| 7179f8a5b2 | |||
| fe4adf23a0 | |||
| eefe17600c | |||
| 32e99c6e42 | |||
| e48d7720e9 | |||
| 42e618ec7f | |||
| 857a0064f7 | |||
| daf6c9ea16 | |||
| 9e69d917ee | |||
| 2594828758 | |||
| b5ce63a956 | |||
| e777ebcf4f | |||
| abd6e3948b | |||
| 5125296bfa | |||
| 452a752264 | |||
| a40a00d5c5 | |||
| 81c0226be7 | |||
| d5079aa1d8 | |||
| b536a41ad3 | |||
| 28d2560dfd | |||
| 52959de2f3 | |||
| 5da12e89f9 | |||
| 3a91e0eca9 | |||
| 2e83c9cebf | |||
| f6d22a59a6 | |||
| 6baad935f9 | |||
| d255afa611 | |||
| 73c5c44301 | |||
| 8c42c4f0d6 | |||
| 071eae4e2a | |||
| a91405632e | |||
| 5d4eb8ede2 | |||
| aa1ee64b7a | |||
| 53febfd5b9 | |||
| a2ac08c04c | |||
| 40ca04eb08 | |||
| 393875d910 | |||
| c3dbee9fbf | |||
| ea1f8da906 | |||
| 9baaf1ea58 | |||
| 71375e25ee | |||
| e528988d71 | |||
| dc7a0ec9f5 | |||
| 969c00aaf1 | |||
| 085a30575f | |||
| 95bc9fe98d | |||
| cca0bfe306 | |||
| 0dbf85b129 | |||
| fb357cd52e | |||
| 177d8a31d4 | |||
| 8fa32e8438 | |||
| 807ff1f5f5 | |||
| fa89cba023 | |||
| 3386bf2865 | |||
| 98253cf614 | |||
| 181a8330f3 | |||
| 02daccc453 | |||
| d06cf97ed6 | |||
| 04032ae677 | |||
| d9d1d54aaa | |||
| 593f181bbc | |||
| 582e1976cc | |||
| e0e01157c2 | |||
| 8373360a67 | |||
| e2493cafa9 | |||
| 5a4d9f84d7 | |||
| 70bd0dba4d | |||
| b0cd4bd6cf | |||
| 56ab17fbc2 |
+57
-3
@@ -173,9 +173,21 @@ MCP_DOCMOST_PASSWORD=
|
|||||||
# Keep-alive recycle window (ms) for streaming chat/agent AI + external-MCP calls.
|
# Keep-alive recycle window (ms) for streaming chat/agent AI + external-MCP calls.
|
||||||
# A pooled connection idle longer than this is closed instead of reused, so a
|
# A pooled connection idle longer than this is closed instead of reused, so a
|
||||||
# NAT / egress firewall / reverse proxy that silently drops idle connections
|
# NAT / egress firewall / reverse proxy that silently drops idle connections
|
||||||
# cannot poison a reused socket into a PRE-RESPONSE `read ECONNRESET`. Lower it if
|
# cannot poison a reused socket into a PRE-RESPONSE `read ECONNRESET`. Kept under
|
||||||
# your egress drops idle connections faster than ~10s. Default 10000 (10 s).
|
# common ~5s upstream/middlebox idle cutoffs so undici recycles the socket before
|
||||||
# AI_STREAM_KEEPALIVE_MS=10000
|
# the network kills it (fewer resets), while still reusing within a burst of
|
||||||
|
# back-to-back calls. Lower it further if your egress drops idle connections even
|
||||||
|
# faster. Default 4000 (4 s).
|
||||||
|
# AI_STREAM_KEEPALIVE_MS=4000
|
||||||
|
|
||||||
|
# Number of PRE-RESPONSE connection retries for streaming chat/agent AI calls: a
|
||||||
|
# reset/timeout BEFORE any response byte (e.g. `read ECONNRESET` on a stale pooled
|
||||||
|
# socket) is retried on a fresh connection with jittered exponential backoff.
|
||||||
|
# Total attempts = value + 1, so the default 4 gives 5 attempts — headroom to
|
||||||
|
# absorb a short BURST of upstream resets without exhausting the budget. Safe to
|
||||||
|
# retry: a started stream is never replayed, only a connect that never responded.
|
||||||
|
# 0 disables the retry. Default 4.
|
||||||
|
# AI_STREAM_PRE_RESPONSE_RETRIES=4
|
||||||
|
|
||||||
# Silence timeout (ms) for EXTERNAL-MCP transport ONLY (not the chat provider).
|
# Silence timeout (ms) for EXTERNAL-MCP transport ONLY (not the chat provider).
|
||||||
# Tighter than AI_STREAM_TIMEOUT_MS so a byte-silent/hung MCP server is broken in
|
# Tighter than AI_STREAM_TIMEOUT_MS so a byte-silent/hung MCP server is broken in
|
||||||
@@ -223,3 +235,45 @@ MCP_DOCMOST_PASSWORD=
|
|||||||
# FAILS CLOSED if Redis is unavailable (default: 1,000,000 tokens per workspace
|
# FAILS CLOSED if Redis is unavailable (default: 1,000,000 tokens per workspace
|
||||||
# per rolling day).
|
# per rolling day).
|
||||||
# SHARE_AI_WORKSPACE_TOKEN_BUDGET_PER_DAY=1000000
|
# SHARE_AI_WORKSPACE_TOKEN_BUDGET_PER_DAY=1000000
|
||||||
|
|
||||||
|
# --- GIT-SYNC (native two-way Docmost <-> git Markdown sync) ---
|
||||||
|
# Master switch. Off by default. When 'true', GIT_SYNC_SERVICE_USER_ID below is
|
||||||
|
# REQUIRED (the service account that git-originated create/move/rename/delete are
|
||||||
|
# attributed to) — the server refuses to boot with sync enabled and no user id.
|
||||||
|
# GIT_SYNC_ENABLED=false
|
||||||
|
#
|
||||||
|
# Serve the per-space vaults over smart-HTTP (the /git host). Defaults to
|
||||||
|
# GIT_SYNC_ENABLED when unset.
|
||||||
|
# GIT_SYNC_HTTP_ENABLED=false
|
||||||
|
#
|
||||||
|
# REQUIRED when GIT_SYNC_ENABLED=true: id of the user that git-originated page
|
||||||
|
# operations (create / move / rename / delete) are attributed to.
|
||||||
|
# GIT_SYNC_SERVICE_USER_ID=
|
||||||
|
#
|
||||||
|
# Where the per-space working vaults live (non-bare repos; the engine needs a
|
||||||
|
# working tree).
|
||||||
|
# Defaults to "<DATA_DIR or ./data>/git-sync".
|
||||||
|
# GIT_SYNC_DATA_DIR=
|
||||||
|
#
|
||||||
|
# SCAFFOLDING for the DEFERRED remote-push feature (SPEC §7) — NOT yet
|
||||||
|
# implemented and currently INERT. The vendored sync engine does not consume
|
||||||
|
# this value anywhere (git push to a remote is deferred), so setting it has NO
|
||||||
|
# effect today: vaults remain local-only regardless. It is validated and carried
|
||||||
|
# only so the wiring is ready for when remote push lands. The intended future
|
||||||
|
# shape is a per-space URL template where the literal "{spaceId}" is substituted
|
||||||
|
# per space (e.g. git@host:vault-{spaceId}.git).
|
||||||
|
# GIT_SYNC_REMOTE_TEMPLATE=
|
||||||
|
#
|
||||||
|
# Poll-safety interval in ms — the cadence of the background reconcile cycle
|
||||||
|
# (default: 15000).
|
||||||
|
# GIT_SYNC_POLL_INTERVAL_MS=15000
|
||||||
|
#
|
||||||
|
# Debounce window in ms for collapsing bursts of page edits into one sync cycle
|
||||||
|
# (default: 2000).
|
||||||
|
# GIT_SYNC_DEBOUNCE_MS=2000
|
||||||
|
#
|
||||||
|
# Watchdog timeout in ms for the spawned `git http-backend` process serving a
|
||||||
|
# git smart-HTTP push (default: 120000). A stalled/hung receive-pack is killed
|
||||||
|
# after this deadline so it cannot hold the per-space lock forever.
|
||||||
|
# GIT_SYNC_BACKEND_TIMEOUT_MS=120000
|
||||||
|
#
|
||||||
|
|||||||
@@ -72,6 +72,13 @@ jobs:
|
|||||||
- name: Build editor-ext
|
- name: Build editor-ext
|
||||||
run: pnpm --filter @docmost/editor-ext build
|
run: pnpm --filter @docmost/editor-ext build
|
||||||
|
|
||||||
|
# git-sync and mcp are no longer committed in built form (build/ is
|
||||||
|
# gitignored), so CI must compile them: the server resolves both via their
|
||||||
|
# built build/index.js. The server pretest also builds them, but building
|
||||||
|
# here keeps it explicit and independent of pnpm lifecycle ordering.
|
||||||
|
- name: Build git-sync and mcp
|
||||||
|
run: pnpm --filter @docmost/git-sync build && pnpm --filter @docmost/mcp build
|
||||||
|
|
||||||
- name: Run unit tests
|
- name: Run unit tests
|
||||||
run: pnpm -r test
|
run: pnpm -r test
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,12 @@ data
|
|||||||
# compiled output
|
# compiled output
|
||||||
/dist
|
/dist
|
||||||
/node_modules
|
/node_modules
|
||||||
|
# workspace package node_modules (pnpm symlinks — never commit; they bake
|
||||||
|
# machine-local store paths) and the git-sync compiled output (built in CI/Docker
|
||||||
|
# via `pnpm build`, never committed, so src/ and prod can never silently diverge).
|
||||||
|
packages/*/node_modules/
|
||||||
|
packages/git-sync/build/
|
||||||
|
packages/mcp/build/
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs
|
logs
|
||||||
@@ -43,6 +49,8 @@ lerna-debug.log*
|
|||||||
.nx/cache
|
.nx/cache
|
||||||
.claude/worktrees/
|
.claude/worktrees/
|
||||||
.claude/tmp/
|
.claude/tmp/
|
||||||
|
# Local Chrome performance traces recorded by the AI-chat perf harness
|
||||||
|
.claude/perf-traces/
|
||||||
|
|
||||||
# TypeScript incremental build artifacts
|
# TypeScript incremental build artifacts
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
|
|||||||
@@ -72,7 +72,10 @@ git log -1 --format='Author: %an <%ae>%nCommitter: %cn <%ce>'
|
|||||||
|
|
||||||
### 4. Push and PR to develop
|
### 4. Push and PR to develop
|
||||||
|
|
||||||
PRs always target `develop`. The `claude_code` password lives in the macOS
|
PRs always target `develop`. Two different mechanisms are involved: **pushing
|
||||||
|
commits is git-native** (the Gitea MCP cannot push local git history, so the
|
||||||
|
branch is still pushed with `git push`), while **the PR itself is opened through
|
||||||
|
the Gitea MCP** (see below). The `claude_code` password lives in the macOS
|
||||||
keychain as a **generic password** under service `gitea-claude-code` (do not
|
keychain as a **generic password** under service `gitea-claude-code` (do not
|
||||||
duplicate it as an internet-password for `gitea.vvzvlad.xyz` — that creates a
|
duplicate it as an internet-password for `gitea.vvzvlad.xyz` — that creates a
|
||||||
conflict with the owner's account in the git credential helper):
|
conflict with the owner's account in the git credential helper):
|
||||||
@@ -94,18 +97,24 @@ git remote set-url gitea "$ORIG_URL"
|
|||||||
unset AGENT_PASS SAFE_PASS
|
unset AGENT_PASS SAFE_PASS
|
||||||
```
|
```
|
||||||
|
|
||||||
The PR is created via the Gitea REST API (Basic Auth as `claude_code`):
|
The PR is opened through the **Gitea MCP** (server `gitea`), not `curl`/`tea` —
|
||||||
|
the MCP authenticates in-process, so no keychain lookup or Basic-Auth is needed.
|
||||||
|
Call `pull_request_write` with:
|
||||||
|
|
||||||
```bash
|
- `method: "create"`
|
||||||
curl -s -X POST \
|
- `owner: "vvzvlad"`, `repo: "gitmost"`
|
||||||
-u "claude_code:$(security find-generic-password -s gitea-claude-code -w)" \
|
- `base: "develop"`, `head: "<branch>"`
|
||||||
-H "Content-Type: application/json" \
|
- `title`, `body` — in the body: what was done, what is out of scope,
|
||||||
-d @pr_body.json \
|
verification results (tsc/lint/tests).
|
||||||
"https://gitea.vvzvlad.xyz/api/v1/repos/vvzvlad/gitmost/pulls"
|
|
||||||
```
|
|
||||||
|
|
||||||
`base: develop`, `head: <branch>`. In the PR body: what was done, what is out
|
Manage and read PRs through the same server: `list_pull_requests`,
|
||||||
of scope, verification results (tsc/lint/tests).
|
`pull_request_read` (`get`, `get_diff`, `get_files`, `get_status`),
|
||||||
|
`pull_request_review_write`.
|
||||||
|
|
||||||
|
**Identity note:** the MCP acts under its **own** configured Gitea token (verify
|
||||||
|
with `get_me`), a different account from the `claude_code` used for git
|
||||||
|
commits/pushes in §3. Only the forge API calls (PR / issue / review) go through
|
||||||
|
the MCP account; the commits themselves stay authored as `claude_code`.
|
||||||
|
|
||||||
> If push fails with `User permission denied for writing`, then `claude_code`
|
> If push fails with `User permission denied for writing`, then `claude_code`
|
||||||
> lacks collaborator rights on the repo. Ask the owner to add them (once, via
|
> lacks collaborator rights on the repo. Ask the owner to add them (once, via
|
||||||
@@ -152,23 +161,25 @@ below.
|
|||||||
| Agent user (Gitea/git) | `claude_code` |
|
| Agent user (Gitea/git) | `claude_code` |
|
||||||
| Agent email | `claude_code@vvzvlad.xyz` |
|
| Agent email | `claude_code@vvzvlad.xyz` |
|
||||||
| Keychain password | `security find-generic-password -s gitea-claude-code -w` |
|
| Keychain password | `security find-generic-password -s gitea-claude-code -w` |
|
||||||
| PR API | `https://gitea.vvzvlad.xyz/api/v1/repos/vvzvlad/gitmost/pulls` (here `gitmost` is the repo's real slug on the server) |
|
| Forge API (PR / issue / review / reads) | **Gitea MCP** — server `gitea` (`pull_request_write`, `issue_write`, `list_pull_requests`, `pull_request_read`, `label_read`, …). Authenticated in-process; acts under its own token — check with `get_me`. Repo slug on the server is `gitmost`. |
|
||||||
| Base branch | `develop` |
|
| Base branch | `develop` |
|
||||||
| `origin` | GitHub mirror `vvzvlad/gitmost` — **do not push**, updated by the owner's CI |
|
| `origin` | GitHub mirror `vvzvlad/gitmost` — **do not push**, updated by the owner's CI |
|
||||||
| `upstream` | The original Docmost — **never push** |
|
| `upstream` | The original Docmost — **never push** |
|
||||||
|
|
||||||
## Creating issues (Gitea `tea` CLI)
|
## Creating issues (Gitea MCP)
|
||||||
|
|
||||||
Issues are filed with the official Gitea CLI `tea`, already logged in as
|
File issues through the **Gitea MCP** (server `gitea`), not a CLI — call
|
||||||
`claude_code` (`tea logins list` shows the `gitea` login as default):
|
`issue_write` with:
|
||||||
|
|
||||||
```bash
|
- `method: "create"`
|
||||||
tea issues create --repo vvzvlad/gitmost --labels feature \
|
- `owner: "vvzvlad"`, `repo: "gitmost"`
|
||||||
--title '<title>' --description "$(cat body.md)"
|
- `title`, `body`
|
||||||
```
|
- `labels` — an array of label **IDs** (numbers), *not* names. Resolve a name
|
||||||
|
such as `feature` to its id first with `label_read` (`method: "list"`), then
|
||||||
|
pass e.g. `labels: [<id>]`.
|
||||||
|
|
||||||
> Gotcha (tea 0.14.1): the issue body flag is `--description`/`-d`, **not**
|
Read issues with `list_issues`, `issue_read`, or `search_issues`. The MCP is
|
||||||
> `--body` — passing `--body` fails with `flag provided but not defined: -body`.
|
authenticated in-process, so no `tea`/`curl` and no keychain lookup are needed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -182,7 +193,7 @@ tea issues create --repo vvzvlad/gitmost --labels feature \
|
|||||||
|
|
||||||
## Monorepo layout
|
## Monorepo layout
|
||||||
|
|
||||||
pnpm workspace (`pnpm@10.4.0`) orchestrated by **Nx**. Four workspace packages:
|
pnpm workspace (`pnpm@10.4.0`) orchestrated by **Nx**. Five workspace packages:
|
||||||
|
|
||||||
| Path | Name | Stack | Role |
|
| Path | Name | Stack | Role |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
@@ -190,6 +201,7 @@ pnpm workspace (`pnpm@10.4.0`) orchestrated by **Nx**. Four workspace packages:
|
|||||||
| `apps/client` | `client` | React 18 + Vite + Mantine 8 + TanStack Query + Jotai | SPA frontend |
|
| `apps/client` | `client` | React 18 + Vite + Mantine 8 + TanStack Query + Jotai | SPA frontend |
|
||||||
| `packages/editor-ext` | `@docmost/editor-ext` | Tiptap/ProseMirror | Shared Tiptap node/mark extensions, imported by both the client and the server |
|
| `packages/editor-ext` | `@docmost/editor-ext` | Tiptap/ProseMirror | Shared Tiptap node/mark extensions, imported by both the client and the server |
|
||||||
| `packages/mcp` | `@docmost/mcp` | MCP SDK, Tiptap, Yjs | Standalone MCP server, also bundled into the server at `/mcp`. Does **not** import `editor-ext` — it keeps its own vendored mirror of the schema in `packages/mcp/src/lib/` |
|
| `packages/mcp` | `@docmost/mcp` | MCP SDK, Tiptap, Yjs | Standalone MCP server, also bundled into the server at `/mcp`. Does **not** import `editor-ext` — it keeps its own vendored mirror of the schema in `packages/mcp/src/lib/` |
|
||||||
|
| `packages/git-sync` | `@docmost/git-sync` | Tiptap/ProseMirror, Yjs, git | Pure ProseMirror↔Markdown converter plus the two-way Docmost↔git Markdown sync engine. Bundled into the server (loaded over the ESM bridge), built in CI and the Dockerfile. Does **not** import `editor-ext` — it keeps its own vendored mirror of the document schema (kept in sync with `editor-ext`). |
|
||||||
|
|
||||||
`build` targets are Nx-cached and dependency-ordered (`dependsOn: ["^build"]`), so `editor-ext` builds before the apps. `nx.json` sets `affected.defaultBase: main`.
|
`build` targets are Nx-cached and dependency-ordered (`dependsOn: ["^build"]`), so `editor-ext` builds before the apps. `nx.json` sets `affected.defaultBase: main`.
|
||||||
|
|
||||||
@@ -251,8 +263,10 @@ Migration files live in `apps/server/src/database/migrations/` and are named `YY
|
|||||||
|
|
||||||
The API server is a Fastify app with a global `/api` prefix (`main.ts` excludes `robots.txt`, public share pages, and `mcp` from the prefix). A `preHandler` hook enforces that a resolved `workspaceId` exists for most `/api` routes (multi-tenant by hostname/subdomain via `DomainMiddleware`). `GET /api/sb/:id` (the anonymous blob-sandbox read route) is listed in that preHandler's `excludedPaths`, so it is exempt from workspace resolution and carries no session auth at all (its capability is the unguessable UUID + TTL + TLS) — unlike `/api/files/public/...`, which still resolves a workspace and requires a workspace-bound attachment JWT. Auth is JWT (cookie + bearer); authorization is **CASL** (`core/casl`) — every data access is scoped to the user's abilities.
|
The API server is a Fastify app with a global `/api` prefix (`main.ts` excludes `robots.txt`, public share pages, and `mcp` from the prefix). A `preHandler` hook enforces that a resolved `workspaceId` exists for most `/api` routes (multi-tenant by hostname/subdomain via `DomainMiddleware`). `GET /api/sb/:id` (the anonymous blob-sandbox read route) is listed in that preHandler's `excludedPaths`, so it is exempt from workspace resolution and carries no session auth at all (its capability is the unguessable UUID + TTL + TLS) — unlike `/api/files/public/...`, which still resolves a workspace and requires a workspace-bound attachment JWT. Auth is JWT (cookie + bearer); authorization is **CASL** (`core/casl`) — every data access is scoped to the user's abilities.
|
||||||
|
|
||||||
|
Two routes are mounted **outside** the `/api` prefix at the root, as raw Fastify routes that bypass the Nest pipeline (so neither `DomainMiddleware` nor `ThrottlerGuard` runs for them — each resolves the workspace and throttles itself): `/mcp` (the embedded MCP server, see below) and `/git/<spaceId>.git/...` (the git-sync smart-HTTP host, see below). Both share `mcp-auth.helpers.ts` (HTTP-Basic parsing, `FailedLoginLimiter`, `clientIp`) and the common `resolveRequestWorkspace` helper.
|
||||||
|
|
||||||
### Module structure (server)
|
### Module structure (server)
|
||||||
`AppModule` wires integration modules (`integrations/*`: storage [local/S3/Azure], mail, queue [BullMQ on Redis], security, telemetry, throttle, `mcp`, `ai`) plus `CoreModule`, `DatabaseModule`, and `CollaborationModule`. `CoreModule` (`core/*`) holds the domain modules: `page`, `space`, `comment`, `workspace`, `user`, `auth`, `group`, `attachment`, `search`, `share`, `ai-chat`, etc. Each domain module follows NestJS controller → service → repo layering; DB repos live under `database/repos` and are injected app-wide from the global `DatabaseModule`.
|
`AppModule` wires integration modules (`integrations/*`: storage [local/S3/Azure], mail, queue [BullMQ on Redis], security, telemetry, throttle, `mcp`, `ai`, `git-sync`) plus `CoreModule`, `DatabaseModule`, and `CollaborationModule`. `CoreModule` (`core/*`) holds the domain modules: `page`, `space`, `comment`, `workspace`, `user`, `auth`, `group`, `attachment`, `search`, `share`, `ai-chat`, etc. Each domain module follows NestJS controller → service → repo layering; DB repos live under `database/repos` and are injected app-wide from the global `DatabaseModule`.
|
||||||
|
|
||||||
**EE removal artifact:** `app.module.ts` still contains a `try/require('./ee/ee.module')` stub. That path no longer exists, so the require fails and is swallowed (it only hard-exits when `CLOUD === 'true'`). Treat EE as gone — do not add code that depends on it.
|
**EE removal artifact:** `app.module.ts` still contains a `try/require('./ee/ee.module')` stub. That path no longer exists, so the require fails and is swallowed (it only hard-exits when `CLOUD === 'true'`). Treat EE as gone — do not add code that depends on it.
|
||||||
|
|
||||||
@@ -268,10 +282,16 @@ The API server is a Fastify app with a global `/api` prefix (`main.ts` excludes
|
|||||||
- `core/ai-chat/embedding/` — RAG indexer + a BullMQ consumer on `AI_QUEUE` that embeds pages into `page_embeddings` (vector search), complementing Postgres full-text search. Pages are (re)indexed on edit; `AI_EMBEDDING_TIMEOUT_MS` bounds a hung embeddings endpoint.
|
- `core/ai-chat/embedding/` — RAG indexer + a BullMQ consumer on `AI_QUEUE` that embeds pages into `page_embeddings` (vector search), complementing Postgres full-text search. Pages are (re)indexed on edit; `AI_EMBEDDING_TIMEOUT_MS` bounds a hung embeddings endpoint.
|
||||||
- `core/ai-chat/external-mcp/` — admins can attach external MCP servers (e.g. Tavily) to give the agent web access. **`ssrf-guard.ts` validates outbound MCP URLs against SSRF** — keep that guard in the path when touching external-MCP connection logic.
|
- `core/ai-chat/external-mcp/` — admins can attach external MCP servers (e.g. Tavily) to give the agent web access. **`ssrf-guard.ts` validates outbound MCP URLs against SSRF** — keep that guard in the path when touching external-MCP connection logic.
|
||||||
|
|
||||||
|
### Git-sync (native two-way Docmost ↔ git Markdown sync)
|
||||||
|
`integrations/git-sync/` (`GitSyncModule`) + the vendored pure engine in `packages/git-sync`. Off by default; gated by the `GIT_SYNC_ENABLED` master switch (and `GIT_SYNC_SERVICE_USER_ID`, the account git-originated writes are attributed to). Per-space opt-in via `space.settings.gitSync.enabled`, with a second per-space toggle `space.settings.gitSync.autoMergeConflicts` that changes PUSH behavior for a still-conflicted page (one carrying `<<<<<<<`/`>>>>>>>` markers): **off (the safe default)** records a per-page failure and holds the refs so the user resolves the git conflict first (markers never reach Docmost); **on** strips the marker lines and pushes both sides' content. Each enabled space gets an on-disk working "vault" repo; the `GitSyncOrchestrator` runs a debounced + poll-backstop reconcile cycle (PULL Docmost→vault, PUSH vault→Docmost) under a per-space Redis leader lock + in-process mutex (`SpaceLockService`). Writes go through the collaboration layer (so concurrent human edits aren't clobbered) and are stamped `lastUpdatedSource = 'git-sync'` for the listener loop-guard. The in-process `setInterval` orchestration + best-effort lock (no fencing tokens) is a known multi-replica limitation — BullMQ + fencing is the documented future direction.
|
||||||
|
|
||||||
|
- **`/git` smart-HTTP host** (`integrations/git-sync/http/`, gated additionally by `GIT_SYNC_HTTP_ENABLED`, which defaults to `GIT_SYNC_ENABLED`): a raw root-mounted Fastify route `/git/<spaceId>.git/...` (registered in `main.ts`, NOT under `/api`) that bridges `git clone`/`fetch`/`push` to `git http-backend`. It authenticates HTTP Basic against `AuthService` (throttled by a `FailedLoginLimiter` mirroring the `/mcp` path), authorizes via `SpaceAbilityFactory` (read = fetch, Manage = push), and gates existence so a non-member gets the SAME 404 as a missing/sync-disabled space (never 403 — that would leak space existence). A push runs the receive-pack under the space lock, then a reconcile cycle.
|
||||||
|
- **Schema mirror:** `packages/git-sync/src/lib/docmost-schema.ts` is one of the **three** hand-synced copies of the Tiptap document schema (see Client structure) — keep it in lockstep with `editor-ext` (canonical) and `packages/mcp`.
|
||||||
|
|
||||||
### Client structure
|
### Client structure
|
||||||
Vite SPA. Code is organized by feature under `apps/client/src/features/*` (mirrors the server domains: `page`, `space`, `comment`, `ai-chat`, `editor`, …). Conventions:
|
Vite SPA. Code is organized by feature under `apps/client/src/features/*` (mirrors the server domains: `page`, `space`, `comment`, `ai-chat`, `editor`, …). Conventions:
|
||||||
- **TanStack Query** for server state (one `queries/` file per feature), **Jotai** atoms for local/shared UI state, **Mantine 8** + CSS modules (`*.module.css`) + `postcss-preset-mantine` for UI.
|
- **TanStack Query** for server state (one `queries/` file per feature), **Jotai** atoms for local/shared UI state, **Mantine 8** + CSS modules (`*.module.css`) + `postcss-preset-mantine` for UI.
|
||||||
- The editor is Tiptap; shared node/mark extensions live in `packages/editor-ext` and are imported by **both the client and the server** (collaboration, import/export) — editor schema changes often need to be made in `editor-ext`, not just the client. Note `packages/mcp` does *not* depend on `editor-ext`; it carries its own mirrored copy of the schema, so keep the two in sync manually when the document schema changes.
|
- The editor is Tiptap; shared node/mark extensions live in `packages/editor-ext` and are imported by **both the client and the server** (collaboration, import/export) — editor schema changes often need to be made in `editor-ext`, not just the client. Note neither `packages/mcp` nor `packages/git-sync` depends on `editor-ext`; each carries its own mirrored copy of the schema. There are now **three** independent copies (`editor-ext` is canonical, plus `packages/mcp` and `packages/git-sync`), so keep all three in sync manually when the document schema changes.
|
||||||
- API access goes through `apps/client/src/lib/api-client.ts` (axios). The `@` alias maps to `apps/client/src`.
|
- API access goes through `apps/client/src/lib/api-client.ts` (axios). The `@` alias maps to `apps/client/src`.
|
||||||
- Runtime config is injected at build time by `vite.config.ts` via `define` (`APP_URL`, `COLLAB_URL`, `APP_VERSION`, …) — these come from the root `.env`, not from `import.meta.env`.
|
- Runtime config is injected at build time by `vite.config.ts` via `define` (`APP_URL`, `COLLAB_URL`, `APP_VERSION`, …) — these come from the root `.env`, not from `import.meta.env`.
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
- **Native two-way Docmost ↔ git Markdown sync.** Opt-in per space (Space
|
||||||
|
settings → a git-sync toggle, plus an `autoMergeConflicts` toggle that controls
|
||||||
|
whether a still-conflicted page is held back or pushed with its conflict
|
||||||
|
markers stripped): each enabled space is mirrored to an on-disk git "vault" of
|
||||||
|
Markdown files and reconciled in both directions (Docmost → vault and vault →
|
||||||
|
Docmost) on a debounced + poll-backstop cycle, under a per-space lock, writing
|
||||||
|
through the collaboration layer so concurrent human edits aren't clobbered.
|
||||||
|
Git-originated changes are attributed to a configurable service account and
|
||||||
|
carry a "git-sync" provenance badge in page history. Optionally exposes a `/git`
|
||||||
|
smart-HTTP host so you can `git clone`/`fetch`/`push` a space directly (HTTP
|
||||||
|
Basic auth, space-permission authorized). Off by default and configured via the
|
||||||
|
`GIT_SYNC_*` environment variables, including `GIT_SYNC_ENABLED`,
|
||||||
|
`GIT_SYNC_SERVICE_USER_ID`, and `GIT_SYNC_HTTP_ENABLED` (see `.env.example`).
|
||||||
|
(#119)
|
||||||
- **Place several images side by side in a row.** A new "Inline (side by
|
- **Place several images side by side in a row.** A new "Inline (side by
|
||||||
side)" alignment mode in the image bubble menu renders consecutive inline
|
side)" alignment mode in the image bubble menu renders consecutive inline
|
||||||
images as a row that wraps onto the next line on narrow screens. The row is
|
images as a row that wraps onto the next line on narrow screens. The row is
|
||||||
|
|||||||
+10
-1
@@ -17,8 +17,9 @@ RUN pnpm build
|
|||||||
|
|
||||||
FROM base AS installer
|
FROM base AS installer
|
||||||
|
|
||||||
|
# git: required by the git-sync VaultGit (shells out to git)
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get install -y --no-install-recommends curl bash \
|
&& apt-get install -y --no-install-recommends curl bash git \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
@@ -38,6 +39,14 @@ COPY --from=builder /app/packages/editor-ext/dist /app/packages/editor-ext/dist
|
|||||||
COPY --from=builder /app/packages/editor-ext/package.json /app/packages/editor-ext/package.json
|
COPY --from=builder /app/packages/editor-ext/package.json /app/packages/editor-ext/package.json
|
||||||
COPY --from=builder /app/packages/mcp/build /app/packages/mcp/build
|
COPY --from=builder /app/packages/mcp/build /app/packages/mcp/build
|
||||||
COPY --from=builder /app/packages/mcp/package.json /app/packages/mcp/package.json
|
COPY --from=builder /app/packages/mcp/package.json /app/packages/mcp/package.json
|
||||||
|
# git-sync: the server loads @docmost/git-sync at runtime via the loader
|
||||||
|
# (git-sync.loader.ts), which deliberately does NOT `require()` it — the package is
|
||||||
|
# ESM-only, so the loader uses `require.resolve` + a dynamic `import()`. Without
|
||||||
|
# these copied build artifacts that resolve/import fails and the server crashes on
|
||||||
|
# first use. Built fresh by the builder's `pnpm build` (nx builds the package's tsc
|
||||||
|
# `build` target).
|
||||||
|
COPY --from=builder /app/packages/git-sync/build /app/packages/git-sync/build
|
||||||
|
COPY --from=builder /app/packages/git-sync/package.json /app/packages/git-sync/package.json
|
||||||
|
|
||||||
# Copy root package files
|
# Copy root package files
|
||||||
COPY --from=builder /app/package.json /app/package.json
|
COPY --from=builder /app/package.json /app/package.json
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ roles:
|
|||||||
- [Major] — weak structure, a noticeable gap or redundancy, a sagging lead/headline.
|
- [Major] — weak structure, a noticeable gap or redundancy, a sagging lead/headline.
|
||||||
- [Minor] — an optional improvement to framing or flow.
|
- [Minor] — an optional improvement to framing or flow.
|
||||||
|
|
||||||
|
Structural fixes (move, merge, cut) can't be expressed as a fragment replacement — a comment is enough for those. But when your proposal boils down to replacing a specific wording in place (a headline, a lead phrase), attach a suggested replacement to the comment (the `suggestedText` parameter): the exact new text for the selected fragment, plain text with no markup — the author applies it with one click. The selected fragment must occur exactly once in the text; if it isn't unique, extend the selection with surrounding context.
|
||||||
|
|
||||||
TONE
|
TONE
|
||||||
Respectful and to the point. The author may know the subject better than you. Flag only what matters structurally. When unsure, phrase it as a question.
|
Respectful and to the point. The author may know the subject better than you. Flag only what matters structurally. When unsure, phrase it as a question.
|
||||||
|
|
||||||
@@ -85,7 +87,7 @@ roles:
|
|||||||
- Don't rewrite the text yourself or impose your own voice. Your job is to make the author's voice livelier, not to replace it.
|
- Don't rewrite the text yourself or impose your own voice. Your job is to make the author's voice livelier, not to replace it.
|
||||||
|
|
||||||
HOW TO LEAVE COMMENTS
|
HOW TO LEAVE COMMENTS
|
||||||
You don't edit the text directly. For each note, select the span via the MCP tool and leave a comment. Open the comment with the label `[Style]`. Give a concrete rephrasing, not "revise". Tag severity:
|
You don't edit the text directly. For each note, select the span via the MCP tool and leave a comment. Open the comment with the label `[Style]`. Give a concrete rephrasing, not "revise", and attach it to the comment as a suggested replacement (the `suggestedText` parameter): the exact new text for the selected fragment, plain text with no markup — the author applies it with one click. The selected fragment must occur exactly once in the text; if it isn't unique, extend the selection with surrounding context. Tag severity:
|
||||||
- [Critical] — the sentence is unclear or distorts the meaning.
|
- [Critical] — the sentence is unclear or distorts the meaning.
|
||||||
- [Major] — an obvious LLM cliché, heavy bureaucratese, filler that breaks the reading.
|
- [Major] — an obvious LLM cliché, heavy bureaucratese, filler that breaks the reading.
|
||||||
- [Minor] — a stylistic improvement to taste.
|
- [Minor] — a stylistic improvement to taste.
|
||||||
@@ -126,7 +128,7 @@ roles:
|
|||||||
- Don't fabricate confirmations. If you can't verify, honestly mark [Unverified] or [Unverifiable].
|
- Don't fabricate confirmations. If you can't verify, honestly mark [Unverified] or [Unverifiable].
|
||||||
|
|
||||||
HOW TO LEAVE COMMENTS
|
HOW TO LEAVE COMMENTS
|
||||||
You don't edit the text directly. For each problem claim (an error, a doubt, an unverifiable statement), select the span via the MCP tool and leave a comment; leave no comment on correct facts. Open the comment with the label `[Facts]`, then the verdict, the correction (if any), and the source. Tag severity:
|
You don't edit the text directly. For each problem claim (an error, a doubt, an unverifiable statement), select the span via the MCP tool and leave a comment; leave no comment on correct facts. Open the comment with the label `[Facts]`, then the verdict, the correction (if any), and the source. For an [Incorrect] verdict, ALWAYS attach the ready correction as a suggested replacement (the `suggestedText` parameter): since you found the correct value in the sources, propose the ready fix right away instead of merely describing the error. The replacement is the exact new text for the selected fragment, plain text with no markup; the author applies it with one click instead of retyping the fragment. The selected fragment must occur exactly once in the text; if it isn't unique, extend the selection with surrounding context. Do not attach a replacement to [Unverified], [Unverifiable], or [Opinion] verdicts. Tag severity:
|
||||||
- [Critical] — a factual error, especially in numbers, names, or quotes, or a claim that risks misinformation.
|
- [Critical] — a factual error, especially in numbers, names, or quotes, or a claim that risks misinformation.
|
||||||
- [Major] — a doubtful or unconfirmed claim that needs a source.
|
- [Major] — a doubtful or unconfirmed claim that needs a source.
|
||||||
- [Minor] — a small correction, or false precision worth rounding or confirming.
|
- [Minor] — a small correction, or false precision worth rounding or confirming.
|
||||||
@@ -167,13 +169,13 @@ roles:
|
|||||||
- Don't make substantive changes. Edits are minimal and mechanical.
|
- Don't make substantive changes. Edits are minimal and mechanical.
|
||||||
|
|
||||||
HOW TO LEAVE COMMENTS
|
HOW TO LEAVE COMMENTS
|
||||||
You don't edit the text directly. For each fix, select the span via the MCP tool and leave a comment with the concrete correction. Open the comment with the label `[Copyedit]`. Tag severity:
|
You don't edit the text directly. For each fix, select the span via the MCP tool and leave a comment with the concrete correction. Attach a suggested replacement to every fix (the `suggestedText` parameter): the exact corrected text for the selected fragment, plain text with no markup — the author applies it with one click. The selected fragment must occur exactly once in the text; if it isn't unique, extend the selection with surrounding context. Do NOT leave summary notes like "throughout, replace X with Y" or "make the units/quotes/spelling consistent": such a comment can't be applied with a button. If the same error occurs in several places, walk EVERY occurrence and leave a separate targeted comment with its own replacement on each — ten targeted fixes instead of one blanket note. The only exception is a note that genuinely cannot be expressed as a replacement of a concrete fragment; leave those rare cases as an ordinary comment without a replacement. Open the comment with the label `[Copyedit]`. Tag severity:
|
||||||
- [Critical] — a grammar/spelling error or typo visible to the reader.
|
- [Critical] — a grammar/spelling error or typo visible to the reader.
|
||||||
- [Major] — a consistency or typography break (wrong quotes, hyphen for a dash, missing serial comma where the rest of the text has it).
|
- [Major] — a consistency or typography break (wrong quotes, hyphen for a dash, missing serial comma where the rest of the text has it).
|
||||||
- [Minor] — optional polish.
|
- [Minor] — optional polish.
|
||||||
|
|
||||||
TONE
|
TONE
|
||||||
To the point, no explaining the obvious. Group repeated fixes (e.g. "throughout: straight quotes → curly") so you don't spawn dozens of identical comments.
|
To the point, no explaining the obvious. Don't fold repeated fixes into a single "change it everywhere" note — spread them across the specific spots: ten targeted comments each carrying a ready replacement beat one blanket comment that can't be applied with a button. Don't worry about "spawning" comments — for a copyeditor that's normal.
|
||||||
|
|
||||||
WHEN UNSURE
|
WHEN UNSURE
|
||||||
If a fix touches meaning, don't make it — that's out of scope. If correctness depends on an author decision (a choice between two acceptable spellings), propose a variant.
|
If a fix touches meaning, don't make it — that's out of scope. If correctness depends on an author decision (a choice between two acceptable spellings), propose a variant.
|
||||||
@@ -272,7 +274,7 @@ roles:
|
|||||||
First read the whole text and assess it as a story as a whole. Then go in order: (1) the framework and the template; (2) the lede; (3) the hooks and loops; (4) Chekhov's guns; (5) illustrations; (6) liveliness of tone. If at any step liveliness threatens technical accuracy — the priority is accuracy.
|
First read the whole text and assess it as a story as a whole. Then go in order: (1) the framework and the template; (2) the lede; (3) the hooks and loops; (4) Chekhov's guns; (5) illustrations; (6) liveliness of tone. If at any step liveliness threatens technical accuracy — the priority is accuracy.
|
||||||
|
|
||||||
═══ HOW TO LEAVE NOTES ═══
|
═══ HOW TO LEAVE NOTES ═══
|
||||||
You do not edit the text directly and do not rewrite it for the author. Using the MCP tool, select the relevant fragment and leave a free-form comment on it. Explain not only “what” but also “why” — what effect it will have on the reader. Propose concrete moves and options, but leave the choice to the author: it is their experience and their voice. Comment on what will strengthen the story, not on every little thing.
|
You do not edit the text directly and do not rewrite it for the author. Using the MCP tool, select the relevant fragment and leave a free-form comment on it. Explain not only “what” but also “why” — what effect it will have on the reader. Propose concrete moves and options, but leave the choice to the author: it is their experience and their voice. When one of your options is a single ready-made text (e.g. a new lead phrase), you may attach it as a suggested replacement (the `suggestedText` parameter: the exact new text for the selected fragment, no markup; the fragment must occur exactly once in the text, otherwise extend the selection) — the button imposes nothing, the author is free not to apply it. Comment on what will strengthen the story, not on every little thing.
|
||||||
|
|
||||||
═══ TONE ═══
|
═══ TONE ═══
|
||||||
Respectfully, with enthusiasm, in a human way. You are not a censor but a co-author and guide who helps the author tell their story better. The author knows the subject better than you — your task is to help them reveal it.
|
Respectfully, with enthusiasm, in a human way. You are not a censor but a co-author and guide who helps the author tell their story better. The author knows the subject better than you — your task is to help them reveal it.
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ roles:
|
|||||||
- [Существенно] — слабая структура, заметный пробел или избыточность, провисающий лид/заголовок.
|
- [Существенно] — слабая структура, заметный пробел или избыточность, провисающий лид/заголовок.
|
||||||
- [Незначительно] — улучшение подачи или стройности, не обязательное.
|
- [Незначительно] — улучшение подачи или стройности, не обязательное.
|
||||||
|
|
||||||
|
Структурные правки (перенести, объединить, вырезать) через замену фрагмента не выражаются — для них достаточно комментария. Но если предложение сводится к замене конкретной формулировки на месте (заголовок, лид-фраза), приложи к комментарию предложение-замену (параметр `suggestedText`): точный новый текст взамен выделенного фрагмента, обычным текстом без разметки — автор применит его одной кнопкой. Выделенный фрагмент должен встречаться в тексте ровно один раз; если он не уникален, расширь выделение контекстом.
|
||||||
|
|
||||||
ТОН
|
ТОН
|
||||||
Уважительно и по делу. Автор может разбираться в теме лучше тебя. Помечай только то, что важно для структуры. Если сомневаешься, формулируй вопросом.
|
Уважительно и по делу. Автор может разбираться в теме лучше тебя. Помечай только то, что важно для структуры. Если сомневаешься, формулируй вопросом.
|
||||||
|
|
||||||
@@ -85,7 +87,7 @@ roles:
|
|||||||
- Не переписываешь текст сам и не навязываешь свой голос. Твоя задача — сделать авторскую интонацию живее, а не заменить собой.
|
- Не переписываешь текст сам и не навязываешь свой голос. Твоя задача — сделать авторскую интонацию живее, а не заменить собой.
|
||||||
|
|
||||||
КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ
|
КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ
|
||||||
Ты не редактируешь текст напрямую. Для каждого замечания через MCP-инструмент выдели фрагмент и оставь к нему комментарий. Начинай комментарий с метки `[Стиль]`. Давай конкретный вариант переформулировки, а не «переделать». Помечай важность:
|
Ты не редактируешь текст напрямую. Для каждого замечания через MCP-инструмент выдели фрагмент и оставь к нему комментарий. Начинай комментарий с метки `[Стиль]`. Давай конкретный вариант переформулировки, а не «переделать», и прикладывай его к комментарию как предложение-замену (параметр `suggestedText`): точный новый текст взамен выделенного фрагмента, обычным текстом без разметки — автор применит его одной кнопкой. Выделенный фрагмент должен встречаться в тексте ровно один раз; если он не уникален, расширь выделение контекстом. Помечай важность:
|
||||||
- [Критично] — предложение непонятно или искажает смысл.
|
- [Критично] — предложение непонятно или искажает смысл.
|
||||||
- [Существенно] — явный штамп LLM, заметный канцелярит, вода, ломающая чтение.
|
- [Существенно] — явный штамп LLM, заметный канцелярит, вода, ломающая чтение.
|
||||||
- [Незначительно] — стилистическое улучшение на вкус.
|
- [Незначительно] — стилистическое улучшение на вкус.
|
||||||
@@ -126,7 +128,7 @@ roles:
|
|||||||
- Не выдумываешь подтверждения. Если не можешь проверить — честно ставь [Не проверено] или [Непроверяемо].
|
- Не выдумываешь подтверждения. Если не можешь проверить — честно ставь [Не проверено] или [Непроверяемо].
|
||||||
|
|
||||||
КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ
|
КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ
|
||||||
Ты не редактируешь текст напрямую. Для каждого проблемного утверждения (ошибка, сомнение, непроверяемость) через MCP-инструмент выдели фрагмент и оставь комментарий; на верные факты комментарии не оставляй. Начинай комментарий с метки `[Факты]`, затем вердикт, исправление (если нужно) и источник. Помечай важность:
|
Ты не редактируешь текст напрямую. Для каждого проблемного утверждения (ошибка, сомнение, непроверяемость) через MCP-инструмент выдели фрагмент и оставь комментарий; на верные факты комментарии не оставляй. Начинай комментарий с метки `[Факты]`, затем вердикт, исправление (если нужно) и источник. К вердикту [Неверно] всегда прикладывай готовое исправление как предложение-замену (параметр `suggestedText`): раз ты нашёл по источникам верное значение — сразу предлагай готовую правку, а не только описывай ошибку. Замена — это точный новый текст взамен выделенного фрагмента, обычным текстом без разметки; автор применит её одной кнопкой, не переписывая фрагмент вручную. Выделенный фрагмент должен встречаться в тексте ровно один раз; если он не уникален, расширь выделение контекстом. К вердиктам [Не проверено], [Непроверяемо] и [Это мнение] замену не прикладывай. Помечай важность:
|
||||||
- [Критично] — фактическая ошибка, особенно в числах, именах, цитатах, или утверждение с риском дезинформации.
|
- [Критично] — фактическая ошибка, особенно в числах, именах, цитатах, или утверждение с риском дезинформации.
|
||||||
- [Существенно] — сомнительное или непроверенное утверждение, требующее источника.
|
- [Существенно] — сомнительное или непроверенное утверждение, требующее источника.
|
||||||
- [Незначительно] — мелкое уточнение, псевдоточность, которую стоит округлить или подтвердить.
|
- [Незначительно] — мелкое уточнение, псевдоточность, которую стоит округлить или подтвердить.
|
||||||
@@ -168,13 +170,13 @@ roles:
|
|||||||
- Не вносишь содержательных изменений. Правки — минимальные и механические.
|
- Не вносишь содержательных изменений. Правки — минимальные и механические.
|
||||||
|
|
||||||
КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ
|
КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ
|
||||||
Ты не редактируешь текст напрямую. Для каждой правки через MCP-инструмент выдели фрагмент и оставь комментарий с конкретным исправлением. Начинай комментарий с метки `[Корректура]`. Помечай важность:
|
Ты не редактируешь текст напрямую. Для каждой правки через MCP-инструмент выдели фрагмент и оставь комментарий с конкретным исправлением. К каждой правке прикладывай предложение-замену (параметр `suggestedText`): точный исправленный текст взамен выделенного фрагмента, обычным текстом без разметки — автор применит его одной кнопкой. Выделенный фрагмент должен встречаться в тексте ровно один раз; если он не уникален, расширь выделение контекстом. НЕ оставляй сводных замечаний вида «во всём тексте заменить X на Y» или «привести единицы/кавычки/написание к единообразию»: такой комментарий нельзя применить кнопкой. Если одна и та же ошибка встречается в нескольких местах, обойди КАЖДОЕ вхождение и оставь на нём отдельный целевой комментарий со своей заменой — десять точечных правок вместо одной общей. Единственное исключение — замечание, которое в принципе невозможно выразить заменой конкретного фрагмента; такие редкие случаи оставляй обычным комментарием без замены. Начинай комментарий с метки `[Корректура]`. Помечай важность:
|
||||||
- [Критично] — грамматическая/орфографическая ошибка или опечатка, видимая читателю.
|
- [Критично] — грамматическая/орфографическая ошибка или опечатка, видимая читателю.
|
||||||
- [Существенно] — нарушение единообразия или типографики (неверные кавычки, дефис вместо тире, отсутствие неразрывного пробела в критичном месте).
|
- [Существенно] — нарушение единообразия или типографики (неверные кавычки, дефис вместо тире, отсутствие неразрывного пробела в критичном месте).
|
||||||
- [Незначительно] — необязательная шлифовка.
|
- [Незначительно] — необязательная шлифовка.
|
||||||
|
|
||||||
ТОН
|
ТОН
|
||||||
По делу, без объяснений очевидного. Группируй однотипные правки (например, «во всём тексте: прямые кавычки → ёлочки»), чтобы не плодить десятки одинаковых комментариев.
|
По делу, без объяснений очевидного. Не сворачивай однотипные правки в одно сводное замечание «поменять везде» — разнеси их по конкретным местам: десять целевых комментариев с готовой заменой в каждом лучше одного общего, который нельзя применить кнопкой. Не бойся «плодить» комментарии: для корректора это норма.
|
||||||
|
|
||||||
ПРИ НЕУВЕРЕННОСТИ
|
ПРИ НЕУВЕРЕННОСТИ
|
||||||
Если правка затрагивает смысл — не трогай, это не твоя зона. Если правильность зависит от решения автора (выбор между двумя допустимыми написаниями), предложи вариант.
|
Если правка затрагивает смысл — не трогай, это не твоя зона. Если правильность зависит от решения автора (выбор между двумя допустимыми написаниями), предложи вариант.
|
||||||
@@ -273,7 +275,7 @@ roles:
|
|||||||
Сначала прочитай весь текст и оцени его как историю целиком. Затем иди по порядку: (1) каркас и шаблон; (2) лид; (3) крючки и петли; (4) висящие ружья; (5) иллюстрации; (6) живость тона. Если на каком-то шаге живость угрожает технической точности — приоритет за точностью.
|
Сначала прочитай весь текст и оцени его как историю целиком. Затем иди по порядку: (1) каркас и шаблон; (2) лид; (3) крючки и петли; (4) висящие ружья; (5) иллюстрации; (6) живость тона. Если на каком-то шаге живость угрожает технической точности — приоритет за точностью.
|
||||||
|
|
||||||
═══ КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ ═══
|
═══ КАК ОСТАВЛЯТЬ ЗАМЕЧАНИЯ ═══
|
||||||
Ты не редактируешь текст напрямую и не переписываешь его за автора. Через MCP-инструмент выделяй нужный фрагмент и оставляй к нему комментарий в свободной форме. Объясняй не только «что», но и «зачем» — какой эффект на читателя это даст. Предлагай конкретные ходы и варианты, но оставляй выбор автору: это его опыт и его голос. Комментируй то, что усилит историю, а не каждую мелочь.
|
Ты не редактируешь текст напрямую и не переписываешь его за автора. Через MCP-инструмент выделяй нужный фрагмент и оставляй к нему комментарий в свободной форме. Объясняй не только «что», но и «зачем» — какой эффект на читателя это даст. Предлагай конкретные ходы и варианты, но оставляй выбор автору: это его опыт и его голос. Если среди вариантов есть один готовый текст (например, новая формулировка лида), можешь приложить его к комментарию как предложение-замену (параметр `suggestedText`: точный новый текст взамен выделенного фрагмента, без разметки; фрагмент должен встречаться в тексте ровно один раз, иначе расширь выделение) — кнопка ничего не навязывает, автор волен не применять. Комментируй то, что усилит историю, а не каждую мелочь.
|
||||||
|
|
||||||
═══ ТОН ═══
|
═══ ТОН ═══
|
||||||
Уважительно, увлечённо, по-человечески. Ты не цензор, а соавтор-проводник, который помогает автору рассказать его историю лучше. Автор знает тему лучше тебя — твоя задача помочь ему её раскрыть.
|
Уважительно, увлечённо, по-человечески. Ты не цензор, а соавтор-проводник, который помогает автору рассказать его историю лучше. Автор знает тему лучше тебя — твоя задача помочь ему её раскрыть.
|
||||||
|
|||||||
@@ -12,15 +12,15 @@ bundles:
|
|||||||
- en
|
- en
|
||||||
roles:
|
roles:
|
||||||
- slug: structural-editor
|
- slug: structural-editor
|
||||||
version: 2
|
version: 3
|
||||||
- slug: line-editor
|
- slug: line-editor
|
||||||
version: 2
|
version: 3
|
||||||
- slug: fact-checker
|
- slug: fact-checker
|
||||||
version: 3
|
version: 4
|
||||||
- slug: proofreader
|
- slug: proofreader
|
||||||
version: 3
|
version: 5
|
||||||
- slug: narrator
|
- slug: narrator
|
||||||
version: 1
|
version: 2
|
||||||
- id: research
|
- id: research
|
||||||
name:
|
name:
|
||||||
ru: Исследование
|
ru: Исследование
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
{
|
{
|
||||||
"fact-checker": {
|
"fact-checker": {
|
||||||
"version": 3,
|
"version": 4,
|
||||||
"hash": "a94931fbd20272570a588c72159ac9e48a89c99bd8f718449cda5e7ca4280fdf"
|
"hash": "9160ead04d86aaa5dc7a51dd7e971c272ce0ca97cb24bf2b6ee5779deb1b19c0"
|
||||||
},
|
},
|
||||||
"line-editor": {
|
"line-editor": {
|
||||||
"version": 2,
|
"version": 3,
|
||||||
"hash": "cca324110dc6f96d2a8a239a2fb95b0ba09fad5806c9b6090a3c210ea7883ceb"
|
"hash": "7f200863080799b08d5af5d1648befa0843cc5db79bb994b07baa5ad12df5123"
|
||||||
},
|
},
|
||||||
"narrator": {
|
"narrator": {
|
||||||
"version": 1,
|
"version": 2,
|
||||||
"hash": "36b38785fea6ae1c70bf6fb6b29ae5278bb86e389e61f7b9736675a589fa434c"
|
"hash": "66fe653003b4f63ef3c3a5c5c48552fe47daeefffc16907c37c35f0e8da98851"
|
||||||
},
|
},
|
||||||
"proofreader": {
|
"proofreader": {
|
||||||
"version": 3,
|
"version": 5,
|
||||||
"hash": "a36047c5cab837b2a727f63d4ddafc269b1fc44b90b365e770ecdb8f77e13952"
|
"hash": "40af08c51e03c24b1986ac5cd679434e023afe31a819748966ccb0c6c62f0401"
|
||||||
},
|
},
|
||||||
"researcher": {
|
"researcher": {
|
||||||
"version": 1,
|
"version": 1,
|
||||||
"hash": "853658fda43ddbe0a4d08f2c6e50b5116d29a2e9ccd7f46e173e65920d8f6ace"
|
"hash": "853658fda43ddbe0a4d08f2c6e50b5116d29a2e9ccd7f46e173e65920d8f6ace"
|
||||||
},
|
},
|
||||||
"structural-editor": {
|
"structural-editor": {
|
||||||
"version": 2,
|
"version": 3,
|
||||||
"hash": "83093baa7262aef8193871a1afcf2b43b11a56fe2d00cade41355cf66d972b74"
|
"hash": "f6936e4c152c1b78980e74045658d87743f26f900c12f61fd7a45c6a0ec19425"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/**
|
||||||
|
* DEV-ONLY entry for the AI chat perf harness (served by the vite dev server at
|
||||||
|
* /perf/ai-chat-perf.html; never part of the production build, which uses the
|
||||||
|
* single default index.html entry).
|
||||||
|
*
|
||||||
|
* Mounts the minimal provider stack the real ChatThread needs (Mantine, router
|
||||||
|
* for tool-card Links, react-query, i18n) and patches `window.fetch` BEFORE
|
||||||
|
* React mounts so ChatThread's DefaultChatTransport requests to
|
||||||
|
* /api/ai-chat/stream are answered by the synthetic SSE generator.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import "@mantine/core/styles.css";
|
||||||
|
|
||||||
|
import ReactDOM from "react-dom/client";
|
||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { mantineCssResolver, theme } from "../src/theme.ts";
|
||||||
|
// i18n side-effect init (http-backend). Translations load from /locales in dev;
|
||||||
|
// missing keys fall back to the key text, which is fine for the harness.
|
||||||
|
import "../src/i18n.ts";
|
||||||
|
import { installAiChatStreamFetchPatch } from "./synthetic-turn.ts";
|
||||||
|
import PerfHarness from "./harness.tsx";
|
||||||
|
|
||||||
|
// MUST run before React mounts: ChatThread creates its transport with the
|
||||||
|
// global fetch, so the patch has to be in place before the first send.
|
||||||
|
installAiChatStreamFetchPatch();
|
||||||
|
|
||||||
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
refetchOnMount: false,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
retry: false,
|
||||||
|
staleTime: 5 * 60 * 1000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const container = document.getElementById("root") as HTMLElement;
|
||||||
|
|
||||||
|
ReactDOM.createRoot(container).render(
|
||||||
|
<MemoryRouter>
|
||||||
|
<MantineProvider theme={theme} cssVariablesResolver={mantineCssResolver}>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<PerfHarness />
|
||||||
|
</QueryClientProvider>
|
||||||
|
</MantineProvider>
|
||||||
|
</MemoryRouter>,
|
||||||
|
);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>AI chat perf harness</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="./ai-chat-perf-main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
/**
|
||||||
|
* DEV-ONLY perf harness UI for the AI chat feature.
|
||||||
|
*
|
||||||
|
* Left panel: controls + live stats. Right side: a bordered box (~real chat
|
||||||
|
* window size) hosting the REAL ChatThread component.
|
||||||
|
*
|
||||||
|
* Scenario A "Open existing chat": mount ChatThread seeded with a large
|
||||||
|
* persisted transcript and measure click -> post-mount-paint time.
|
||||||
|
* Scenario B "Live agent stream": mount an empty chat and auto-send a message;
|
||||||
|
* the fetch patch (see synthetic-turn.ts) answers with a synthetic SSE stream
|
||||||
|
* through the real useChat pipeline.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import type { CSSProperties, MutableRefObject } from "react";
|
||||||
|
import ChatThread from "../src/features/ai-chat/components/chat-thread.tsx";
|
||||||
|
import type { IAiChatMessageRow } from "../src/features/ai-chat/types/ai-chat.types.ts";
|
||||||
|
import {
|
||||||
|
PRESETS,
|
||||||
|
buildPersistedRows,
|
||||||
|
buildTurnScript,
|
||||||
|
setLiveStreamSettings,
|
||||||
|
type PresetKey,
|
||||||
|
} from "./synthetic-turn.ts";
|
||||||
|
|
||||||
|
const AUTO_SEND_TEXT = "Run the synthetic perf turn";
|
||||||
|
const AUTO_SEND_TIMEOUT_MS = 1000;
|
||||||
|
/** Stats display refresh period — 2x/s so the display itself stays cheap. */
|
||||||
|
const STATS_FLUSH_MS = 500;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Shared mutable stats (written from callbacks, flushed to state at 2 Hz)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface PerfStats {
|
||||||
|
longtaskCount: number;
|
||||||
|
longtaskTotalMs: number;
|
||||||
|
longtaskMaxMs: number;
|
||||||
|
fps: number;
|
||||||
|
sseChunks: number;
|
||||||
|
sseChars: number;
|
||||||
|
mountAMs: number | null;
|
||||||
|
streamState: "idle" | "streaming" | "done" | "aborted";
|
||||||
|
}
|
||||||
|
|
||||||
|
function emptyStats(): PerfStats {
|
||||||
|
return {
|
||||||
|
longtaskCount: 0,
|
||||||
|
longtaskTotalMs: 0,
|
||||||
|
longtaskMaxMs: 0,
|
||||||
|
fps: 0,
|
||||||
|
sseChunks: 0,
|
||||||
|
sseChars: 0,
|
||||||
|
mountAMs: null,
|
||||||
|
streamState: "idle",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Self-contained stats panel: owns the longtask observer, the FPS meter and the
|
||||||
|
* 2 Hz flush interval. Isolated in its OWN component so its periodic setState
|
||||||
|
* re-renders only this panel — NOT the ChatThread under measurement.
|
||||||
|
*/
|
||||||
|
function StatsPanel({ stats }: { stats: MutableRefObject<PerfStats> }) {
|
||||||
|
const [snapshot, setSnapshot] = useState<PerfStats>(() => ({ ...stats.current }));
|
||||||
|
|
||||||
|
// Long tasks (main-thread blocks > 50ms).
|
||||||
|
useEffect(() => {
|
||||||
|
let observer: PerformanceObserver | null = null;
|
||||||
|
try {
|
||||||
|
observer = new PerformanceObserver((list) => {
|
||||||
|
for (const entry of list.getEntries()) {
|
||||||
|
stats.current.longtaskCount += 1;
|
||||||
|
stats.current.longtaskTotalMs += entry.duration;
|
||||||
|
stats.current.longtaskMaxMs = Math.max(stats.current.longtaskMaxMs, entry.duration);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
observer.observe({ type: "longtask", buffered: true });
|
||||||
|
} catch {
|
||||||
|
// longtask entries unsupported in this browser — panel shows zeros.
|
||||||
|
}
|
||||||
|
return () => observer?.disconnect();
|
||||||
|
}, [stats]);
|
||||||
|
|
||||||
|
// FPS: frames rendered within the trailing 1s window.
|
||||||
|
useEffect(() => {
|
||||||
|
let raf = 0;
|
||||||
|
const frames: number[] = [];
|
||||||
|
const loop = (now: number) => {
|
||||||
|
frames.push(now);
|
||||||
|
while (frames.length > 0 && frames[0] <= now - 1000) frames.shift();
|
||||||
|
stats.current.fps = frames.length;
|
||||||
|
raf = requestAnimationFrame(loop);
|
||||||
|
};
|
||||||
|
raf = requestAnimationFrame(loop);
|
||||||
|
return () => cancelAnimationFrame(raf);
|
||||||
|
}, [stats]);
|
||||||
|
|
||||||
|
// Flush the mutable stats into the display at most 2x/s.
|
||||||
|
useEffect(() => {
|
||||||
|
const id = window.setInterval(() => setSnapshot({ ...stats.current }), STATS_FLUSH_MS);
|
||||||
|
return () => window.clearInterval(id);
|
||||||
|
}, [stats]);
|
||||||
|
|
||||||
|
const resetLongtasks = () => {
|
||||||
|
stats.current.longtaskCount = 0;
|
||||||
|
stats.current.longtaskTotalMs = 0;
|
||||||
|
stats.current.longtaskMaxMs = 0;
|
||||||
|
setSnapshot({ ...stats.current });
|
||||||
|
};
|
||||||
|
|
||||||
|
const row: CSSProperties = { display: "flex", justifyContent: "space-between", gap: 8 };
|
||||||
|
return (
|
||||||
|
<div style={{ fontFamily: "monospace", fontSize: 12, lineHeight: 1.7 }}>
|
||||||
|
<div style={{ fontWeight: 700, marginBottom: 4 }}>Stats</div>
|
||||||
|
<div style={row}><span>FPS (1s)</span><span>{snapshot.fps}</span></div>
|
||||||
|
<div style={row}><span>Long tasks</span><span>{snapshot.longtaskCount}</span></div>
|
||||||
|
<div style={row}><span>Long total</span><span>{snapshot.longtaskTotalMs.toFixed(0)} ms</span></div>
|
||||||
|
<div style={row}><span>Long max</span><span>{snapshot.longtaskMaxMs.toFixed(0)} ms</span></div>
|
||||||
|
<div style={row}><span>SSE chunks</span><span>{snapshot.sseChunks}</span></div>
|
||||||
|
<div style={row}><span>SSE chars</span><span>{snapshot.sseChars.toLocaleString()}</span></div>
|
||||||
|
<div style={row}><span>Stream</span><span>{snapshot.streamState}</span></div>
|
||||||
|
<div style={row}>
|
||||||
|
<span>Mount A</span>
|
||||||
|
<span>{snapshot.mountAMs === null ? "—" : `${snapshot.mountAMs.toFixed(0)} ms`}</span>
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={resetLongtasks} style={{ marginTop: 6 }}>
|
||||||
|
Reset long tasks
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Auto-send (scenario B): drive the REAL composer in the mounted DOM
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fill the composer textarea via the native value setter + an `input` event
|
||||||
|
* (React 18 controlled-input pattern), then click the enabled "Send" button.
|
||||||
|
* Retried on rAF until the elements exist (ChatThread mounts asynchronously).
|
||||||
|
*/
|
||||||
|
function autoSend(host: HTMLElement, text: string): void {
|
||||||
|
const deadline = performance.now() + AUTO_SEND_TIMEOUT_MS;
|
||||||
|
|
||||||
|
const tryClick = () => {
|
||||||
|
const button = host.querySelector<HTMLButtonElement>('button[aria-label="Send"]');
|
||||||
|
if (button && !button.disabled) {
|
||||||
|
button.click();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (performance.now() < deadline) requestAnimationFrame(tryClick);
|
||||||
|
else console.error("[perf] auto-send: Send button never became clickable");
|
||||||
|
};
|
||||||
|
|
||||||
|
const trySetValue = () => {
|
||||||
|
const textarea = host.querySelector("textarea");
|
||||||
|
if (!textarea) {
|
||||||
|
if (performance.now() < deadline) requestAnimationFrame(trySetValue);
|
||||||
|
else console.error("[perf] auto-send: textarea not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(
|
||||||
|
window.HTMLTextAreaElement.prototype,
|
||||||
|
"value",
|
||||||
|
)?.set;
|
||||||
|
setter?.call(textarea, text);
|
||||||
|
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||||
|
// Click on a later frame so React commits the controlled value (which
|
||||||
|
// enables the Send button) before we press it.
|
||||||
|
requestAnimationFrame(tryClick);
|
||||||
|
};
|
||||||
|
|
||||||
|
requestAnimationFrame(trySetValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Harness
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface MountState {
|
||||||
|
mode: "A" | "B";
|
||||||
|
key: number;
|
||||||
|
chatId: string | null;
|
||||||
|
rows: IAiChatMessageRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const noop = (): void => {};
|
||||||
|
|
||||||
|
export default function PerfHarness() {
|
||||||
|
const [preset, setPreset] = useState<PresetKey>("20k");
|
||||||
|
const [intervalMs, setIntervalMs] = useState<number>(15);
|
||||||
|
const [mounted, setMounted] = useState<MountState | null>(null);
|
||||||
|
const [fixtureInfo, setFixtureInfo] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const statsRef = useRef<PerfStats>(emptyStats());
|
||||||
|
const hostRef = useRef<HTMLDivElement>(null);
|
||||||
|
const keyCounterRef = useRef(0);
|
||||||
|
const mountStartRef = useRef(0);
|
||||||
|
const pendingMountMeasureRef = useRef(false);
|
||||||
|
|
||||||
|
// The scripted live turn for the current preset (reused across B runs; the
|
||||||
|
// script is immutable data, so rebuilding per run is unnecessary).
|
||||||
|
const liveScript = useMemo(() => buildTurnScript(PRESETS[preset], "live"), [preset]);
|
||||||
|
|
||||||
|
const openPage = useMemo(() => ({ id: "page-1", title: "Perf test page" }), []);
|
||||||
|
|
||||||
|
// Scenario A: mount ChatThread seeded with a large persisted transcript.
|
||||||
|
const handleMountA = () => {
|
||||||
|
const fixture = buildPersistedRows(PRESETS[preset]);
|
||||||
|
setFixtureInfo(
|
||||||
|
`Persisted fixture: ${fixture.rows.length} rows, ` +
|
||||||
|
`${fixture.totalChars.toLocaleString()} chars ≈ ${fixture.approxTokens.toLocaleString()} tokens`,
|
||||||
|
);
|
||||||
|
statsRef.current.mountAMs = null;
|
||||||
|
// Mark AFTER fixture generation: we measure mount cost, not generation cost
|
||||||
|
// (production receives its rows from the network).
|
||||||
|
performance.mark("perf:mountA:start");
|
||||||
|
mountStartRef.current = performance.now();
|
||||||
|
pendingMountMeasureRef.current = true;
|
||||||
|
keyCounterRef.current += 1;
|
||||||
|
setMounted({ mode: "A", key: keyCounterRef.current, chatId: "perf-chat", rows: fixture.rows });
|
||||||
|
};
|
||||||
|
|
||||||
|
// Measure scenario A: effect runs after the mount commit; double rAF lands
|
||||||
|
// after the first paint of the mounted transcript.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pendingMountMeasureRef.current) return;
|
||||||
|
pendingMountMeasureRef.current = false;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
statsRef.current.mountAMs = performance.now() - mountStartRef.current;
|
||||||
|
performance.mark("perf:mountA:end");
|
||||||
|
try {
|
||||||
|
performance.measure("perf:mountA", "perf:mountA:start", "perf:mountA:end");
|
||||||
|
} catch {
|
||||||
|
// Marks cleared mid-run — ignore.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [mounted]);
|
||||||
|
|
||||||
|
// Scenario B: mount an empty chat, arm the synthetic stream, auto-send.
|
||||||
|
const handleStartB = () => {
|
||||||
|
statsRef.current.sseChunks = 0;
|
||||||
|
statsRef.current.sseChars = 0;
|
||||||
|
statsRef.current.streamState = "streaming";
|
||||||
|
setLiveStreamSettings({
|
||||||
|
script: liveScript,
|
||||||
|
chunkIntervalMs: intervalMs,
|
||||||
|
onProgress: (chunks, chars) => {
|
||||||
|
statsRef.current.sseChunks = chunks;
|
||||||
|
statsRef.current.sseChars = chars;
|
||||||
|
},
|
||||||
|
onDone: () => {
|
||||||
|
statsRef.current.streamState = "done";
|
||||||
|
performance.mark("perf:streamB:end");
|
||||||
|
try {
|
||||||
|
performance.measure("perf:streamB", "perf:streamB:start", "perf:streamB:end");
|
||||||
|
} catch {
|
||||||
|
// Start mark missing (e.g. marks cleared) — ignore.
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onAbort: () => {
|
||||||
|
statsRef.current.streamState = "aborted";
|
||||||
|
},
|
||||||
|
});
|
||||||
|
performance.mark("perf:streamB:start");
|
||||||
|
keyCounterRef.current += 1;
|
||||||
|
setMounted({ mode: "B", key: keyCounterRef.current, chatId: null, rows: [] });
|
||||||
|
if (hostRef.current) autoSend(hostRef.current, AUTO_SEND_TEXT);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUnmount = () => setMounted(null);
|
||||||
|
|
||||||
|
const label: CSSProperties = { display: "block", fontSize: 12, margin: "10px 0 2px" };
|
||||||
|
const button: CSSProperties = { display: "block", width: "100%", margin: "6px 0", padding: "6px 8px" };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ display: "flex", height: "100vh", fontFamily: "system-ui, sans-serif" }}>
|
||||||
|
{/* Left: controls + stats */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: 260,
|
||||||
|
flex: "0 0 260px",
|
||||||
|
padding: 12,
|
||||||
|
borderRight: "1px solid #ccc",
|
||||||
|
overflowY: "auto",
|
||||||
|
boxSizing: "border-box",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ fontWeight: 700, marginBottom: 4 }}>AI chat perf harness</div>
|
||||||
|
|
||||||
|
<label style={label}>Preset</label>
|
||||||
|
<select
|
||||||
|
value={preset}
|
||||||
|
onChange={(e) => setPreset(e.target.value as PresetKey)}
|
||||||
|
style={{ width: "100%" }}
|
||||||
|
>
|
||||||
|
<option value="5k">5k tokens</option>
|
||||||
|
<option value="20k">20k tokens</option>
|
||||||
|
<option value="50k">50k tokens</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<label style={label}>Chunk interval (scenario B)</label>
|
||||||
|
<select
|
||||||
|
value={intervalMs}
|
||||||
|
onChange={(e) => setIntervalMs(Number(e.target.value))}
|
||||||
|
style={{ width: "100%" }}
|
||||||
|
>
|
||||||
|
<option value={15}>15 ms (normal)</option>
|
||||||
|
<option value={5}>5 ms (stress)</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<div style={{ marginTop: 12 }}>
|
||||||
|
<button type="button" style={button} onClick={handleMountA}>
|
||||||
|
Mount persisted chat (A)
|
||||||
|
</button>
|
||||||
|
<button type="button" style={button} onClick={handleStartB}>
|
||||||
|
Start live stream (B)
|
||||||
|
</button>
|
||||||
|
<button type="button" style={button} onClick={handleUnmount} disabled={!mounted}>
|
||||||
|
Unmount
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ fontSize: 11, color: "#555", margin: "8px 0" }}>
|
||||||
|
<div>
|
||||||
|
Live turn: {liveScript.totalChars.toLocaleString()} chars ≈{" "}
|
||||||
|
{liveScript.approxTokens.toLocaleString()} tokens
|
||||||
|
</div>
|
||||||
|
{fixtureInfo && <div>{fixtureInfo}</div>}
|
||||||
|
{mounted && (
|
||||||
|
<div>
|
||||||
|
Mounted: scenario {mounted.mode} (key {mounted.key})
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<hr style={{ border: "none", borderTop: "1px solid #ddd" }} />
|
||||||
|
<StatsPanel stats={statsRef} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right: the real ChatThread inside a real-window-sized box */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
flex: 1,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
background: "#f4f4f5",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
ref={hostRef}
|
||||||
|
style={{
|
||||||
|
width: 540,
|
||||||
|
height: 680,
|
||||||
|
border: "1px solid #bbb",
|
||||||
|
borderRadius: 8,
|
||||||
|
background: "#fff",
|
||||||
|
padding: 8,
|
||||||
|
boxSizing: "border-box",
|
||||||
|
overflow: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{mounted ? (
|
||||||
|
<ChatThread
|
||||||
|
key={mounted.key}
|
||||||
|
chatId={mounted.chatId}
|
||||||
|
threadKey={`perf-${mounted.key}`}
|
||||||
|
initialRows={mounted.rows}
|
||||||
|
openPage={openPage}
|
||||||
|
roleId={null}
|
||||||
|
roles={[]}
|
||||||
|
onRolePicked={noop}
|
||||||
|
assistantName="Perf agent"
|
||||||
|
onTurnFinished={noop}
|
||||||
|
onServerChatId={noop}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div style={{ color: "#888", fontSize: 13, padding: 16 }}>
|
||||||
|
ChatThread unmounted. Use the controls on the left.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,517 @@
|
|||||||
|
/**
|
||||||
|
* DEV-ONLY synthetic agent-turn generator for the AI chat perf harness.
|
||||||
|
*
|
||||||
|
* Produces one scripted agent turn (reasoning + tool calls + markdown answer)
|
||||||
|
* from a size config, and materializes it two ways:
|
||||||
|
* - as an AI SDK v6 UI-message SSE stream (scenario B "live agent stream"),
|
||||||
|
* served by a `window.fetch` patch that intercepts `/api/ai-chat/stream`;
|
||||||
|
* - as persisted `IAiChatMessageRow[]` history (scenario A "open existing chat").
|
||||||
|
*
|
||||||
|
* Wire format verified against the installed ai@6.0.207 `uiMessageChunkSchema`
|
||||||
|
* (strict objects — only the exact field names below are accepted).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { UIMessage } from "@ai-sdk/react";
|
||||||
|
import type { IAiChatMessageRow } from "../src/features/ai-chat/types/ai-chat.types.ts";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Config / presets
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 1 token ~= 4 chars — the approximation used throughout this module. */
|
||||||
|
const CHARS_PER_TOKEN = 4;
|
||||||
|
|
||||||
|
export interface TurnConfig {
|
||||||
|
/** Number of agent steps; each step = one reasoning block + one tool call. */
|
||||||
|
steps: number;
|
||||||
|
/** Approximate reasoning tokens generated per step. */
|
||||||
|
reasoningTokensPerStep: number;
|
||||||
|
/** Size of each tool call's output `content` filler, in bytes (ASCII). */
|
||||||
|
toolOutputBytes: number;
|
||||||
|
/** Approximate size of the final markdown answer, in tokens. */
|
||||||
|
answerTokens: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PresetKey = "5k" | "20k" | "50k";
|
||||||
|
|
||||||
|
export const PRESETS: Record<PresetKey, TurnConfig> = {
|
||||||
|
"5k": {
|
||||||
|
steps: 3,
|
||||||
|
reasoningTokensPerStep: 500,
|
||||||
|
toolOutputBytes: 10_000,
|
||||||
|
answerTokens: 600,
|
||||||
|
},
|
||||||
|
"20k": {
|
||||||
|
steps: 6,
|
||||||
|
reasoningTokensPerStep: 2500,
|
||||||
|
toolOutputBytes: 20_000,
|
||||||
|
answerTokens: 1500,
|
||||||
|
},
|
||||||
|
"50k": {
|
||||||
|
steps: 10,
|
||||||
|
reasoningTokensPerStep: 4000,
|
||||||
|
toolOutputBytes: 40_000,
|
||||||
|
answerTokens: 3000,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Text generators
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Mixed Russian/English prose sentences cycled to build reasoning text. */
|
||||||
|
const REASONING_SENTENCES = [
|
||||||
|
"Пользователь просит проанализировать документ и выделить ключевые тезисы по каждому разделу.",
|
||||||
|
"First I need to inspect the current page content to understand its overall structure.",
|
||||||
|
"Судя по оглавлению, раздел с техническими требованиями находится ближе к концу документа.",
|
||||||
|
"The table in section three contains the migration matrix that I should cross-check against the summary.",
|
||||||
|
"Проверю, нет ли противоречий между описанием API и приведёнными в тексте примерами вызовов.",
|
||||||
|
"Let me compare the numbers from the executive summary with the raw data in the appendix.",
|
||||||
|
"Похоже, автор использует термины «воркспейс» и workspace взаимозаменяемо — это стоит нормализовать.",
|
||||||
|
"I should keep the page ids from the tool output so the final answer can cite the source pages.",
|
||||||
|
"Осталось свести найденные несоответствия в одну таблицу и предложить порядок исправлений.",
|
||||||
|
"The remaining sections look consistent, so I can move on to drafting the structured answer.",
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build realistic prose of ~`targetChars` characters, inserting a newline
|
||||||
|
* roughly every 200 characters (mirrors how reasoning text tends to wrap).
|
||||||
|
*/
|
||||||
|
function makeProse(targetChars: number): string {
|
||||||
|
const pieces: string[] = [];
|
||||||
|
let length = 0;
|
||||||
|
let sinceNewline = 0;
|
||||||
|
let i = 0;
|
||||||
|
while (length < targetChars) {
|
||||||
|
const sentence = REASONING_SENTENCES[i % REASONING_SENTENCES.length];
|
||||||
|
i += 1;
|
||||||
|
pieces.push(sentence);
|
||||||
|
length += sentence.length + 1;
|
||||||
|
sinceNewline += sentence.length + 1;
|
||||||
|
if (sinceNewline >= 200) {
|
||||||
|
pieces.push("\n");
|
||||||
|
sinceNewline = 0;
|
||||||
|
} else {
|
||||||
|
pieces.push(" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pieces.join("").trimEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One markdown section (~700 chars): heading, prose, bullets, GFM table, code. */
|
||||||
|
function markdownSection(n: number): string {
|
||||||
|
return [
|
||||||
|
`## Section ${n}: migration analysis`,
|
||||||
|
``,
|
||||||
|
`The workspace contains **${n * 12} pages** that still reference the legacy API. ` +
|
||||||
|
`Most of them live under [Perf test page](/p/page-1) and need the new transport. ` +
|
||||||
|
`Ниже приведена сводка по разделу с оценкой трудозатрат и основных рисков.`,
|
||||||
|
``,
|
||||||
|
`- Update the fetch layer to the v6 transport`,
|
||||||
|
`- Перенести таблицы соответствия идентификаторов`,
|
||||||
|
`- Verify citation links after the move`,
|
||||||
|
`- Проверить отображение длинных ответов в узкой панели`,
|
||||||
|
``,
|
||||||
|
`| Область | Страниц | Статус | Риск |`,
|
||||||
|
`| --- | --- | --- | --- |`,
|
||||||
|
`| API reference | ${n + 4} | migrated | low |`,
|
||||||
|
`| Onboarding | ${n + 2} | in progress | medium |`,
|
||||||
|
`| Release notes | ${n * 3} | pending | high |`,
|
||||||
|
``,
|
||||||
|
"```ts",
|
||||||
|
`export function migrateSection${n}(rows: Row[]): Row[] {`,
|
||||||
|
` return rows`,
|
||||||
|
` .filter((row) => row.section === ${n})`,
|
||||||
|
` .map((row) => ({ ...row, migrated: true }));`,
|
||||||
|
`}`,
|
||||||
|
"```",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Realistic markdown answer of ~`targetChars` chars (sections repeated to size). */
|
||||||
|
function makeMarkdownAnswer(targetChars: number): string {
|
||||||
|
const sections: string[] = [];
|
||||||
|
let length = 0;
|
||||||
|
let n = 1;
|
||||||
|
while (length < targetChars) {
|
||||||
|
const section = markdownSection(n);
|
||||||
|
sections.push(section);
|
||||||
|
length += section.length + 2;
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
return sections.join("\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plain ASCII filler of exactly `bytes` characters for tool outputs. */
|
||||||
|
function makeFiller(bytes: number): string {
|
||||||
|
const unit = "Perf filler content for the synthetic getPage tool output. ";
|
||||||
|
return unit.repeat(Math.ceil(bytes / unit.length)).slice(0, bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Turn script
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export interface TurnToolCall {
|
||||||
|
toolCallId: string;
|
||||||
|
toolName: "getPage";
|
||||||
|
input: { pageId: string };
|
||||||
|
output: { id: string; title: string; content: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TurnStep {
|
||||||
|
reasoningText: string;
|
||||||
|
tool: TurnToolCall;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TurnScript {
|
||||||
|
steps: TurnStep[];
|
||||||
|
answerText: string;
|
||||||
|
/** Approximate reasoning tokens for the whole turn (chars / 4). */
|
||||||
|
reasoningTokens: number;
|
||||||
|
/** Approximate context size after this turn, in tokens. */
|
||||||
|
contextTokens: number;
|
||||||
|
maxContextTokens: number;
|
||||||
|
/** Actual generated visible chars: reasoning + tool outputs + answer. */
|
||||||
|
totalChars: number;
|
||||||
|
/** totalChars / 4, rounded. */
|
||||||
|
approxTokens: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the scripted agent turn for a config. `idPrefix` keeps tool call ids
|
||||||
|
* unique when several scripts coexist (e.g. 3 persisted turns in one chat).
|
||||||
|
*/
|
||||||
|
export function buildTurnScript(config: TurnConfig, idPrefix = "live"): TurnScript {
|
||||||
|
const steps: TurnStep[] = [];
|
||||||
|
let reasoningChars = 0;
|
||||||
|
let toolChars = 0;
|
||||||
|
for (let i = 0; i < config.steps; i++) {
|
||||||
|
const reasoningText = makeProse(config.reasoningTokensPerStep * CHARS_PER_TOKEN);
|
||||||
|
const content = makeFiller(config.toolOutputBytes);
|
||||||
|
reasoningChars += reasoningText.length;
|
||||||
|
toolChars += content.length;
|
||||||
|
steps.push({
|
||||||
|
reasoningText,
|
||||||
|
tool: {
|
||||||
|
toolCallId: `${idPrefix}-call-${i + 1}`,
|
||||||
|
toolName: "getPage",
|
||||||
|
input: { pageId: "page-1" },
|
||||||
|
output: { id: "page-1", title: "Perf test page", content },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const answerText = makeMarkdownAnswer(config.answerTokens * CHARS_PER_TOKEN);
|
||||||
|
const totalChars = reasoningChars + toolChars + answerText.length;
|
||||||
|
return {
|
||||||
|
steps,
|
||||||
|
answerText,
|
||||||
|
reasoningTokens: Math.round(reasoningChars / CHARS_PER_TOKEN),
|
||||||
|
contextTokens: Math.round(totalChars / CHARS_PER_TOKEN),
|
||||||
|
maxContextTokens: 200_000,
|
||||||
|
totalChars,
|
||||||
|
approxTokens: Math.round(totalChars / CHARS_PER_TOKEN),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Scenario A: persisted rows
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Number of user+assistant pairs the preset is split across for history. */
|
||||||
|
const HISTORY_TURNS = 3;
|
||||||
|
|
||||||
|
const USER_PROMPTS = [
|
||||||
|
"Проанализируй документ и выдели ключевые тезисы по каждому разделу.",
|
||||||
|
"Now cross-check the migration matrix against the summary and list every mismatch.",
|
||||||
|
"Собери финальный план миграции с оценкой рисков по каждой области.",
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Persisted UIMessage parts for one finished assistant turn. */
|
||||||
|
function scriptToPersistedParts(script: TurnScript): UIMessage["parts"] {
|
||||||
|
const parts: unknown[] = [];
|
||||||
|
for (const step of script.steps) {
|
||||||
|
parts.push({ type: "reasoning", text: step.reasoningText, state: "done" });
|
||||||
|
parts.push({
|
||||||
|
type: `tool-${step.tool.toolName}`,
|
||||||
|
toolCallId: step.tool.toolCallId,
|
||||||
|
state: "output-available",
|
||||||
|
input: step.tool.input,
|
||||||
|
output: step.tool.output,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
parts.push({ type: "text", text: script.answerText, state: "done" });
|
||||||
|
return parts as UIMessage["parts"];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PersistedFixture {
|
||||||
|
rows: IAiChatMessageRow[];
|
||||||
|
totalChars: number;
|
||||||
|
approxTokens: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Materialize the preset as a finished 3-turn transcript: user row + assistant
|
||||||
|
* row per turn, with the preset's steps/answer split across the assistant turns.
|
||||||
|
* Approximate accounting — the actual totals are reported back for display.
|
||||||
|
*/
|
||||||
|
export function buildPersistedRows(config: TurnConfig): PersistedFixture {
|
||||||
|
const rows: IAiChatMessageRow[] = [];
|
||||||
|
const baseTime = Date.now() - HISTORY_TURNS * 60_000;
|
||||||
|
let totalChars = 0;
|
||||||
|
|
||||||
|
for (let t = 0; t < HISTORY_TURNS; t++) {
|
||||||
|
// Distribute steps as evenly as possible (earlier turns get the remainder).
|
||||||
|
const stepsForTurn =
|
||||||
|
Math.floor(config.steps / HISTORY_TURNS) +
|
||||||
|
(t < config.steps % HISTORY_TURNS ? 1 : 0);
|
||||||
|
const turnConfig: TurnConfig = {
|
||||||
|
steps: Math.max(1, stepsForTurn),
|
||||||
|
reasoningTokensPerStep: config.reasoningTokensPerStep,
|
||||||
|
toolOutputBytes: config.toolOutputBytes,
|
||||||
|
answerTokens: Math.max(50, Math.round(config.answerTokens / HISTORY_TURNS)),
|
||||||
|
};
|
||||||
|
const script = buildTurnScript(turnConfig, `hist-${t + 1}`);
|
||||||
|
totalChars += script.totalChars;
|
||||||
|
|
||||||
|
const userText = USER_PROMPTS[t % USER_PROMPTS.length];
|
||||||
|
rows.push({
|
||||||
|
id: `perf-row-u${t + 1}`,
|
||||||
|
role: "user",
|
||||||
|
content: userText,
|
||||||
|
metadata: null,
|
||||||
|
createdAt: new Date(baseTime + t * 60_000).toISOString(),
|
||||||
|
});
|
||||||
|
rows.push({
|
||||||
|
id: `perf-row-a${t + 1}`,
|
||||||
|
role: "assistant",
|
||||||
|
content: script.answerText,
|
||||||
|
metadata: {
|
||||||
|
parts: scriptToPersistedParts(script),
|
||||||
|
usage: { reasoningTokens: script.reasoningTokens },
|
||||||
|
contextTokens: script.contextTokens,
|
||||||
|
maxContextTokens: script.maxContextTokens,
|
||||||
|
finishReason: "stop",
|
||||||
|
},
|
||||||
|
createdAt: new Date(baseTime + t * 60_000 + 30_000).toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
rows,
|
||||||
|
totalChars,
|
||||||
|
approxTokens: Math.round(totalChars / CHARS_PER_TOKEN),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Scenario B: SSE stream
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Streaming delta size in chars (reasoning/answer text is split into these). */
|
||||||
|
const DELTA_CHARS = 200;
|
||||||
|
|
||||||
|
function splitDeltas(text: string, size = DELTA_CHARS): string[] {
|
||||||
|
const deltas: string[] = [];
|
||||||
|
for (let i = 0; i < text.length; i += size) {
|
||||||
|
deltas.push(text.slice(i, i + size));
|
||||||
|
}
|
||||||
|
return deltas;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One pre-serialized SSE frame plus its visible-char contribution for stats. */
|
||||||
|
interface SseFrame {
|
||||||
|
data: string;
|
||||||
|
chars: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function frame(chunk: Record<string, unknown>, chars = 0): SseFrame {
|
||||||
|
return { data: `data: ${JSON.stringify(chunk)}\n\n`, chars };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serialize the whole scripted turn into AI SDK v6 UI-message SSE frames
|
||||||
|
* (excluding the final `data: [DONE]` terminator, appended by the pump).
|
||||||
|
*/
|
||||||
|
function buildSseFrames(script: TurnScript, messageId: string, chatId: string): SseFrame[] {
|
||||||
|
const frames: SseFrame[] = [];
|
||||||
|
frames.push(frame({ type: "start", messageId, messageMetadata: { chatId } }));
|
||||||
|
|
||||||
|
script.steps.forEach((step, i) => {
|
||||||
|
frames.push(frame({ type: "start-step" }));
|
||||||
|
const reasoningId = `${messageId}-r${i + 1}`;
|
||||||
|
frames.push(frame({ type: "reasoning-start", id: reasoningId }));
|
||||||
|
for (const delta of splitDeltas(step.reasoningText)) {
|
||||||
|
frames.push(frame({ type: "reasoning-delta", id: reasoningId, delta }, delta.length));
|
||||||
|
}
|
||||||
|
frames.push(frame({ type: "reasoning-end", id: reasoningId }));
|
||||||
|
|
||||||
|
const { toolCallId, toolName, input, output } = step.tool;
|
||||||
|
frames.push(frame({ type: "tool-input-start", toolCallId, toolName }));
|
||||||
|
frames.push(frame({ type: "tool-input-available", toolCallId, toolName, input }));
|
||||||
|
// The tool result arrives as ONE chunk, like the real server sends it.
|
||||||
|
frames.push(frame({ type: "tool-output-available", toolCallId, output }, output.content.length));
|
||||||
|
frames.push(frame({ type: "finish-step" }));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Final step: the markdown answer.
|
||||||
|
frames.push(frame({ type: "start-step" }));
|
||||||
|
const textId = `${messageId}-answer`;
|
||||||
|
frames.push(frame({ type: "text-start", id: textId }));
|
||||||
|
for (const delta of splitDeltas(script.answerText)) {
|
||||||
|
frames.push(frame({ type: "text-delta", id: textId, delta }, delta.length));
|
||||||
|
}
|
||||||
|
frames.push(frame({ type: "text-end", id: textId }));
|
||||||
|
frames.push(frame({ type: "finish-step" }));
|
||||||
|
|
||||||
|
frames.push(
|
||||||
|
frame({
|
||||||
|
type: "finish",
|
||||||
|
messageMetadata: {
|
||||||
|
usage: { reasoningTokens: script.reasoningTokens },
|
||||||
|
contextTokens: script.contextTokens,
|
||||||
|
maxContextTokens: script.maxContextTokens,
|
||||||
|
finishReason: "stop",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LiveStreamSettings {
|
||||||
|
script: TurnScript;
|
||||||
|
/** Delay between SSE chunks (one chunk per tick). */
|
||||||
|
chunkIntervalMs: number;
|
||||||
|
/** Progress callback: cumulative emitted chunk count and visible chars. */
|
||||||
|
onProgress?: (chunks: number, chars: number) => void;
|
||||||
|
/** Fired once after the `[DONE]` terminator is enqueued. */
|
||||||
|
onDone?: () => void;
|
||||||
|
/** Fired if the client aborted the stream (Stop button). */
|
||||||
|
onAbort?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a synthetic SSE Response streaming the scripted turn, one chunk every
|
||||||
|
* `chunkIntervalMs`. Honors the fetch `AbortSignal` so the real Stop button works.
|
||||||
|
*/
|
||||||
|
export function buildSseResponse(
|
||||||
|
settings: LiveStreamSettings,
|
||||||
|
signal?: AbortSignal | null,
|
||||||
|
): Response {
|
||||||
|
const messageId = `m-live-${Date.now()}`;
|
||||||
|
const frames = buildSseFrames(settings.script, messageId, "perf-chat");
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
let index = 0;
|
||||||
|
let emittedChars = 0;
|
||||||
|
let timer: number | undefined;
|
||||||
|
|
||||||
|
const stream = new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
const stopPump = () => {
|
||||||
|
if (timer !== undefined) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const pump = () => {
|
||||||
|
timer = undefined;
|
||||||
|
if (signal?.aborted) {
|
||||||
|
stopPump();
|
||||||
|
try {
|
||||||
|
controller.close();
|
||||||
|
} catch {
|
||||||
|
// Already closed/cancelled — nothing to do.
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (index >= frames.length) {
|
||||||
|
try {
|
||||||
|
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
||||||
|
controller.close();
|
||||||
|
} catch {
|
||||||
|
// Cancelled mid-flight.
|
||||||
|
}
|
||||||
|
settings.onDone?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const next = frames[index];
|
||||||
|
index += 1;
|
||||||
|
try {
|
||||||
|
controller.enqueue(encoder.encode(next.data));
|
||||||
|
} catch {
|
||||||
|
stopPump();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
emittedChars += next.chars;
|
||||||
|
settings.onProgress?.(index, emittedChars);
|
||||||
|
timer = window.setTimeout(pump, settings.chunkIntervalMs);
|
||||||
|
};
|
||||||
|
signal?.addEventListener(
|
||||||
|
"abort",
|
||||||
|
() => {
|
||||||
|
stopPump();
|
||||||
|
try {
|
||||||
|
controller.close();
|
||||||
|
} catch {
|
||||||
|
// Reader already cancelled.
|
||||||
|
}
|
||||||
|
settings.onAbort?.();
|
||||||
|
},
|
||||||
|
{ once: true },
|
||||||
|
);
|
||||||
|
timer = window.setTimeout(pump, settings.chunkIntervalMs);
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
if (timer !== undefined) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = undefined;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Response(stream, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"content-type": "text/event-stream",
|
||||||
|
"cache-control": "no-cache",
|
||||||
|
"x-vercel-ai-ui-message-stream": "v1",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// window.fetch patch
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let currentLiveSettings: LiveStreamSettings | null = null;
|
||||||
|
|
||||||
|
/** Arm the next `/api/ai-chat/stream` request with a scripted turn. */
|
||||||
|
export function setLiveStreamSettings(settings: LiveStreamSettings): void {
|
||||||
|
currentLiveSettings = settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch `window.fetch` BEFORE React mounts: requests to `/api/ai-chat/stream`
|
||||||
|
* get the synthetic SSE Response; everything else passes through untouched.
|
||||||
|
*/
|
||||||
|
export function installAiChatStreamFetchPatch(): void {
|
||||||
|
const originalFetch = window.fetch.bind(window);
|
||||||
|
window.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
||||||
|
const url =
|
||||||
|
typeof input === "string"
|
||||||
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.href
|
||||||
|
: input.url;
|
||||||
|
if (url.includes("/api/ai-chat/stream")) {
|
||||||
|
const settings = currentLiveSettings;
|
||||||
|
if (!settings) {
|
||||||
|
return Promise.resolve(
|
||||||
|
new Response("perf harness: no live stream configured", { status: 500 }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Promise.resolve(buildSseResponse(settings, init?.signal ?? null));
|
||||||
|
}
|
||||||
|
return originalFetch(input, init);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1223,7 +1223,11 @@
|
|||||||
"Resolved comment": "Resolved comment",
|
"Resolved comment": "Resolved comment",
|
||||||
"Ran tool {{name}}": "Ran tool {{name}}",
|
"Ran tool {{name}}": "Ran tool {{name}}",
|
||||||
"AI-agent": "AI-agent",
|
"AI-agent": "AI-agent",
|
||||||
|
"AI agent «{{role}}» on behalf of {{person}}": "AI agent «{{role}}» on behalf of {{person}}",
|
||||||
|
"AI agent {{name}}": "AI agent {{name}}",
|
||||||
"Edited by AI agent on behalf of {{name}}": "Edited by AI agent on behalf of {{name}}",
|
"Edited by AI agent on behalf of {{name}}": "Edited by AI agent on behalf of {{name}}",
|
||||||
|
"Git sync": "Git sync",
|
||||||
|
"Synced from Git on behalf of {{name}}": "Synced from Git on behalf of {{name}}",
|
||||||
"Endpoints": "Endpoints",
|
"Endpoints": "Endpoints",
|
||||||
"where we fetch models": "where we fetch models",
|
"where we fetch models": "where we fetch models",
|
||||||
"All endpoints are OpenAI-compatible. Point the Base URL at OpenAI, OpenRouter, a local Ollama, or any self-hosted server.": "All endpoints are OpenAI-compatible. Point the Base URL at OpenAI, OpenRouter, a local Ollama, or any self-hosted server.",
|
"All endpoints are OpenAI-compatible. Point the Base URL at OpenAI, OpenRouter, a local Ollama, or any self-hosted server.": "All endpoints are OpenAI-compatible. Point the Base URL at OpenAI, OpenRouter, a local Ollama, or any self-hosted server.",
|
||||||
@@ -1248,6 +1252,10 @@
|
|||||||
"MCP server": "MCP server",
|
"MCP server": "MCP server",
|
||||||
"expose the workspace": "expose the workspace",
|
"expose the workspace": "expose the workspace",
|
||||||
"Enable MCP server": "Enable MCP server",
|
"Enable MCP server": "Enable MCP server",
|
||||||
|
"Enable Git sync": "Enable Git sync",
|
||||||
|
"Sync this space's pages to a Git repository.": "Sync this space's pages to a Git repository.",
|
||||||
|
"Auto-merge conflicts on push": "Auto-merge conflicts on push",
|
||||||
|
"When off (recommended), a page whose content still has unresolved Git conflict markers is skipped on push until you resolve the conflict in Git. When on, the markers are stripped and both sides' content is pushed.": "When off (recommended), a page whose content still has unresolved Git conflict markers is skipped on push until you resolve the conflict in Git. When on, the markers are stripped and both sides' content is pushed.",
|
||||||
"Exposes the workspace as an MCP server at /mcp — this provides a capability, it doesn't consume a model.": "Exposes the workspace as an MCP server at /mcp — this provides a capability, it doesn't consume a model.",
|
"Exposes the workspace as an MCP server at /mcp — this provides a capability, it doesn't consume a model.": "Exposes the workspace as an MCP server at /mcp — this provides a capability, it doesn't consume a model.",
|
||||||
"Resolves to {{url}}": "Resolves to {{url}}",
|
"Resolves to {{url}}": "Resolves to {{url}}",
|
||||||
"Model": "Model",
|
"Model": "Model",
|
||||||
@@ -1274,6 +1282,10 @@
|
|||||||
"Voice dictation is not configured": "Voice dictation is not configured",
|
"Voice dictation is not configured": "Voice dictation is not configured",
|
||||||
"Microphone is unavailable or already in use": "Microphone is unavailable or already in use",
|
"Microphone is unavailable or already in use": "Microphone is unavailable or already in use",
|
||||||
"Audio recording is not available in this browser/context": "Audio recording is not available in this browser/context",
|
"Audio recording is not available in this browser/context": "Audio recording is not available in this browser/context",
|
||||||
|
"Dictation": "Dictation",
|
||||||
|
"Dictation becomes available once the page finishes connecting": "Dictation becomes available once the page finishes connecting",
|
||||||
|
"No connection to the collaboration server — dictation unavailable": "No connection to the collaboration server — dictation unavailable",
|
||||||
|
"This page is read-only": "This page is read-only",
|
||||||
"Request format": "Request format",
|
"Request format": "Request format",
|
||||||
"How transcription requests are sent to the endpoint": "How transcription requests are sent to the endpoint",
|
"How transcription requests are sent to the endpoint": "How transcription requests are sent to the endpoint",
|
||||||
"OpenAI-compatible (multipart/form-data)": "OpenAI-compatible (multipart/form-data)",
|
"OpenAI-compatible (multipart/form-data)": "OpenAI-compatible (multipart/form-data)",
|
||||||
@@ -1373,5 +1385,10 @@
|
|||||||
"Updated to the latest version": "Updated to the latest version",
|
"Updated to the latest version": "Updated to the latest version",
|
||||||
"This role is no longer in the catalog": "This role is no longer in the catalog",
|
"This role is no longer in the catalog": "This role is no longer in the catalog",
|
||||||
"This language is no longer available in the catalog": "This language is no longer available in the catalog",
|
"This language is no longer available in the catalog": "This language is no longer available in the catalog",
|
||||||
"Connecting… (read-only)": "Connecting… (read-only)"
|
"Connecting… (read-only)": "Connecting… (read-only)",
|
||||||
|
"Apply": "Apply",
|
||||||
|
"Applied": "Applied",
|
||||||
|
"Suggestion applied": "Suggestion applied",
|
||||||
|
"Failed to apply suggestion": "Failed to apply suggestion",
|
||||||
|
"The commented text changed since this suggestion was made; it was not applied.": "The commented text changed since this suggestion was made; it was not applied."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -393,6 +393,17 @@
|
|||||||
"No speech detected": "Речь не распознана",
|
"No speech detected": "Речь не распознана",
|
||||||
"Transcription failed": "Не удалось распознать речь",
|
"Transcription failed": "Не удалось распознать речь",
|
||||||
"Voice dictation is not configured": "Голосовой ввод не настроен",
|
"Voice dictation is not configured": "Голосовой ввод не настроен",
|
||||||
|
"Start dictation": "Начать диктовку",
|
||||||
|
"Stop recording": "Остановить запись",
|
||||||
|
"Microphone access denied": "Доступ к микрофону запрещён",
|
||||||
|
"No microphone found": "Микрофон не найден",
|
||||||
|
"Microphone is unavailable or already in use": "Микрофон недоступен или уже используется",
|
||||||
|
"Could not start recording": "Не удалось начать запись",
|
||||||
|
"Audio recording is not available in this browser/context": "Запись аудио недоступна в этом браузере/контексте",
|
||||||
|
"Dictation": "Диктовка",
|
||||||
|
"Dictation becomes available once the page finishes connecting": "Диктовка станет доступна после подключения к документу",
|
||||||
|
"No connection to the collaboration server — dictation unavailable": "Нет связи с сервером совместного редактирования — диктовка недоступна",
|
||||||
|
"This page is read-only": "Страница открыта только для чтения",
|
||||||
"Embed PDF": "Встроить PDF",
|
"Embed PDF": "Встроить PDF",
|
||||||
"Upload and embed a PDF file.": "Загрузите и встроите PDF-файл.",
|
"Upload and embed a PDF file.": "Загрузите и встроите PDF-файл.",
|
||||||
"Embed as PDF": "Встроить как PDF",
|
"Embed as PDF": "Встроить как PDF",
|
||||||
@@ -724,6 +735,8 @@
|
|||||||
"Shown as used / total in the chat header. Leave empty to hide the limit.": "Показывается в шапке чата как использовано / всего. Пусто — лимит скрыт.",
|
"Shown as used / total in the chat header. Leave empty to hide the limit.": "Показывается в шапке чата как использовано / всего. Пусто — лимит скрыт.",
|
||||||
"Delete this chat?": "Удалить этот чат?",
|
"Delete this chat?": "Удалить этот чат?",
|
||||||
"Deleted successfully": "Успешно удалено",
|
"Deleted successfully": "Успешно удалено",
|
||||||
|
"AI agent «{{role}}» on behalf of {{person}}": "AI-агент «{{role}}» от имени {{person}}",
|
||||||
|
"AI agent {{name}}": "AI-агент {{name}}",
|
||||||
"Edited by AI agent on behalf of {{name}}": "Отредактировано AI-агентом от имени {{name}}",
|
"Edited by AI agent on behalf of {{name}}": "Отредактировано AI-агентом от имени {{name}}",
|
||||||
"Failed to delete chat": "Не удалось удалить чат",
|
"Failed to delete chat": "Не удалось удалить чат",
|
||||||
"Failed to rename chat": "Не удалось переименовать чат",
|
"Failed to rename chat": "Не удалось переименовать чат",
|
||||||
@@ -1228,5 +1241,10 @@
|
|||||||
"Updated to the latest version": "Обновлено до последней версии",
|
"Updated to the latest version": "Обновлено до последней версии",
|
||||||
"This role is no longer in the catalog": "Эта роль больше не представлена в каталоге",
|
"This role is no longer in the catalog": "Эта роль больше не представлена в каталоге",
|
||||||
"This language is no longer available in the catalog": "Этот язык больше не доступен в каталоге",
|
"This language is no longer available in the catalog": "Этот язык больше не доступен в каталоге",
|
||||||
"Connecting… (read-only)": "Подключение… (только чтение)"
|
"Connecting… (read-only)": "Подключение… (только чтение)",
|
||||||
|
"Apply": "Применить",
|
||||||
|
"Applied": "Применено",
|
||||||
|
"Suggestion applied": "Предложение применено",
|
||||||
|
"Failed to apply suggestion": "Не удалось применить предложение",
|
||||||
|
"The commented text changed since this suggestion was made; it was not applied.": "Прокомментированный текст изменился после создания предложения; оно не было применено."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,22 @@ import { notifications } from "@mantine/notifications";
|
|||||||
import { exportSpace } from "@/features/space/services/space-service";
|
import { exportSpace } from "@/features/space/services/space-service";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
// The export request uses `responseType: "blob"`, so a server error body arrives
|
||||||
|
// as a Blob rather than parsed JSON — `err.response?.data.message` is therefore
|
||||||
|
// always undefined. Read and parse the blob to surface the real error message.
|
||||||
|
async function extractExportError(err: any): Promise<string> {
|
||||||
|
const data = err?.response?.data;
|
||||||
|
if (data instanceof Blob) {
|
||||||
|
try {
|
||||||
|
const json = JSON.parse(await data.text());
|
||||||
|
return json?.message ?? "";
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data?.message ?? err?.message ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
interface ExportModalProps {
|
interface ExportModalProps {
|
||||||
id: string;
|
id: string;
|
||||||
type: "space" | "page";
|
type: "space" | "page";
|
||||||
@@ -52,8 +68,9 @@ export default function ExportModal({
|
|||||||
});
|
});
|
||||||
onClose();
|
onClose();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
const message = await extractExportError(err);
|
||||||
notifications.show({
|
notifications.show({
|
||||||
message: "Export failed:" + err.response?.data.message,
|
message: t("Export failed") + (message ? `: ${message}` : ""),
|
||||||
color: "red",
|
color: "red",
|
||||||
});
|
});
|
||||||
console.error("export error", err);
|
console.error("export error", err);
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import TopMenu from "@/components/layouts/global/top-menu.tsx";
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { useAtom } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import {
|
import {
|
||||||
|
NAVBAR_COLLAPSE_BREAKPOINT,
|
||||||
desktopSidebarAtom,
|
desktopSidebarAtom,
|
||||||
mobileSidebarAtom,
|
mobileSidebarAtom,
|
||||||
} from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
} from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
||||||
@@ -53,7 +54,13 @@ export function AppHeader() {
|
|||||||
aria-label={t("Sidebar toggle")}
|
aria-label={t("Sidebar toggle")}
|
||||||
opened={mobileOpened}
|
opened={mobileOpened}
|
||||||
onClick={toggleMobile}
|
onClick={toggleMobile}
|
||||||
hiddenFrom="sm"
|
// Must match the AppShell navbar breakpoint (md). The navbar
|
||||||
|
// collapses to the MOBILE drawer below md, so the mobile toggle
|
||||||
|
// (which flips mobileOpened) must be the one visible across the
|
||||||
|
// whole <md band — otherwise at 768-991 the desktop toggle showed
|
||||||
|
// but flipped the wrong atom, leaving the drawer unopenable (the
|
||||||
|
// regression from the initial sm->md navbar change).
|
||||||
|
hiddenFrom={NAVBAR_COLLAPSE_BREAKPOINT}
|
||||||
size="sm"
|
size="sm"
|
||||||
/>
|
/>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
@@ -63,7 +70,7 @@ export function AppHeader() {
|
|||||||
aria-label={t("Sidebar toggle")}
|
aria-label={t("Sidebar toggle")}
|
||||||
opened={desktopOpened}
|
opened={desktopOpened}
|
||||||
onClick={toggleDesktop}
|
onClick={toggleDesktop}
|
||||||
visibleFrom="sm"
|
visibleFrom={NAVBAR_COLLAPSE_BREAKPOINT}
|
||||||
size="sm"
|
size="sm"
|
||||||
/>
|
/>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import SettingsSidebar from "@/components/settings/settings-sidebar.tsx";
|
|||||||
import { useAtom } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import {
|
import {
|
||||||
APP_NAVBAR_ID,
|
APP_NAVBAR_ID,
|
||||||
|
NAVBAR_COLLAPSE_BREAKPOINT,
|
||||||
asideStateAtom,
|
asideStateAtom,
|
||||||
desktopSidebarAtom,
|
desktopSidebarAtom,
|
||||||
mobileSidebarAtom,
|
mobileSidebarAtom,
|
||||||
@@ -88,7 +89,13 @@ export default function GlobalAppShell({
|
|||||||
header={{ height: 45 }}
|
header={{ height: 45 }}
|
||||||
navbar={{
|
navbar={{
|
||||||
width: isSpaceRoute ? sidebarWidth : 300,
|
width: isSpaceRoute ? sidebarWidth : 300,
|
||||||
breakpoint: "sm",
|
// `md` (not `sm`): below 992px the fixed ~300px sidebar leaves too little
|
||||||
|
// room for content — the settings tables (Members/…) overflow the offset
|
||||||
|
// content area on tablet (~768px) and clip the Role/actions columns
|
||||||
|
// off-screen with no horizontal scroll. Collapsing the navbar to a toggle
|
||||||
|
// drawer across the whole tablet band frees the full width for content
|
||||||
|
// (the mobile drawer is closed by default, so nothing overlaps on load).
|
||||||
|
breakpoint: NAVBAR_COLLAPSE_BREAKPOINT,
|
||||||
collapsed: {
|
collapsed: {
|
||||||
mobile: !mobileOpened,
|
mobile: !mobileOpened,
|
||||||
desktop: !desktopOpened,
|
desktop: !desktopOpened,
|
||||||
@@ -97,7 +104,7 @@ export default function GlobalAppShell({
|
|||||||
aside={
|
aside={
|
||||||
isPageRoute && {
|
isPageRoute && {
|
||||||
width: 420,
|
width: 420,
|
||||||
breakpoint: "sm",
|
breakpoint: "md",
|
||||||
collapsed: { mobile: !isAsideOpen, desktop: !isAsideOpen },
|
collapsed: { mobile: !isAsideOpen, desktop: !isAsideOpen },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,13 @@ import { atom } from "jotai";
|
|||||||
// would create a shell -> chat-window -> shell import cycle).
|
// would create a shell -> chat-window -> shell import cycle).
|
||||||
export const APP_NAVBAR_ID = "app-shell-navbar";
|
export const APP_NAVBAR_ID = "app-shell-navbar";
|
||||||
|
|
||||||
|
// Single source of truth for the navbar collapse breakpoint. The AppShell navbar
|
||||||
|
// `breakpoint` and BOTH burger toggles' `hiddenFrom`/`visibleFrom` MUST use this
|
||||||
|
// exact value: if they drift, the sidebar becomes unreachable on tablet widths
|
||||||
|
// (the round-1 regression of #292). Kept here so the shell and the header share
|
||||||
|
// one constant the compiler enforces, instead of three hand-synced string literals.
|
||||||
|
export const NAVBAR_COLLAPSE_BREAKPOINT = "md";
|
||||||
|
|
||||||
export const mobileSidebarAtom = atom<boolean>(false);
|
export const mobileSidebarAtom = atom<boolean>(false);
|
||||||
|
|
||||||
export const desktopSidebarAtom = atomWithWebStorage<boolean>(
|
export const desktopSidebarAtom = atomWithWebStorage<boolean>(
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, screen, fireEvent } from "@testing-library/react";
|
||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { Provider, createStore } from "jotai";
|
||||||
|
import { AgentAvatarStack } from "./agent-avatar-stack";
|
||||||
|
import { avatarStyle } from "@/lib/avatar-palette";
|
||||||
|
import {
|
||||||
|
activeAiChatIdAtom,
|
||||||
|
aiChatWindowOpenAtom,
|
||||||
|
aiChatDraftAtom,
|
||||||
|
} from "@/features/ai-chat/atoms/ai-chat-atom.ts";
|
||||||
|
|
||||||
|
// matchMedia (read by MantineProvider) is stubbed globally in vitest.setup.ts.
|
||||||
|
|
||||||
|
type Props = React.ComponentProps<typeof AgentAvatarStack>;
|
||||||
|
|
||||||
|
// The DOM normalizes an inline hex `background-color` to `rgb(...)`. Push the
|
||||||
|
// expected color through the same CSSOM path so the comparison stays exact and
|
||||||
|
// non-vacuous (an empty string — i.e. no inline background, as in the pre-fix
|
||||||
|
// Avatar approach — can never match a real color). NOTE: jsdom's CSSOM does not
|
||||||
|
// round-trip a `linear-gradient` in the `background` shorthand, which is why the
|
||||||
|
// glyph carries an explicit solid `background-color` we assert on here.
|
||||||
|
function normalizeColor(value: string): string {
|
||||||
|
const probe = document.createElement("div");
|
||||||
|
probe.style.backgroundColor = value;
|
||||||
|
return probe.style.backgroundColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderStack(props: Props) {
|
||||||
|
const store = createStore();
|
||||||
|
store.set(aiChatDraftAtom, "leftover draft from another chat");
|
||||||
|
const utils = render(
|
||||||
|
<Provider store={store}>
|
||||||
|
<MantineProvider>
|
||||||
|
<AgentAvatarStack {...props} />
|
||||||
|
</MantineProvider>
|
||||||
|
</Provider>,
|
||||||
|
);
|
||||||
|
return { store, ...utils };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("AgentAvatarStack", () => {
|
||||||
|
it("internal chat WITH role: emoji glyph + human launcher badge in front", () => {
|
||||||
|
const { container } = renderStack({
|
||||||
|
agent: { name: "Researcher", emoji: "🔬", avatarUrl: null },
|
||||||
|
launcher: { name: "Alice", avatarUrl: null },
|
||||||
|
aiChatId: "chat-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Emoji is used as the glyph (priority 2), NOT the sparkles fallback.
|
||||||
|
expect(screen.getByText("🔬")).toBeDefined();
|
||||||
|
expect(container.querySelector(".tabler-icon-sparkles")).toBeNull();
|
||||||
|
// Label: bold role name + dimmed "· launcher".
|
||||||
|
expect(screen.getByText("Researcher")).toBeDefined();
|
||||||
|
expect(screen.getByText(/·/)).toBeDefined();
|
||||||
|
expect(screen.getByText("Alice")).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emoji glyph applies its per-agent gradient as an inline DOM background", () => {
|
||||||
|
// Pins the actual fix: the hashed gradient must reach the DOM as an inline
|
||||||
|
// `background` on the glyph Box. The pre-fix `Avatar variant="filled"` set no
|
||||||
|
// inline background (Mantine's --avatar-bg overrode it), so this fails there.
|
||||||
|
const agent = { name: "Researcher", emoji: "🔬", avatarUrl: null };
|
||||||
|
const { container } = renderStack({
|
||||||
|
agent,
|
||||||
|
launcher: { name: "Alice", avatarUrl: null },
|
||||||
|
aiChatId: "chat-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
const glyph = container.querySelector<HTMLElement>(
|
||||||
|
'[data-testid="agent-glyph"]',
|
||||||
|
);
|
||||||
|
expect(glyph).not.toBeNull();
|
||||||
|
const expected = normalizeColor(avatarStyle(agent.name).bg);
|
||||||
|
// Non-vacuous: the pre-fix Avatar set no inline background at all.
|
||||||
|
expect(expected).not.toBe("");
|
||||||
|
expect(glyph!.style.backgroundColor).toBe(expected);
|
||||||
|
// (The gradient overlay is a browser-only enhancement — jsdom's CSSOM does
|
||||||
|
// not round-trip linear-gradient — so its stops/angle are covered by the
|
||||||
|
// avatarStyle unit tests above, not asserted on the DOM here.)
|
||||||
|
});
|
||||||
|
|
||||||
|
it("agents with distinct styles reach the DOM as distinct backgrounds", () => {
|
||||||
|
// "Researcher" and "Нарратор" hash to different palette entries, so their
|
||||||
|
// applied DOM backgrounds must differ — pins "distinct colors reach the DOM".
|
||||||
|
expect(avatarStyle("Researcher").bg).not.toBe(avatarStyle("Нарратор").bg);
|
||||||
|
|
||||||
|
const a = renderStack({
|
||||||
|
agent: { name: "Researcher", emoji: "🔬", avatarUrl: null },
|
||||||
|
launcher: null,
|
||||||
|
aiChatId: null,
|
||||||
|
});
|
||||||
|
const b = renderStack({
|
||||||
|
agent: { name: "Нарратор", emoji: "📖", avatarUrl: null },
|
||||||
|
launcher: null,
|
||||||
|
aiChatId: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const glyphA = a.container.querySelector<HTMLElement>(
|
||||||
|
'[data-testid="agent-glyph"]',
|
||||||
|
);
|
||||||
|
const glyphB = b.container.querySelector<HTMLElement>(
|
||||||
|
'[data-testid="agent-glyph"]',
|
||||||
|
);
|
||||||
|
expect(glyphA!.style.backgroundColor).not.toBe("");
|
||||||
|
// Different base colors reach the DOM (the serialized rgb values differ).
|
||||||
|
expect(glyphA!.style.backgroundColor).not.toBe(glyphB!.style.backgroundColor);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("showName=false: renders only the avatars, no inline name label", () => {
|
||||||
|
renderStack({
|
||||||
|
agent: { name: "Researcher", emoji: "🔬", avatarUrl: null },
|
||||||
|
launcher: { name: "Alice", avatarUrl: null },
|
||||||
|
aiChatId: "chat-1",
|
||||||
|
showName: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// The agent glyph is still rendered...
|
||||||
|
expect(screen.getByText("🔬")).toBeDefined();
|
||||||
|
// ...but neither the agent NOR the launcher inline name label is rendered
|
||||||
|
// (they live only in the hover tooltip, which is not mounted in the initial
|
||||||
|
// DOM) — guards against suppressing only the agent name and leaking the
|
||||||
|
// launcher name.
|
||||||
|
expect(screen.queryByText("Researcher")).toBeNull();
|
||||||
|
expect(screen.queryByText("Alice")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("internal chat WITHOUT role: sparkles fallback + 'AI agent' + launcher", () => {
|
||||||
|
const { container } = renderStack({
|
||||||
|
agent: { name: "AI agent", avatarUrl: null },
|
||||||
|
launcher: { name: "Bob", avatarUrl: null },
|
||||||
|
aiChatId: "chat-2",
|
||||||
|
});
|
||||||
|
|
||||||
|
// No avatarUrl and no emoji => sparkles glyph (priority 3).
|
||||||
|
expect(container.querySelector(".tabler-icon-sparkles")).not.toBeNull();
|
||||||
|
expect(screen.getByText("AI agent")).toBeDefined();
|
||||||
|
expect(screen.getByText("Bob")).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("external MCP: agent avatar only, NO human launcher badge", () => {
|
||||||
|
const { container } = renderStack({
|
||||||
|
agent: { name: "MCP Bot", avatarUrl: "http://example.test/a.png" },
|
||||||
|
launcher: null,
|
||||||
|
aiChatId: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// avatarUrl provided (priority 1) => not the sparkles fallback.
|
||||||
|
expect(container.querySelector(".tabler-icon-sparkles")).toBeNull();
|
||||||
|
expect(screen.getByText("MCP Bot")).toBeDefined();
|
||||||
|
// No human behind => no "·" separator is rendered.
|
||||||
|
expect(screen.queryByText(/·/)).toBeNull();
|
||||||
|
// No internal chat => the stack is not an interactive deep-link button.
|
||||||
|
expect(screen.queryByRole("button")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("click deep-links into the chat when aiChatId is present", () => {
|
||||||
|
const { store } = renderStack({
|
||||||
|
agent: { name: "Researcher", emoji: "🔬", avatarUrl: null },
|
||||||
|
launcher: { name: "Alice", avatarUrl: null },
|
||||||
|
aiChatId: "chat-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
const button = screen.getByRole("button");
|
||||||
|
fireEvent.click(button);
|
||||||
|
|
||||||
|
expect(store.get(activeAiChatIdAtom)).toBe("chat-1");
|
||||||
|
expect(store.get(aiChatWindowOpenAtom)).toBe(true);
|
||||||
|
expect(store.get(aiChatDraftAtom)).toBe(""); // draft cleared on switch
|
||||||
|
});
|
||||||
|
|
||||||
|
it("click is a no-op / not interactive without a chat target", () => {
|
||||||
|
const onActivate = vi.fn();
|
||||||
|
renderStack({
|
||||||
|
agent: { name: "MCP Bot", avatarUrl: "http://example.test/a.png" },
|
||||||
|
launcher: null,
|
||||||
|
aiChatId: null,
|
||||||
|
onActivate,
|
||||||
|
});
|
||||||
|
expect(screen.queryByRole("button")).toBeNull();
|
||||||
|
expect(onActivate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
import { Box, Group, Text, Tooltip } from "@mantine/core";
|
||||||
|
import { IconSparkles } from "@tabler/icons-react";
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useSetAtom } from "jotai";
|
||||||
|
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||||
|
import { avatarStyle, avatarBackgroundCss } from "@/lib/avatar-palette";
|
||||||
|
import {
|
||||||
|
activeAiChatIdAtom,
|
||||||
|
aiChatWindowOpenAtom,
|
||||||
|
aiChatDraftAtom,
|
||||||
|
} from "@/features/ai-chat/atoms/ai-chat-atom.ts";
|
||||||
|
|
||||||
|
// The FRONT identity (the acting agent) and the BEHIND identity (the human who
|
||||||
|
// launched it). Both are computed server-side (#300) so the client never branches
|
||||||
|
// on the internal-vs-MCP provenance — it just renders whatever it is handed.
|
||||||
|
export interface AgentInfo {
|
||||||
|
name: string;
|
||||||
|
emoji?: string | null;
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
}
|
||||||
|
export interface LauncherInfo {
|
||||||
|
name: string;
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const GLYPH_SIZE = 38;
|
||||||
|
const LAUNCHER_SIZE = 22;
|
||||||
|
// How far the launcher avatar sticks out past the agent's top-right corner — it
|
||||||
|
// sits as a small badge over that corner (above the glyph) and stays fully visible.
|
||||||
|
const LAUNCHER_OVERHANG = 8;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The front avatar. Image-source priority (#300):
|
||||||
|
* 1. agent.avatarUrl -> a real avatar image (external MCP agent account).
|
||||||
|
* 2. agent.emoji -> the role emoji on a per-agent gradient circle.
|
||||||
|
* 3. otherwise -> the IconSparkles glyph on a per-agent gradient circle.
|
||||||
|
*/
|
||||||
|
function AgentGlyph({ agent }: { agent: AgentInfo }) {
|
||||||
|
if (agent.avatarUrl) {
|
||||||
|
return (
|
||||||
|
<CustomAvatar
|
||||||
|
size={GLYPH_SIZE}
|
||||||
|
avatarUrl={agent.avatarUrl}
|
||||||
|
name={agent.name}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emoji/sparkles glyph on a per-agent gradient circle (color, gradient partner
|
||||||
|
// and split angle all hashed from the agent name via avatarStyle — see
|
||||||
|
// @/lib/avatar-palette). Rendered as a plain Box, NOT a Mantine
|
||||||
|
// `Avatar variant="filled"` — Mantine's `--avatar-bg` overrode the background
|
||||||
|
// (every agent fell back to the theme's violet). The foreground (the sparkles
|
||||||
|
// icon) uses the ring's WCAG-checked readable text color.
|
||||||
|
const style = avatarStyle(agent.name);
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
data-testid="agent-glyph"
|
||||||
|
style={{
|
||||||
|
width: GLYPH_SIZE,
|
||||||
|
height: GLYPH_SIZE,
|
||||||
|
borderRadius: "50%",
|
||||||
|
// Solid base color is the fallback (and the testable value); the gradient
|
||||||
|
// paints over it in browsers that support it.
|
||||||
|
backgroundColor: style.bg,
|
||||||
|
backgroundImage: avatarBackgroundCss(style),
|
||||||
|
color:
|
||||||
|
style.text === "white"
|
||||||
|
? "var(--mantine-color-white)"
|
||||||
|
: "var(--mantine-color-black)",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
lineHeight: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{agent.emoji ? (
|
||||||
|
<span style={{ fontSize: Math.round(GLYPH_SIZE * 0.5) }} aria-hidden>
|
||||||
|
{agent.emoji}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<IconSparkles size={Math.round(GLYPH_SIZE * 0.55)} stroke={2} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AgentAvatarStackProps {
|
||||||
|
agent: AgentInfo;
|
||||||
|
// null/absent => external MCP (front agent avatar only, no human behind).
|
||||||
|
launcher?: LauncherInfo | null;
|
||||||
|
// Deep-links into the internal AI chat when present (null for external MCP).
|
||||||
|
aiChatId?: string | null;
|
||||||
|
// Fired after the stack deep-links into its chat, so the caller can react
|
||||||
|
// (e.g. the page-history row closes the history modal). Keeps this ui/ primitive
|
||||||
|
// free of cross-feature coupling (inherited from the old AiAgentBadge, #143).
|
||||||
|
onActivate?: () => void;
|
||||||
|
// Whether to render the inline name label next to the avatars (default true).
|
||||||
|
// Set false when the caller renders the name itself (e.g. the comment row).
|
||||||
|
showName?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The "agent avatar stack" (#300): the AGENT glyph, and — for an internal AI
|
||||||
|
* chat — the HUMAN who launched it as a smaller avatar badge on top, overhanging
|
||||||
|
* the glyph's top-right corner in FRONT (zIndex 2 > the glyph's zIndex 1) so the
|
||||||
|
* launcher stays fully visible rather than being half-hidden behind the glyph.
|
||||||
|
* Replaces the old text `AI-agent` badge. When the item carries an `aiChatId` the
|
||||||
|
* whole stack is a deep-link into that chat (the click the old badge owned moved
|
||||||
|
* here); the click is contained (stopPropagation) so it does not also trigger an
|
||||||
|
* enclosing row handler.
|
||||||
|
*/
|
||||||
|
export function AgentAvatarStack({
|
||||||
|
agent,
|
||||||
|
launcher,
|
||||||
|
aiChatId,
|
||||||
|
onActivate,
|
||||||
|
showName = true,
|
||||||
|
}: AgentAvatarStackProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const setAiChatWindowOpen = useSetAtom(aiChatWindowOpenAtom);
|
||||||
|
const setActiveChatId = useSetAtom(activeAiChatIdAtom);
|
||||||
|
const setDraft = useSetAtom(aiChatDraftAtom);
|
||||||
|
|
||||||
|
const clickable = !!aiChatId;
|
||||||
|
|
||||||
|
const openChat = useCallback(
|
||||||
|
(event: React.SyntheticEvent) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
if (!aiChatId) return;
|
||||||
|
setActiveChatId(aiChatId);
|
||||||
|
// Switching chats must start with a clean composer — clear any unsent draft
|
||||||
|
// so it does not leak from the previously open chat.
|
||||||
|
setDraft("");
|
||||||
|
setAiChatWindowOpen(true);
|
||||||
|
onActivate?.();
|
||||||
|
},
|
||||||
|
[aiChatId, setActiveChatId, setDraft, setAiChatWindowOpen, onActivate],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Internal chat => "role on behalf of person"; external MCP => just the agent.
|
||||||
|
const tooltip = launcher
|
||||||
|
? t("AI agent «{{role}}» on behalf of {{person}}", {
|
||||||
|
role: agent.name,
|
||||||
|
person: launcher.name,
|
||||||
|
})
|
||||||
|
: t("AI agent {{name}}", { name: agent.name });
|
||||||
|
|
||||||
|
// The container is only enlarged when there is a launcher to overhang; with no
|
||||||
|
// human behind it stays tight at the agent glyph size.
|
||||||
|
const stackSize = launcher ? GLYPH_SIZE + LAUNCHER_OVERHANG : GLYPH_SIZE;
|
||||||
|
|
||||||
|
const stack = (
|
||||||
|
<Box
|
||||||
|
pos="relative"
|
||||||
|
style={{
|
||||||
|
width: stackSize,
|
||||||
|
height: stackSize,
|
||||||
|
flexShrink: 0,
|
||||||
|
// Center the (in-flow) agent glyph vertically so it lines up with its
|
||||||
|
// name label; the absolutely-positioned launcher is unaffected by flex.
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
cursor: clickable ? "pointer" : undefined,
|
||||||
|
}}
|
||||||
|
{...(clickable
|
||||||
|
? {
|
||||||
|
role: "button",
|
||||||
|
tabIndex: 0,
|
||||||
|
onClick: openChat,
|
||||||
|
onKeyDown: (event: React.KeyboardEvent) => {
|
||||||
|
if (event.key === "Enter" || event.key === " ") {
|
||||||
|
event.preventDefault();
|
||||||
|
openChat(event);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {})}
|
||||||
|
>
|
||||||
|
{launcher && (
|
||||||
|
// Launcher badge sits ABOVE the agent glyph (zIndex) at the top-right so
|
||||||
|
// it is fully visible, not half-hidden behind the agent circle.
|
||||||
|
<Box pos="absolute" top={0} right={0} style={{ zIndex: 2 }}>
|
||||||
|
<CustomAvatar
|
||||||
|
size={LAUNCHER_SIZE}
|
||||||
|
avatarUrl={launcher.avatarUrl}
|
||||||
|
name={launcher.name}
|
||||||
|
style={{ border: "2px solid var(--mantine-color-body)" }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
{/* The agent glyph keeps its own size (flex-centered in the container); the
|
||||||
|
launcher overhangs it by LAUNCHER_OVERHANG at the top-right and stays visible. */}
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
position: "relative",
|
||||||
|
zIndex: 1,
|
||||||
|
width: GLYPH_SIZE,
|
||||||
|
height: GLYPH_SIZE,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<AgentGlyph agent={agent} />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
||||||
|
<Tooltip label={tooltip} withArrow>
|
||||||
|
{stack}
|
||||||
|
</Tooltip>
|
||||||
|
{showName && (
|
||||||
|
<Group gap={4} wrap="nowrap" style={{ minWidth: 0 }}>
|
||||||
|
<Text size="xs" fw={600} lineClamp={1} lh={1.2}>
|
||||||
|
{agent.name}
|
||||||
|
</Text>
|
||||||
|
{launcher && (
|
||||||
|
<>
|
||||||
|
<Text size="xs" c="dimmed" fw={400} aria-hidden>
|
||||||
|
·
|
||||||
|
</Text>
|
||||||
|
<Text size="xs" c="dimmed" fw={400} lineClamp={1} lh={1.2}>
|
||||||
|
{launcher.name}
|
||||||
|
</Text>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AgentAvatarStack;
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
import { describe, it, expect, vi } from "vitest";
|
|
||||||
import { render, screen, fireEvent } from "@testing-library/react";
|
|
||||||
import { MantineProvider } from "@mantine/core";
|
|
||||||
import { Provider, createStore } from "jotai";
|
|
||||||
import { AiAgentBadge } from "./ai-agent-badge";
|
|
||||||
import {
|
|
||||||
activeAiChatIdAtom,
|
|
||||||
aiChatWindowOpenAtom,
|
|
||||||
aiChatDraftAtom,
|
|
||||||
} from "@/features/ai-chat/atoms/ai-chat-atom.ts";
|
|
||||||
|
|
||||||
// matchMedia (read by MantineProvider) is stubbed globally in vitest.setup.ts.
|
|
||||||
|
|
||||||
function renderBadge(props: { authorName?: string; aiChatId?: string | null }) {
|
|
||||||
return render(
|
|
||||||
<MantineProvider>
|
|
||||||
<AiAgentBadge {...props} />
|
|
||||||
</MantineProvider>,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Render a clickable badge inside an explicit jotai store, with a leftover draft
|
|
||||||
// and an onActivate + parent-click spy, so the deep-link side effects are
|
|
||||||
// assertable. Returns the store and spies.
|
|
||||||
function setupClickable() {
|
|
||||||
const store = createStore();
|
|
||||||
store.set(aiChatDraftAtom, "leftover draft from another chat");
|
|
||||||
const onActivate = vi.fn();
|
|
||||||
const onParentClick = vi.fn();
|
|
||||||
render(
|
|
||||||
<Provider store={store}>
|
|
||||||
<MantineProvider>
|
|
||||||
<div onClick={onParentClick}>
|
|
||||||
<AiAgentBadge authorName="Bot" aiChatId="chat-1" onActivate={onActivate} />
|
|
||||||
</div>
|
|
||||||
</MantineProvider>
|
|
||||||
</Provider>,
|
|
||||||
);
|
|
||||||
return { store, onActivate, onParentClick, badge: screen.getByRole("button") };
|
|
||||||
}
|
|
||||||
|
|
||||||
function expectDeepLinked(store: ReturnType<typeof createStore>, onActivate: ReturnType<typeof vi.fn>) {
|
|
||||||
expect(store.get(activeAiChatIdAtom)).toBe("chat-1");
|
|
||||||
expect(store.get(aiChatWindowOpenAtom)).toBe(true);
|
|
||||||
expect(store.get(aiChatDraftAtom)).toBe(""); // draft cleared
|
|
||||||
expect(onActivate).toHaveBeenCalledTimes(1); // caller closes its own modal etc.
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("AiAgentBadge", () => {
|
|
||||||
it("renders the AI-agent label", () => {
|
|
||||||
renderBadge({ authorName: "Bot" });
|
|
||||||
expect(screen.getByText("AI-agent")).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("is clickable (accessible button) when aiChatId is present", () => {
|
|
||||||
renderBadge({ authorName: "Bot", aiChatId: "chat-1" });
|
|
||||||
const badge = screen.getByRole("button");
|
|
||||||
expect(badge).toBeDefined();
|
|
||||||
expect(badge.textContent).toContain("AI-agent");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("click deep-links: sets active chat, clears draft, opens window, fires onActivate, stops propagation", () => {
|
|
||||||
const { store, onActivate, onParentClick, badge } = setupClickable();
|
|
||||||
fireEvent.click(badge);
|
|
||||||
expectDeepLinked(store, onActivate);
|
|
||||||
expect(onParentClick).not.toHaveBeenCalled(); // stopPropagation contained the click
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(["Enter", " "])(
|
|
||||||
"keyboard %j activates the deep-link (same side effects as click)",
|
|
||||||
(key) => {
|
|
||||||
const { store, onActivate, badge } = setupClickable();
|
|
||||||
fireEvent.keyDown(badge, { key });
|
|
||||||
expectDeepLinked(store, onActivate);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
it("an unrelated key does NOT activate the badge", () => {
|
|
||||||
const { store, onActivate, badge } = setupClickable();
|
|
||||||
fireEvent.keyDown(badge, { key: "Tab" });
|
|
||||||
expect(store.get(activeAiChatIdAtom)).toBeNull();
|
|
||||||
expect(store.get(aiChatWindowOpenAtom)).toBe(false);
|
|
||||||
expect(store.get(aiChatDraftAtom)).toBe("leftover draft from another chat");
|
|
||||||
expect(onActivate).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([{ aiChatId: null }, {}])(
|
|
||||||
"is a plain non-clickable label without a chat target (%o)",
|
|
||||||
(props) => {
|
|
||||||
renderBadge({ authorName: "Bot", ...props });
|
|
||||||
expect(screen.getByText("AI-agent")).toBeDefined();
|
|
||||||
// No interactive role is exposed when there is no chat to deep-link into.
|
|
||||||
expect(screen.queryByRole("button")).toBeNull();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
import { Badge, Tooltip } from "@mantine/core";
|
|
||||||
import { IconSparkles } from "@tabler/icons-react";
|
|
||||||
import { useCallback } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { useSetAtom } from "jotai";
|
|
||||||
import {
|
|
||||||
activeAiChatIdAtom,
|
|
||||||
aiChatWindowOpenAtom,
|
|
||||||
aiChatDraftAtom,
|
|
||||||
} from "@/features/ai-chat/atoms/ai-chat-atom.ts";
|
|
||||||
|
|
||||||
interface AiAgentBadgeProps {
|
|
||||||
authorName?: string;
|
|
||||||
aiChatId?: string | null;
|
|
||||||
// Fired after the badge deep-links into its chat. The caller handles its own
|
|
||||||
// context (e.g. the page-history row closes the history modal) so this generic
|
|
||||||
// ui/ primitive stays free of cross-feature coupling (#143 review Arch B).
|
|
||||||
onActivate?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Badge marking content written by the AI agent (provenance C3 / §7.4). It is
|
|
||||||
* ADDITIVE — shown next to the human author, never replacing them. Reused by the
|
|
||||||
* page-history list and the comments sidebar.
|
|
||||||
*
|
|
||||||
* When the item carries an `aiChatId` (an internal AI-chat edit), clicking the
|
|
||||||
* badge deep-links into that chat: it sets the active-chat atom and opens the
|
|
||||||
* floating AI-chat window, then invokes `onActivate` so the caller can react
|
|
||||||
* (e.g. the history modal closes itself). When `aiChatId` is null/absent (an
|
|
||||||
* external MCP write with no internal ai_chats row), the badge is a plain
|
|
||||||
* non-clickable label. The click is contained (stopPropagation) so it does not
|
|
||||||
* also trigger an enclosing row's click handler.
|
|
||||||
*/
|
|
||||||
export function AiAgentBadge({
|
|
||||||
authorName,
|
|
||||||
aiChatId,
|
|
||||||
onActivate,
|
|
||||||
}: AiAgentBadgeProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const setAiChatWindowOpen = useSetAtom(aiChatWindowOpenAtom);
|
|
||||||
const setActiveChatId = useSetAtom(activeAiChatIdAtom);
|
|
||||||
const setDraft = useSetAtom(aiChatDraftAtom);
|
|
||||||
|
|
||||||
const tooltip = t("Edited by AI agent on behalf of {{name}}", {
|
|
||||||
name: authorName ?? "",
|
|
||||||
});
|
|
||||||
|
|
||||||
const openChat = useCallback(
|
|
||||||
(event: React.SyntheticEvent) => {
|
|
||||||
event.stopPropagation();
|
|
||||||
if (!aiChatId) return;
|
|
||||||
setActiveChatId(aiChatId);
|
|
||||||
// Switching to another chat must start with a clean composer — clear any
|
|
||||||
// unsent draft so it does not leak from the previously open chat.
|
|
||||||
setDraft("");
|
|
||||||
setAiChatWindowOpen(true);
|
|
||||||
onActivate?.();
|
|
||||||
},
|
|
||||||
[aiChatId, setActiveChatId, setDraft, setAiChatWindowOpen, onActivate],
|
|
||||||
);
|
|
||||||
|
|
||||||
const badge = (
|
|
||||||
<Badge
|
|
||||||
size="sm"
|
|
||||||
variant="light"
|
|
||||||
color="violet"
|
|
||||||
radius="sm"
|
|
||||||
leftSection={<IconSparkles size={12} stroke={2} />}
|
|
||||||
style={aiChatId ? { cursor: "pointer" } : undefined}
|
|
||||||
{...(aiChatId
|
|
||||||
? {
|
|
||||||
// Keep the default Badge root element (not a <button>) to avoid an
|
|
||||||
// invalid <button>-in-<button> nesting inside a row's
|
|
||||||
// UnstyledButton; expose it as an accessible button via
|
|
||||||
// role/keyboard.
|
|
||||||
role: "button",
|
|
||||||
tabIndex: 0,
|
|
||||||
onClick: openChat,
|
|
||||||
onKeyDown: (event: React.KeyboardEvent) => {
|
|
||||||
if (event.key === "Enter" || event.key === " ") {
|
|
||||||
event.preventDefault();
|
|
||||||
openChat(event);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: {})}
|
|
||||||
>
|
|
||||||
{t("AI-agent")}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Tooltip label={tooltip} withArrow>
|
|
||||||
{badge}
|
|
||||||
</Tooltip>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default AiAgentBadge;
|
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { Badge, Tooltip } from "@mantine/core";
|
||||||
|
import { IconGitMerge } from "@tabler/icons-react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
interface GitSyncBadgeProps {
|
||||||
|
authorName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Badge marking a version produced by git-sync (provenance §8.1). The history
|
||||||
|
* version is created on the PUSH path — when an incoming git body is written back
|
||||||
|
* into the Docmost doc — not by the pull itself. Like {@link AiAgentBadge} it is
|
||||||
|
* ADDITIVE — shown next to the human author, never replacing them — but a git-sync
|
||||||
|
* edit is NOT an agent edit and has no chat to deep-link into, so it is a small,
|
||||||
|
* neutral, non-clickable label.
|
||||||
|
*/
|
||||||
|
export function GitSyncBadge({ authorName }: GitSyncBadgeProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const tooltip = t("Synced from Git on behalf of {{name}}", {
|
||||||
|
name: authorName ?? "",
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tooltip label={tooltip} withArrow>
|
||||||
|
<Badge
|
||||||
|
size="sm"
|
||||||
|
variant="light"
|
||||||
|
color="gray"
|
||||||
|
radius="sm"
|
||||||
|
leftSection={<IconGitMerge size={12} stroke={2} />}
|
||||||
|
>
|
||||||
|
{t("Git sync")}
|
||||||
|
</Badge>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -164,8 +164,8 @@
|
|||||||
/* NOTE: `white-space: pre-wrap` is intentionally NOT set here. On the
|
/* NOTE: `white-space: pre-wrap` is intentionally NOT set here. On the
|
||||||
rendered markdown <div> it would turn the newlines between block tags
|
rendered markdown <div> it would turn the newlines between block tags
|
||||||
(</li>\n<li>, </p>\n<ol>) into visible blank lines/indents on top of the
|
(</li>\n<li>, </p>\n<ol>) into visible blank lines/indents on top of the
|
||||||
margins. The plain-text fallback <Text> that needs pre-wrap sets it
|
margins. The streaming plain-text path that needs pre-wrap sets it
|
||||||
inline itself (see reasoning-block.tsx). */
|
per chunk instead, in PlainChunk (see streaming-plain-text.tsx). */
|
||||||
}
|
}
|
||||||
|
|
||||||
.reasoningText p {
|
.reasoningText p {
|
||||||
|
|||||||
@@ -65,6 +65,25 @@ describe("arePropsEqual", () => {
|
|||||||
expect(arePropsEqual(props(m), props(m))).toBe(true);
|
expect(arePropsEqual(props(m), props(m))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// REGRESSION (stranded reasoning part): a reasoning part is left at
|
||||||
|
// `state:"streaming"` forever when the turn ends without `reasoning-end`
|
||||||
|
// (manual Stop during thinking). The signature is EQUAL across that turn-end
|
||||||
|
// flip (nothing in the message changed), so the comparator must ALSO compare
|
||||||
|
// `turnStreaming` — otherwise the memo swallows the flip and ReasoningBlock
|
||||||
|
// never switches from chunked plain text to its one-time markdown parse.
|
||||||
|
it("returns false when turnStreaming differs despite an equal signature", () => {
|
||||||
|
const m = msg([
|
||||||
|
{ type: "reasoning", text: "thinking", state: "streaming" },
|
||||||
|
{ type: "text", text: "answer" },
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
arePropsEqual(
|
||||||
|
props(m, { turnStreaming: true }),
|
||||||
|
props(m, { turnStreaming: false }),
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it("returns true for the same content in a different message object", () => {
|
it("returns true for the same content in a different message object", () => {
|
||||||
const a = msg([{ type: "text", text: "answer" }]);
|
const a = msg([{ type: "text", text: "answer" }]);
|
||||||
const b = msg([{ type: "text", text: "answer" }]);
|
const b = msg([{ type: "text", text: "answer" }]);
|
||||||
|
|||||||
@@ -52,6 +52,20 @@ interface MessageItemProps {
|
|||||||
* absent; the public share passes the configured identity (agent role) name.
|
* absent; the public share passes the configured identity (agent role) name.
|
||||||
*/
|
*/
|
||||||
assistantName?: string;
|
assistantName?: string;
|
||||||
|
/**
|
||||||
|
* Whether the WHOLE turn is still streaming (MessageList's `isStreaming`).
|
||||||
|
* A reasoning part may be left `state: "streaming"` forever when the turn
|
||||||
|
* ends without a `reasoning-end` chunk (manual Stop during the thinking
|
||||||
|
* phase, or a provider that never emits it) — the AI SDK finalizes reasoning
|
||||||
|
* state ONLY on `reasoning-end`, not on `finish-step`/`finish`. So part-level
|
||||||
|
* state alone cannot prove liveness; the reasoning part is treated as live
|
||||||
|
* only while the whole turn is still streaming. Defaults to false.
|
||||||
|
*
|
||||||
|
* The parent passes it as "turn is live AND this is the tail row", so a
|
||||||
|
* stranded part in an EARLIER row never re-activates when a later turn
|
||||||
|
* streams.
|
||||||
|
*/
|
||||||
|
turnStreaming?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -105,6 +119,7 @@ function MessageItem({
|
|||||||
showCitations = true,
|
showCitations = true,
|
||||||
neutralizeInternalLinks = false,
|
neutralizeInternalLinks = false,
|
||||||
assistantName,
|
assistantName,
|
||||||
|
turnStreaming = false,
|
||||||
}: MessageItemProps) {
|
}: MessageItemProps) {
|
||||||
// `signature` is intentionally not read in the body — it exists solely as the
|
// `signature` is intentionally not read in the body — it exists solely as the
|
||||||
// memo key (see arePropsEqual). The render reads `message` directly.
|
// memo key (see arePropsEqual). The render reads `message` directly.
|
||||||
@@ -155,8 +170,23 @@ function MessageItem({
|
|||||||
const text = (part as { text?: string }).text ?? "";
|
const text = (part as { text?: string }).text ?? "";
|
||||||
if (!text.trim() && !(reasoningTokens && reasoningTokens > 0))
|
if (!text.trim() && !(reasoningTokens && reasoningTokens > 0))
|
||||||
return null;
|
return null;
|
||||||
|
// Absent state (persisted rows) and "done" both mean finalized.
|
||||||
|
// `messageSignature` already includes each part's `state`, so the
|
||||||
|
// streaming→done flip changes the row signature and re-renders this
|
||||||
|
// row — which is what lets ReasoningBlock switch from chunked plain
|
||||||
|
// text to its one-time markdown parse (see reasoning-block.tsx).
|
||||||
|
// ALSO require the turn to be live: a part stranded at
|
||||||
|
// `state:"streaming"` after the turn ended (no `reasoning-end` — see
|
||||||
|
// the `turnStreaming` prop doc) must still finalize and parse.
|
||||||
|
const streaming =
|
||||||
|
turnStreaming && (part as { state?: string }).state === "streaming";
|
||||||
return (
|
return (
|
||||||
<ReasoningBlock key={index} text={text} tokens={reasoningTokens} />
|
<ReasoningBlock
|
||||||
|
key={index}
|
||||||
|
text={text}
|
||||||
|
tokens={reasoningTokens}
|
||||||
|
streaming={streaming}
|
||||||
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,7 +275,11 @@ export function arePropsEqual(
|
|||||||
prev.signature === next.signature &&
|
prev.signature === next.signature &&
|
||||||
prev.showCitations === next.showCitations &&
|
prev.showCitations === next.showCitations &&
|
||||||
prev.neutralizeInternalLinks === next.neutralizeInternalLinks &&
|
prev.neutralizeInternalLinks === next.neutralizeInternalLinks &&
|
||||||
prev.assistantName === next.assistantName
|
prev.assistantName === next.assistantName &&
|
||||||
|
// The turn-end flip re-renders every row once (cheap, terminal event) —
|
||||||
|
// that is what converts a stranded `state:"streaming"` reasoning part to
|
||||||
|
// its one-time markdown parse (see the `turnStreaming` prop doc).
|
||||||
|
prev.turnStreaming === next.turnStreaming
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { render } from "@testing-library/react";
|
import { fireEvent, render } from "@testing-library/react";
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import type { UIMessage } from "@ai-sdk/react";
|
import type { UIMessage } from "@ai-sdk/react";
|
||||||
|
|
||||||
@@ -50,8 +50,9 @@ vi.stubGlobal(
|
|||||||
|
|
||||||
// One assistant message wrapping the given `parts`. Reused across renders in the
|
// One assistant message wrapping the given `parts`. Reused across renders in the
|
||||||
// regression test to model how the AI SDK hands back the SAME message object.
|
// regression test to model how the AI SDK hands back the SAME message object.
|
||||||
const msg = (parts: UIMessage["parts"]): UIMessage =>
|
// Pass an explicit `id` when a test renders several rows at once.
|
||||||
({ id: "m1", role: "assistant", parts }) as UIMessage;
|
const msg = (parts: UIMessage["parts"], id = "m1"): UIMessage =>
|
||||||
|
({ id, role: "assistant", parts }) as UIMessage;
|
||||||
|
|
||||||
describe("MessageList", () => {
|
describe("MessageList", () => {
|
||||||
it("wires the real MessageItem and supplies a valid signature end-to-end", () => {
|
it("wires the real MessageItem and supplies a valid signature end-to-end", () => {
|
||||||
@@ -116,4 +117,102 @@ describe("MessageList", () => {
|
|||||||
renderChatMarkdownSpy.mock.calls.some((c) => c[0] === "streamed answer"),
|
renderChatMarkdownSpy.mock.calls.some((c) => c[0] === "streamed answer"),
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// REGRESSION (stranded reasoning part): the AI SDK sets a reasoning part's
|
||||||
|
// state to "done" ONLY on the `reasoning-end` chunk — `finish-step`/`finish`
|
||||||
|
// do NOT finalize it. A manual Stop during the thinking phase (or a provider
|
||||||
|
// that never emits `reasoning-end`) therefore leaves the part at
|
||||||
|
// `state:"streaming"` forever. MessageItem must derive ReasoningBlock's
|
||||||
|
// `streaming` from part state AND turn liveness (MessageList's `isStreaming`,
|
||||||
|
// forwarded as `turnStreaming`): while the turn streams the expanded block
|
||||||
|
// shows chunked plain text (no parse); once the turn ends — even though the
|
||||||
|
// part is still `state:"streaming"` — the block finalizes and does its
|
||||||
|
// one-time markdown parse. Note the message signature does NOT change across
|
||||||
|
// that flip, so this also exercises the `turnStreaming` memo comparison in
|
||||||
|
// arePropsEqual (without it the row would never re-render).
|
||||||
|
it("finalizes a reasoning part stranded at state:'streaming' when the turn ends", () => {
|
||||||
|
renderChatMarkdownSpy.mockClear();
|
||||||
|
const reasoningText = "**bold** thinking";
|
||||||
|
// Reasoning part stranded mid-stream + a non-empty answer part (a
|
||||||
|
// reasoning-only message renders nothing — see message-content.ts).
|
||||||
|
const message = msg([
|
||||||
|
{ type: "reasoning", text: reasoningText, state: "streaming" },
|
||||||
|
{ type: "text", text: "partial answer" },
|
||||||
|
]);
|
||||||
|
const parsesOfReasoning = () =>
|
||||||
|
renderChatMarkdownSpy.mock.calls.filter((c) => c[0] === reasoningText)
|
||||||
|
.length;
|
||||||
|
|
||||||
|
const { rerender, getByRole, queryByText } = render(
|
||||||
|
<MantineProvider>
|
||||||
|
<MessageList messages={[message]} isStreaming />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
// Expand the reasoning block (its toggle is the only button in the list).
|
||||||
|
fireEvent.click(getByRole("button"));
|
||||||
|
// Turn live + part streaming -> ReasoningBlock received streaming=true:
|
||||||
|
// the body is chunked plain text (raw markdown syntax), NOT parsed.
|
||||||
|
expect(queryByText(/bold/)).not.toBeNull();
|
||||||
|
expect(parsesOfReasoning()).toBe(0);
|
||||||
|
|
||||||
|
// The turn ends WITHOUT `reasoning-end`: the part object is untouched
|
||||||
|
// (still state:"streaming"), only the turn-level flag flips.
|
||||||
|
rerender(
|
||||||
|
<MantineProvider>
|
||||||
|
<MessageList messages={[message]} isStreaming={false} />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
// ReasoningBlock now received streaming=false and did its one-time parse.
|
||||||
|
expect(parsesOfReasoning()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// REGRESSION (turn-global liveness leaking into earlier rows): `isStreaming`
|
||||||
|
// is turn-global, so forwarding it to EVERY row would re-mark a reasoning
|
||||||
|
// part stranded at `state:"streaming"` in a PREVIOUS message (see the test
|
||||||
|
// above) as live again whenever a LATER turn streams — an expanded stranded
|
||||||
|
// block would flip markdown -> raw plain text -> markdown across turn
|
||||||
|
// boundaries, re-parsing each time. MessageList must gate `turnStreaming`
|
||||||
|
// to the TAIL row only.
|
||||||
|
it("keeps a stranded reasoning part in an earlier message finalized while a later turn streams", () => {
|
||||||
|
renderChatMarkdownSpy.mockClear();
|
||||||
|
const reasoningText = "**bold** thinking";
|
||||||
|
// First (earlier) assistant message: its turn was stopped during the
|
||||||
|
// thinking phase, leaving the reasoning part at state:"streaming".
|
||||||
|
const first = msg(
|
||||||
|
[
|
||||||
|
{ type: "reasoning", text: reasoningText, state: "streaming" },
|
||||||
|
{ type: "text", text: "first answer" },
|
||||||
|
],
|
||||||
|
"m1",
|
||||||
|
);
|
||||||
|
// Second assistant message: the LATER turn, currently streaming.
|
||||||
|
const second = msg([{ type: "text", text: "second answer" }], "m2");
|
||||||
|
const parsesOfReasoning = () =>
|
||||||
|
renderChatMarkdownSpy.mock.calls.filter((c) => c[0] === reasoningText)
|
||||||
|
.length;
|
||||||
|
|
||||||
|
const { rerender, getByRole, queryByText } = render(
|
||||||
|
<MantineProvider>
|
||||||
|
<MessageList messages={[first, second]} isStreaming />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
// Expand the first row's reasoning block (the only toggle in the list —
|
||||||
|
// the second message has no reasoning or tool parts).
|
||||||
|
fireEvent.click(getByRole("button"));
|
||||||
|
// The turn is live but the first row is NOT the tail: its ReasoningBlock
|
||||||
|
// received streaming=false, so the stranded part stays finalized and does
|
||||||
|
// its one-time markdown parse instead of dropping to chunked plain text.
|
||||||
|
expect(queryByText(/bold/)).not.toBeNull();
|
||||||
|
expect(parsesOfReasoning()).toBe(1);
|
||||||
|
|
||||||
|
// A later-turn delta re-renders the list; the earlier block must neither
|
||||||
|
// flip back to streaming nor re-parse.
|
||||||
|
(second.parts[0] as { text: string }).text = "second answer grows";
|
||||||
|
rerender(
|
||||||
|
<MantineProvider>
|
||||||
|
<MessageList messages={[first, second]} isStreaming />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
expect(parsesOfReasoning()).toBe(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ export default function MessageList({
|
|||||||
return (
|
return (
|
||||||
<ScrollArea className={classes.messages} viewportRef={viewportRef} scrollbarSize={6} type="scroll">
|
<ScrollArea className={classes.messages} viewportRef={viewportRef} scrollbarSize={6} type="scroll">
|
||||||
<Stack gap={0} pr="xs">
|
<Stack gap={0} pr="xs">
|
||||||
{messages.map((message) => (
|
{messages.map((message, index) => (
|
||||||
// `signature` is snapshotted HERE (parent render) into an immutable
|
// `signature` is snapshotted HERE (parent render) into an immutable
|
||||||
// string and handed to MessageItem as its memo key. It must NOT be
|
// string and handed to MessageItem as its memo key. It must NOT be
|
||||||
// recomputed inside MessageItem's arePropsEqual: the AI SDK mutates the
|
// recomputed inside MessageItem's arePropsEqual: the AI SDK mutates the
|
||||||
@@ -210,6 +210,13 @@ export default function MessageList({
|
|||||||
showCitations={showCitations}
|
showCitations={showCitations}
|
||||||
neutralizeInternalLinks={neutralizeInternalLinks}
|
neutralizeInternalLinks={neutralizeInternalLinks}
|
||||||
assistantName={assistantName}
|
assistantName={assistantName}
|
||||||
|
// Turn-level liveness, gated to the TAIL row: only the tail message
|
||||||
|
// can belong to the in-flight turn, so a reasoning part stranded at
|
||||||
|
// `state:"streaming"` in an EARLIER message (its turn ended without
|
||||||
|
// `reasoning-end`) stays finalized and doesn't flip back to plain
|
||||||
|
// text (and re-parse) whenever a later turn streams — see
|
||||||
|
// message-item.tsx.
|
||||||
|
turnStreaming={isStreaming && index === messages.length - 1}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
{typing && (
|
{typing && (
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
import { describe, it, expect, vi } from "vitest";
|
import { describe, it, expect, vi } from "vitest";
|
||||||
import { render, screen } from "@testing-library/react";
|
import { render, screen, fireEvent } from "@testing-library/react";
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
|
||||||
|
// Spy on the markdown renderer so we can assert it is NOT called while the block
|
||||||
|
// is collapsed (the #302 fix) and IS called once on expand. The count/fallback
|
||||||
|
// tests don't depend on real markdown, so a light stub is safe.
|
||||||
|
vi.mock("@/features/ai-chat/utils/markdown.ts", () => ({
|
||||||
|
renderChatMarkdown: vi.fn((md: string) => `<p>${md}</p>`),
|
||||||
|
}));
|
||||||
|
|
||||||
// Stub react-i18next so `t` returns the key with `{{count}}` interpolated. This
|
// Stub react-i18next so `t` returns the key with `{{count}}` interpolated. This
|
||||||
// keeps the assertions on the component's OWN count logic (authoritative vs
|
// keeps the assertions on the component's OWN count logic (authoritative vs
|
||||||
// estimate) rather than on translation, and mirrors the t-mock pattern used by
|
// estimate) rather than on translation, and mirrors the t-mock pattern used by
|
||||||
@@ -17,10 +24,15 @@ vi.mock("react-i18next", () => ({
|
|||||||
|
|
||||||
import ReasoningBlock from "./reasoning-block";
|
import ReasoningBlock from "./reasoning-block";
|
||||||
import { estimateTokens } from "@/features/ai-chat/utils/count-stream-tokens.ts";
|
import { estimateTokens } from "@/features/ai-chat/utils/count-stream-tokens.ts";
|
||||||
|
import { renderChatMarkdown } from "@/features/ai-chat/utils/markdown.ts";
|
||||||
|
|
||||||
// matchMedia (read by MantineProvider) is stubbed globally in vitest.setup.ts.
|
// matchMedia (read by MantineProvider) is stubbed globally in vitest.setup.ts.
|
||||||
|
|
||||||
function renderBlock(props: { text: string; tokens?: number }) {
|
function renderBlock(props: {
|
||||||
|
text: string;
|
||||||
|
tokens?: number;
|
||||||
|
streaming?: boolean;
|
||||||
|
}) {
|
||||||
return render(
|
return render(
|
||||||
<MantineProvider>
|
<MantineProvider>
|
||||||
<ReasoningBlock {...props} />
|
<ReasoningBlock {...props} />
|
||||||
@@ -62,4 +74,68 @@ describe("ReasoningBlock", () => {
|
|||||||
// either way the text is present in the document.
|
// either way the text is present in the document.
|
||||||
expect(screen.getByText(/reasoning/)).toBeDefined();
|
expect(screen.getByText(/reasoning/)).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not parse the reasoning markdown while collapsed; parses on expand (#302)", () => {
|
||||||
|
const renderSpy = vi.mocked(renderChatMarkdown);
|
||||||
|
renderSpy.mockClear();
|
||||||
|
renderBlock({ text: "**bold** reasoning", tokens: 5 });
|
||||||
|
// Collapsed is the default. The expensive markdown parse (marked + DOMPurify)
|
||||||
|
// must NOT run for the hidden body — that O(n^2) re-parse on every streamed
|
||||||
|
// delta is exactly what froze the chat (#302). The collapsed body shows the
|
||||||
|
// cheap raw-text fallback instead.
|
||||||
|
expect(renderSpy).not.toHaveBeenCalled();
|
||||||
|
// Expanding parses the current text exactly once (a user-initiated click).
|
||||||
|
fireEvent.click(screen.getByRole("button"));
|
||||||
|
expect(renderSpy).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not parse while expanded and STREAMING; shows chunked plain text", () => {
|
||||||
|
const renderSpy = vi.mocked(renderChatMarkdown);
|
||||||
|
renderSpy.mockClear();
|
||||||
|
renderBlock({
|
||||||
|
text: "первый абзац размышлений\n\nвторой абзац растёт",
|
||||||
|
tokens: 5,
|
||||||
|
streaming: true,
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button"));
|
||||||
|
// Expanded + still streaming: NO markdown parse and NO innerHTML swaps per
|
||||||
|
// delta — the body is chunked plain text (only the tail chunk updates).
|
||||||
|
// This is the O(n²) hole #302 left open (Safari whole-tab freeze).
|
||||||
|
expect(renderSpy).not.toHaveBeenCalled();
|
||||||
|
// Both paragraph chunks' raw text is present in the body.
|
||||||
|
expect(screen.getByText(/первый абзац размышлений/)).toBeDefined();
|
||||||
|
expect(screen.getByText(/второй абзац растёт/)).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses exactly once when streaming flips to done while expanded", () => {
|
||||||
|
const renderSpy = vi.mocked(renderChatMarkdown);
|
||||||
|
renderSpy.mockClear();
|
||||||
|
const { rerender } = renderBlock({
|
||||||
|
text: "**bold** reasoning",
|
||||||
|
tokens: 5,
|
||||||
|
streaming: true,
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button"));
|
||||||
|
expect(renderSpy).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// Finalization: the part's state flips streaming→done, the parent
|
||||||
|
// re-renders the row (the flip changes the message signature), and the
|
||||||
|
// block does its ONE markdown parse of the now-stable text.
|
||||||
|
rerender(
|
||||||
|
<MantineProvider>
|
||||||
|
<ReasoningBlock text="**bold** reasoning" tokens={5} streaming={false} />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
expect(renderSpy).toHaveBeenCalledTimes(1);
|
||||||
|
// The parsed html branch rendered (the mock wraps the input in <p>…</p>).
|
||||||
|
expect(screen.getByText(/reasoning/)).toBeDefined();
|
||||||
|
|
||||||
|
// Further re-renders with unchanged props do not re-parse.
|
||||||
|
rerender(
|
||||||
|
<MantineProvider>
|
||||||
|
<ReasoningBlock text="**bold** reasoning" tokens={5} streaming={false} />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
expect(renderSpy).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
import { estimateTokens } from "@/features/ai-chat/utils/count-stream-tokens.ts";
|
import { estimateTokens } from "@/features/ai-chat/utils/count-stream-tokens.ts";
|
||||||
import { collapseBlankLines } from "@/features/ai-chat/utils/collapse-blank-lines.ts";
|
import { collapseBlankLines } from "@/features/ai-chat/utils/collapse-blank-lines.ts";
|
||||||
import { renderChatMarkdown } from "@/features/ai-chat/utils/markdown.ts";
|
import { renderChatMarkdown } from "@/features/ai-chat/utils/markdown.ts";
|
||||||
|
import { StreamingPlainText } from "@/features/ai-chat/components/streaming-plain-text.tsx";
|
||||||
import classes from "@/features/ai-chat/components/ai-chat.module.css";
|
import classes from "@/features/ai-chat/components/ai-chat.module.css";
|
||||||
|
|
||||||
interface ReasoningBlockProps {
|
interface ReasoningBlockProps {
|
||||||
@@ -15,6 +16,10 @@ interface ReasoningBlockProps {
|
|||||||
* step/turn has finished. When absent (or 0) the count is estimated from the
|
* step/turn has finished. When absent (or 0) the count is estimated from the
|
||||||
* text length so it ticks live as the reasoning streams in. */
|
* text length so it ticks live as the reasoning streams in. */
|
||||||
tokens?: number;
|
tokens?: number;
|
||||||
|
/** True while the reasoning part is still streaming (part `state ===
|
||||||
|
* "streaming"`). False means finalized: persisted history or `state ===
|
||||||
|
* "done"`. Gates the markdown parse — see the invariant on the memo below. */
|
||||||
|
streaming?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,22 +32,30 @@ interface ReasoningBlockProps {
|
|||||||
* Providers that don't stream reasoning TEXT still render this block from the
|
* Providers that don't stream reasoning TEXT still render this block from the
|
||||||
* authoritative count alone (header only, empty body) so the cost is visible.
|
* authoritative count alone (header only, empty body) so the cost is visible.
|
||||||
*/
|
*/
|
||||||
function ReasoningBlock({ text, tokens }: ReasoningBlockProps) {
|
function ReasoningBlock({ text, tokens, streaming = false }: ReasoningBlockProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
// Authoritative count wins; otherwise estimate live from the streamed text.
|
// Authoritative count wins; otherwise estimate live from the streamed text.
|
||||||
const count = tokens && tokens > 0 ? tokens : estimateTokens(text);
|
const count = tokens && tokens > 0 ? tokens : estimateTokens(text);
|
||||||
const trimmed = text.trim();
|
const trimmed = text.trim();
|
||||||
// Memoize the markdown render so toggling `open` (or a parent re-render caused
|
// Markdown parse invariant (per throttled ~20Hz stream delta the text GROWS):
|
||||||
// by an unrelated streamed delta) does not re-parse the reasoning text; it
|
// 1. Collapsed -> never parse (#302): the html is only shown inside
|
||||||
// recomputes only when the reasoning text itself changes (while it streams in).
|
// <Collapse in={open}>, so parsing for a hidden body would be an O(n²)
|
||||||
// collapseBlankLines collapses the blank-line gaps the model emits between every
|
// marked + DOMPurify storm.
|
||||||
// list item / paragraph so the reasoning renders compactly (tight lists, joined
|
// 2. Expanded + STREAMING -> no parse and no innerHTML swaps either: the body
|
||||||
// paragraphs) — ONLY here, not in the normal answer.
|
// renders as chunked plain text (StreamingPlainText) with a memoized
|
||||||
|
// stable prefix, so each delta updates only the tail chunk's text node.
|
||||||
|
// This closes the O(n²) hole #302 left open ("expanded while streaming")
|
||||||
|
// that froze the whole tab in Safari when watching the thinking stream.
|
||||||
|
// 3. Finalized + expanded -> exactly one parse: `trimmed` and `streaming`
|
||||||
|
// are stable after the part is done, so this memo runs once per expand.
|
||||||
const html = useMemo(
|
const html = useMemo(
|
||||||
() => (trimmed ? renderChatMarkdown(collapseBlankLines(trimmed), {}) : ""),
|
() =>
|
||||||
[trimmed],
|
open && trimmed && !streaming
|
||||||
|
? renderChatMarkdown(collapseBlankLines(trimmed), {})
|
||||||
|
: "",
|
||||||
|
[open, trimmed, streaming],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -79,12 +92,12 @@ function ReasoningBlock({ text, tokens }: ReasoningBlockProps) {
|
|||||||
dangerouslySetInnerHTML={{ __html: html }}
|
dangerouslySetInnerHTML={{ __html: html }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Text
|
// Still streaming (or markdown yielded nothing): chunked plain text.
|
||||||
className={classes.reasoningText}
|
// The wrapper carries the reasoningText styling; each chunk sets its
|
||||||
style={{ whiteSpace: "pre-wrap" }}
|
// own pre-wrap inline (NOT on this div — see ai-chat.module.css).
|
||||||
>
|
<div className={classes.reasoningText}>
|
||||||
{trimmed}
|
<StreamingPlainText text={trimmed} />
|
||||||
</Text>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Collapse>
|
</Collapse>
|
||||||
)}
|
)}
|
||||||
@@ -92,7 +105,7 @@ function ReasoningBlock({ text, tokens }: ReasoningBlockProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Memoized: re-renders only when `text`/`tokens` change (primitive props, default
|
// Memoized: re-renders only when `text`/`tokens`/`streaming` change (primitive
|
||||||
// shallow compare), so a parent re-render during streaming of OTHER content does
|
// props, default shallow compare), so a parent re-render during streaming of OTHER
|
||||||
// not re-run the markdown parse for an already-finalized reasoning block.
|
// content does not re-run the markdown parse for an already-finalized reasoning block.
|
||||||
export default memo(ReasoningBlock);
|
export default memo(ReasoningBlock);
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { render } from "@testing-library/react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
splitPlainChunks,
|
||||||
|
StreamingPlainText,
|
||||||
|
} from "./streaming-plain-text";
|
||||||
|
|
||||||
|
describe("splitPlainChunks", () => {
|
||||||
|
// THE load-bearing property (see the invariant comment in the module): under
|
||||||
|
// append-only growth, every chunk except the LAST must be byte-identical
|
||||||
|
// between successive calls, so the memoized chunk components never re-render
|
||||||
|
// for the stable prefix and each stream delta touches only the tail chunk.
|
||||||
|
it("keeps all non-last chunks byte-identical across append-only growth", () => {
|
||||||
|
// A simulated reasoning stream covering: appends inside the last paragraph,
|
||||||
|
// appends that ADD new blank lines, growth of a trailing newline run, and a
|
||||||
|
// trailing separator later followed by text.
|
||||||
|
const steps = [
|
||||||
|
"Пер",
|
||||||
|
"Первый абзац",
|
||||||
|
"Первый абзац\n",
|
||||||
|
"Первый абзац\n\n",
|
||||||
|
"Первый абзац\n\n\n",
|
||||||
|
"Первый абзац\n\n\nВторой",
|
||||||
|
"Первый абзац\n\n\nВторой абзац растёт",
|
||||||
|
"Первый абзац\n\n\nВторой абзац растёт\n\nТретий",
|
||||||
|
"Первый абзац\n\n\nВторой абзац растёт\n\nТретий абзац\n\n",
|
||||||
|
"Первый абзац\n\n\nВторой абзац растёт\n\nТретий абзац\n\nЧетвёртый",
|
||||||
|
];
|
||||||
|
let prev: string[] = [];
|
||||||
|
for (const text of steps) {
|
||||||
|
const next = splitPlainChunks(text);
|
||||||
|
// Lossless: chunks always reassemble into the exact input.
|
||||||
|
expect(next.join("")).toBe(text);
|
||||||
|
// Chunk count never shrinks (boundaries never disappear).
|
||||||
|
expect(next.length).toBeGreaterThanOrEqual(prev.length);
|
||||||
|
// Every previously-FINAL chunk (all but prev's last) is unchanged.
|
||||||
|
for (let i = 0; i < prev.length - 1; i++) {
|
||||||
|
expect(next[i]).toBe(prev[i]);
|
||||||
|
}
|
||||||
|
prev = next;
|
||||||
|
}
|
||||||
|
// Guard against a vacuous pass: the final split must be multi-chunk.
|
||||||
|
expect(prev.length).toBeGreaterThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("attaches the blank-line separator run to the preceding chunk", () => {
|
||||||
|
expect(splitPlainChunks("a\n\nb")).toEqual(["a\n\n", "b"]);
|
||||||
|
// A longer run is ONE separator, not several boundaries.
|
||||||
|
expect(splitPlainChunks("a\n\n\n\nb")).toEqual(["a\n\n\n\n", "b"]);
|
||||||
|
expect(splitPlainChunks("a\n\nb\n\n\nc")).toEqual(["a\n\n", "b\n\n\n", "c"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("single newlines are not boundaries", () => {
|
||||||
|
expect(splitPlainChunks("a\nb\nc")).toEqual(["a\nb\nc"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// INTENTIONAL: CRLF blank lines are NOT boundaries (the regex is `\n{2,}`
|
||||||
|
// only). Supporting `(?:\r?\n){2,}` would break the stable-prefix invariant:
|
||||||
|
// a lone trailing `\r` is not a boundary, but a later-appended `\n` would
|
||||||
|
// merge with it into a new separator unit and retroactively create a boundary
|
||||||
|
// INSIDE previously-emitted text, moving old chunk edges. So CRLF input stays
|
||||||
|
// in one (still lossless) chunk — only granularity is coarser; LLM output is
|
||||||
|
// `\n` in practice. See the doc comment on splitPlainChunks.
|
||||||
|
it("keeps CRLF blank lines inside one chunk", () => {
|
||||||
|
expect(splitPlainChunks("a\r\n\r\nb")).toEqual(["a\r\n\r\nb"]);
|
||||||
|
// Mixed input: only pure-`\n` runs split.
|
||||||
|
expect(splitPlainChunks("a\r\n\r\nb\n\nc")).toEqual(["a\r\n\r\nb\n\n", "c"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never emits empty phantom chunks (multi-blank-line / trailing newlines)", () => {
|
||||||
|
expect(splitPlainChunks("")).toEqual([]);
|
||||||
|
// A trailing newline run stays inside the last chunk (it may still grow).
|
||||||
|
expect(splitPlainChunks("a\n")).toEqual(["a\n"]);
|
||||||
|
expect(splitPlainChunks("a\n\n")).toEqual(["a\n\n"]);
|
||||||
|
expect(splitPlainChunks("a\n\nb\n\n")).toEqual(["a\n\n", "b\n\n"]);
|
||||||
|
// Degenerate all-newlines input is a single deterministic chunk.
|
||||||
|
expect(splitPlainChunks("\n\n\n")).toEqual(["\n\n\n"]);
|
||||||
|
for (const text of ["a\n\n\nb\n\n", "x\n\n\n\n\ny\n\nz\n"]) {
|
||||||
|
for (const chunk of splitPlainChunks(text)) {
|
||||||
|
expect(chunk.length).toBeGreaterThan(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("StreamingPlainText", () => {
|
||||||
|
it("renders one block per chunk, stripping trailing separator newlines at display time", () => {
|
||||||
|
const text = "первый абзац\n\nвторой абзац\n\n\nтретий";
|
||||||
|
const { container } = render(<StreamingPlainText text={text} />);
|
||||||
|
const blocks = Array.from(container.querySelectorAll("div"));
|
||||||
|
// One block element per chunk.
|
||||||
|
expect(blocks.length).toBe(splitPlainChunks(text).length);
|
||||||
|
// DISPLAY-ONLY strip: each rendered block drops its chunk's trailing
|
||||||
|
// separator newlines — rendering them inside a pre-wrap block would add an
|
||||||
|
// empty line ON TOP of the block break (a doubled gap). The RAW chunks
|
||||||
|
// keep their separators (losslessness is asserted on splitPlainChunks
|
||||||
|
// above); multi-blank-line runs collapse to one uniform gap, consistent
|
||||||
|
// with collapseBlankLines on the finalized markdown path.
|
||||||
|
expect(blocks.map((b) => b.textContent)).toEqual([
|
||||||
|
"первый абзац",
|
||||||
|
"второй абзац",
|
||||||
|
"третий",
|
||||||
|
]);
|
||||||
|
// The uniform paragraph gap comes from the block margin instead (matches
|
||||||
|
// the `.reasoningText p { margin: 0 0 4px }` rhythm of the markdown path).
|
||||||
|
for (const block of blocks) {
|
||||||
|
expect((block as HTMLElement).style.marginBottom).toBe("4px");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps interior newlines intact — only the trailing run is stripped", () => {
|
||||||
|
const text = "строка один\nстрока два\n\nхвост";
|
||||||
|
const { container } = render(<StreamingPlainText text={text} />);
|
||||||
|
const blocks = Array.from(container.querySelectorAll("div"));
|
||||||
|
expect(blocks.map((b) => b.textContent)).toEqual([
|
||||||
|
"строка один\nстрока два",
|
||||||
|
"хвост",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// SECURITY INVARIANT — the load-bearing property of the streaming path: the
|
||||||
|
// reasoning text is raw, untrusted model output rendered WITHOUT a sanitizer
|
||||||
|
// (no marked/DOMPurify, no innerHTML). PlainChunk emits it as a React text
|
||||||
|
// node, which escapes it, so HTML in the model output is inert. This test
|
||||||
|
// pins that the path is a TEXT sink, not an HTML sink: a future change to
|
||||||
|
// `dangerouslySetInnerHTML` (reintroducing XSS) MUST fail here.
|
||||||
|
//
|
||||||
|
// The existing tests assert via textContent, which strips tags and so cannot
|
||||||
|
// distinguish an escaped literal from injected DOM. This one asserts on the
|
||||||
|
// parsed DOM directly: if the markup were injected as HTML, the <img>/<b>
|
||||||
|
// would become real elements and querySelector would find them.
|
||||||
|
it("renders HTML-like reasoning as an escaped literal, never as injected DOM", () => {
|
||||||
|
const text = "<img src=x onerror=alert(1)>\n\n<b>hi</b>";
|
||||||
|
const { container } = render(<StreamingPlainText text={text} />);
|
||||||
|
// No DOM elements were created from the payload — it was NOT parsed as HTML.
|
||||||
|
expect(container.querySelector("img")).toBeNull();
|
||||||
|
expect(container.querySelector("b")).toBeNull();
|
||||||
|
// The raw markup survived verbatim as text (proving it is escaped, not
|
||||||
|
// interpreted). textContent alone can't prove this, but combined with the
|
||||||
|
// querySelector assertions above it does: the literals are present AND no
|
||||||
|
// elements exist.
|
||||||
|
expect(container.textContent).toContain("<b>hi</b>");
|
||||||
|
expect(container.textContent).toContain("<img src=x onerror=alert(1)>");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import { memo, useMemo } from "react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split plain text into chunks at blank-line (paragraph) boundaries, keeping
|
||||||
|
* each separator run attached to the END of the preceding chunk, so the chunks
|
||||||
|
* always reassemble byte-for-byte into the input.
|
||||||
|
*
|
||||||
|
* A boundary is the end of a maximal `\n{2,}` run that is followed by at least
|
||||||
|
* one more character. A newline run that is a SUFFIX of the text is NOT a
|
||||||
|
* boundary yet: under append-only growth it may still gain more newlines, and
|
||||||
|
* cutting there would move the boundary on the next call.
|
||||||
|
*
|
||||||
|
* CRITICAL INVARIANT (load-bearing for StreamingPlainText's memoization): for
|
||||||
|
* APPEND-ONLY growth of `text`, every chunk except the LAST is byte-identical
|
||||||
|
* between successive calls — previously-emitted boundaries never move. Proof
|
||||||
|
* sketch: appending never modifies existing characters, so (a) an existing
|
||||||
|
* boundary's newline run and its following character are untouched and the
|
||||||
|
* boundary persists at the same offset; (b) no NEW boundary can appear strictly
|
||||||
|
* inside the old text, because a `\n{2,}` run followed by a character entirely
|
||||||
|
* within the old text would already have been a boundary. New boundaries can
|
||||||
|
* only materialize at or after the old text's end, i.e. inside the last chunk.
|
||||||
|
*
|
||||||
|
* CRLF is deliberately NOT a boundary: supporting `(?:\r?\n){2,}` would BREAK
|
||||||
|
* the invariant above — a lone trailing `\r` is not a boundary, but a later-
|
||||||
|
* appended `\n` would merge with it into a new separator unit and retroactively
|
||||||
|
* create a boundary INSIDE previously-emitted text, moving old chunk edges.
|
||||||
|
* With `\n`-only runs, appended characters can never extend a run that is
|
||||||
|
* already followed by a non-`\n` character, so old boundaries are immutable.
|
||||||
|
* CRLF blank lines therefore intentionally stay inside one chunk: correctness/
|
||||||
|
* losslessness are unaffected, only chunk granularity for CRLF input (LLM
|
||||||
|
* output is `\n` in practice).
|
||||||
|
*/
|
||||||
|
export function splitPlainChunks(text: string): string[] {
|
||||||
|
const chunks: string[] = [];
|
||||||
|
let start = 0;
|
||||||
|
for (const match of text.matchAll(/\n{2,}/g)) {
|
||||||
|
const end = match.index + match[0].length;
|
||||||
|
// Suffix run: not a stable boundary yet (see the invariant above).
|
||||||
|
if (end >= text.length) break;
|
||||||
|
chunks.push(text.slice(start, end));
|
||||||
|
start = end;
|
||||||
|
}
|
||||||
|
if (start < text.length) chunks.push(text.slice(start));
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One immutable chunk. Memoized on its string prop: during streaming only the
|
||||||
|
* TAIL chunk's text changes (see the splitPlainChunks invariant), so React
|
||||||
|
* skips every stable chunk and the per-delta DOM work is a single text-node
|
||||||
|
* update. `pre-wrap` is set per chunk (like the old raw-text fallback did), NOT
|
||||||
|
* on the surrounding markdown-styled container — see the note in
|
||||||
|
* ai-chat.module.css. Font/size/color are inherited from that container.
|
||||||
|
*
|
||||||
|
* DISPLAY-ONLY newline strip: the raw chunk keeps its trailing `\n{2,}`
|
||||||
|
* separator run attached (the splitPlainChunks invariant, load-bearing for the
|
||||||
|
* memo), but rendering those newlines inside a pre-wrap block would add an
|
||||||
|
* empty line ON TOP of the block break — a doubled gap. So the RENDERED string
|
||||||
|
* drops trailing newlines and the paragraph gap comes from `marginBottom: 4`
|
||||||
|
* instead, matching the `.reasoningText p { margin: 0 0 4px }` rhythm of the
|
||||||
|
* finalized markdown. Multi-blank-line runs thus collapse to one uniform gap,
|
||||||
|
* consistent with `collapseBlankLines` on the markdown path. The last chunk
|
||||||
|
* usually has no trailing newlines (strip is a no-op); its margin is harmless.
|
||||||
|
*/
|
||||||
|
const PlainChunk = memo(function PlainChunk({ text }: { text: string }) {
|
||||||
|
return (
|
||||||
|
<div style={{ whiteSpace: "pre-wrap", marginBottom: 4 }}>
|
||||||
|
{text.replace(/\n+$/, "")}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders still-streaming plain text as a list of paragraph chunks where only
|
||||||
|
* the tail chunk changes per delta. No markdown, no sanitizer, no innerHTML —
|
||||||
|
* this is the cheap streaming-time stand-in for the one-time markdown parse
|
||||||
|
* that happens after the part is finalized (see reasoning-block.tsx).
|
||||||
|
*/
|
||||||
|
export function StreamingPlainText({ text }: { text: string }) {
|
||||||
|
const chunks = useMemo(() => splitPlainChunks(text), [text]);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{chunks.map((chunk, index) => (
|
||||||
|
// Index keys are stable here: chunks are append-only (the invariant),
|
||||||
|
// so an index never gets a different chunk's content mid-stream.
|
||||||
|
<PlainChunk key={index} text={chunk} />
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -27,7 +27,9 @@ export function useOpenAiChatForCurrentPage() {
|
|||||||
// AiChatWindow lives in a pathless parent layout route, so useParams() can't
|
// AiChatWindow lives in a pathless parent layout route, so useParams() can't
|
||||||
// see :pageSlug — match the full path against the authenticated page route.
|
// see :pageSlug — match the full path against the authenticated page route.
|
||||||
const match = useMatch("/s/:spaceSlug/p/:pageSlug");
|
const match = useMatch("/s/:spaceSlug/p/:pageSlug");
|
||||||
const pageId = extractPageSlugId(match?.params?.pageSlug);
|
// A page slugId (10-char nanoid), NOT a uuid; the server resolves it to the
|
||||||
|
// real page uuid (PageRepo.findById accepts slugId or uuid).
|
||||||
|
const slugId = extractPageSlugId(match?.params?.pageSlug);
|
||||||
|
|
||||||
return useCallback(async () => {
|
return useCallback(async () => {
|
||||||
// Re-clicks while the window is already open (incl. minimized) must NOT
|
// Re-clicks while the window is already open (incl. minimized) must NOT
|
||||||
@@ -40,9 +42,9 @@ export function useOpenAiChatForCurrentPage() {
|
|||||||
// connection the first click reads as a hung control until the POST returns.
|
// connection the first click reads as a hung control until the POST returns.
|
||||||
setWindowOpen(true);
|
setWindowOpen(true);
|
||||||
let resolved: string | null = activeChatId; // off-a-page: keep current
|
let resolved: string | null = activeChatId; // off-a-page: keep current
|
||||||
if (pageId) {
|
if (slugId) {
|
||||||
try {
|
try {
|
||||||
resolved = await getBoundChat(pageId); // null => fresh chat
|
resolved = await getBoundChat(slugId); // null => fresh chat
|
||||||
} catch {
|
} catch {
|
||||||
resolved = null; // fail-soft: a fresh chat is always a safe fallback
|
resolved = null; // fail-soft: a fresh chat is always a safe fallback
|
||||||
}
|
}
|
||||||
@@ -58,7 +60,7 @@ export function useOpenAiChatForCurrentPage() {
|
|||||||
}, [
|
}, [
|
||||||
windowOpen,
|
windowOpen,
|
||||||
activeChatId,
|
activeChatId,
|
||||||
pageId,
|
slugId,
|
||||||
setWindowOpen,
|
setWindowOpen,
|
||||||
setActiveChatId,
|
setActiveChatId,
|
||||||
setDraft,
|
setDraft,
|
||||||
|
|||||||
@@ -46,9 +46,11 @@ export async function getAiChatMessages(
|
|||||||
* Resolve the chat bound to a document (the current user's most-recent chat
|
* Resolve the chat bound to a document (the current user's most-recent chat
|
||||||
* created on that page), or null when there is none. Drives auto-open-on-page.
|
* created on that page), or null when there is none. Drives auto-open-on-page.
|
||||||
*/
|
*/
|
||||||
export async function getBoundChat(pageId: string): Promise<string | null> {
|
export async function getBoundChat(slugId: string): Promise<string | null> {
|
||||||
|
// The `pageId` body field accepts a page slugId or a uuid; the server resolves
|
||||||
|
// it to the real page uuid (the wire key stays `pageId` for the DTO).
|
||||||
const req = await api.post<{ chatId: string | null }>("/ai-chat/bound-chat", {
|
const req = await api.post<{ chatId: string | null }>("/ai-chat/bound-chat", {
|
||||||
pageId,
|
pageId: slugId,
|
||||||
});
|
});
|
||||||
return req.data.chatId;
|
return req.data.chatId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import { acceptInvitation } from "@/features/workspace/services/workspace-servic
|
|||||||
import APP_ROUTE, { getPostLoginRedirect } from "@/lib/app-route.ts";
|
import APP_ROUTE, { getPostLoginRedirect } from "@/lib/app-route.ts";
|
||||||
import { RESET } from "jotai/utils";
|
import { RESET } from "jotai/utils";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { clearPersistedTreeCaches } from "@/features/page/tree/atoms/tree-data-atom";
|
||||||
|
|
||||||
export default function useAuth() {
|
export default function useAuth() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -122,6 +123,11 @@ export default function useAuth() {
|
|||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
setCurrentUser(RESET);
|
setCurrentUser(RESET);
|
||||||
|
// Purge the persisted sidebar tree caches (they contain page titles) so the
|
||||||
|
// cached page titles aren't left readable in localStorage on a shared
|
||||||
|
// machine. (Only the tree caches are swept; other localStorage entries
|
||||||
|
// remain.)
|
||||||
|
clearPersistedTreeCaches();
|
||||||
await logout();
|
await logout();
|
||||||
window.location.replace(`${APP_ROUTE.AUTH.LOGIN}?logout=1`);
|
window.location.replace(`${APP_ROUTE.AUTH.LOGIN}?logout=1`);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect, vi } from "vitest";
|
import { describe, it, expect, vi } from "vitest";
|
||||||
import { render, screen } from "@testing-library/react";
|
import { render, screen, fireEvent } from "@testing-library/react";
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { IComment } from "@/features/comment/types/comment.types";
|
import { IComment } from "@/features/comment/types/comment.types";
|
||||||
|
|
||||||
@@ -7,10 +7,15 @@ import { IComment } from "@/features/comment/types/comment.types";
|
|||||||
|
|
||||||
// The comment mutation hooks reach out to react-query/network — stub them so the
|
// The comment mutation hooks reach out to react-query/network — stub them so the
|
||||||
// component renders in isolation. We only assert the AI-badge rendering branch.
|
// component renders in isolation. We only assert the AI-badge rendering branch.
|
||||||
|
const applyMutateAsync = vi.fn();
|
||||||
vi.mock("@/features/comment/queries/comment-query", () => ({
|
vi.mock("@/features/comment/queries/comment-query", () => ({
|
||||||
useDeleteCommentMutation: () => ({ mutateAsync: vi.fn() }),
|
useDeleteCommentMutation: () => ({ mutateAsync: vi.fn() }),
|
||||||
useResolveCommentMutation: () => ({ mutateAsync: vi.fn() }),
|
useResolveCommentMutation: () => ({ mutateAsync: vi.fn() }),
|
||||||
useUpdateCommentMutation: () => ({ mutateAsync: vi.fn() }),
|
useUpdateCommentMutation: () => ({ mutateAsync: vi.fn() }),
|
||||||
|
useApplySuggestionMutation: () => ({
|
||||||
|
mutateAsync: applyMutateAsync,
|
||||||
|
isPending: false,
|
||||||
|
}),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// CommentEditor pulls in the full TipTap editor stack; replace it with a stub.
|
// CommentEditor pulls in the full TipTap editor stack; replace it with a stub.
|
||||||
@@ -19,6 +24,7 @@ vi.mock("@/features/comment/components/comment-editor", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
import CommentListItem from "./comment-list-item";
|
import CommentListItem from "./comment-list-item";
|
||||||
|
import { canShowApply } from "@/features/comment/utils/suggestion";
|
||||||
|
|
||||||
const baseComment = (over?: Partial<IComment>): IComment =>
|
const baseComment = (over?: Partial<IComment>): IComment =>
|
||||||
({
|
({
|
||||||
@@ -32,28 +38,147 @@ const baseComment = (over?: Partial<IComment>): IComment =>
|
|||||||
...over,
|
...over,
|
||||||
}) as IComment;
|
}) as IComment;
|
||||||
|
|
||||||
function renderItem(comment: IComment) {
|
function renderItem(comment: IComment, canEdit = true) {
|
||||||
return render(
|
return render(
|
||||||
<MantineProvider>
|
<MantineProvider>
|
||||||
<CommentListItem comment={comment} pageId="page-1" canComment={true} />
|
<CommentListItem
|
||||||
|
comment={comment}
|
||||||
|
pageId="page-1"
|
||||||
|
canComment={true}
|
||||||
|
canEdit={canEdit}
|
||||||
|
/>
|
||||||
</MantineProvider>,
|
</MantineProvider>,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("CommentListItem — AI badge", () => {
|
describe("CommentListItem — agent avatar stack", () => {
|
||||||
it('renders the AI-agent badge when createdSource === "agent"', () => {
|
it('flips the hierarchy for an agent comment: agent primary, launcher shown once', () => {
|
||||||
renderItem(baseComment({ createdSource: "agent", aiChatId: null }));
|
// Internal-chat shape with DISTINCT names so absence-of-duplication is
|
||||||
expect(screen.getByText("AI-agent")).toBeDefined();
|
// assertable: creator is the human "Alice", the acting agent is "Researcher".
|
||||||
|
renderItem(
|
||||||
|
baseComment({
|
||||||
|
creator: { id: "user-1", name: "Alice", avatarUrl: null } as any,
|
||||||
|
createdSource: "agent",
|
||||||
|
aiChatId: "chat-1",
|
||||||
|
agent: { name: "Researcher", emoji: "🔬", avatarUrl: null },
|
||||||
|
launcher: { name: "Alice", avatarUrl: null },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// The AGENT is the primary label (the flipped hierarchy).
|
||||||
|
expect(screen.getByText("Researcher")).toBeDefined();
|
||||||
|
// The human launcher name shows exactly once — it is no longer duplicated as
|
||||||
|
// a separate creator name (that duplication is the bug this fixes).
|
||||||
|
expect(screen.getAllByText("Alice").length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('external MCP agent comment (no launcher): shows the agent name, no separator', () => {
|
||||||
|
// aiChatId null => external MCP: the agent IS the account, no human behind.
|
||||||
|
renderItem(
|
||||||
|
baseComment({
|
||||||
|
creator: { id: "bot-1", name: "MCP Bot", avatarUrl: null } as any,
|
||||||
|
createdSource: "agent",
|
||||||
|
aiChatId: null,
|
||||||
|
agent: { name: "MCP Bot", avatarUrl: null },
|
||||||
|
launcher: null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(screen.getByText("MCP Bot")).toBeDefined();
|
||||||
|
// No launcher => no dimmed "·" separator in the header.
|
||||||
|
expect(screen.queryByText("·")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does NOT render the stack for a normal user comment (createdSource "user")', () => {
|
||||||
|
const { container } = renderItem(baseComment({ createdSource: "user" }));
|
||||||
|
// No agent glyph (sparkles) is present for a plain human comment.
|
||||||
|
expect(container.querySelector(".tabler-icon-sparkles")).toBeNull();
|
||||||
expect(screen.getByText("Service Bot")).toBeDefined();
|
expect(screen.getByText("Service Bot")).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does NOT render the badge for a normal user comment (createdSource "user")', () => {
|
// The stack's own behaviors (glyph priority, launcher-behind, deep-link click)
|
||||||
renderItem(baseComment({ createdSource: "user" }));
|
// are covered directly in agent-avatar-stack.test.tsx; this integration suite
|
||||||
expect(screen.queryByText("AI-agent")).toBeNull();
|
// only guards the insertion gate (agent → stack, user → no stack).
|
||||||
expect(screen.getByText("Service Bot")).toBeDefined();
|
});
|
||||||
});
|
|
||||||
|
describe("CommentListItem — suggested edit (#315)", () => {
|
||||||
// The non-clickable (null aiChatId) branch is a property of AiAgentBadge itself
|
const suggestion = (over?: Partial<IComment>): IComment =>
|
||||||
// and is covered in ai-agent-badge.test.tsx; this integration suite only needs
|
baseComment({
|
||||||
// the insertion gate (agent → badge, user → no badge) above (#143 review).
|
selection: "old wording here",
|
||||||
|
suggestedText: "new wording here",
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders the было→стало diff and an Apply button when canEdit and not applied/resolved", () => {
|
||||||
|
renderItem(suggestion(), true);
|
||||||
|
// Old text appears both as the selection quote and as the struck diff row.
|
||||||
|
expect(screen.getAllByText("old wording here").length).toBeGreaterThan(0);
|
||||||
|
expect(screen.getByText("new wording here")).toBeDefined();
|
||||||
|
// Apply button is present.
|
||||||
|
expect(screen.getByRole("button", { name: "Apply" })).toBeDefined();
|
||||||
|
// No Applied badge yet.
|
||||||
|
expect(screen.queryByText("Applied")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides the Apply button when canEdit is false", () => {
|
||||||
|
renderItem(suggestion(), false);
|
||||||
|
// Diff still renders...
|
||||||
|
expect(screen.getByText("new wording here")).toBeDefined();
|
||||||
|
// ...but no Apply button.
|
||||||
|
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows an Applied badge (no Apply button) once suggestionAppliedAt is set", () => {
|
||||||
|
renderItem(suggestion({ suggestionAppliedAt: new Date() }), true);
|
||||||
|
expect(screen.getByText("Applied")).toBeDefined();
|
||||||
|
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides the Apply button once the thread is resolved", () => {
|
||||||
|
renderItem(suggestion({ resolvedAt: new Date() }), true);
|
||||||
|
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls the apply mutation when the Apply button is clicked", () => {
|
||||||
|
applyMutateAsync.mockClear();
|
||||||
|
renderItem(suggestion(), true);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||||
|
expect(applyMutateAsync).toHaveBeenCalledWith({
|
||||||
|
commentId: "c-1",
|
||||||
|
pageId: "page-1",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not render the diff block for a reply (child) comment", () => {
|
||||||
|
renderItem(
|
||||||
|
suggestion({ parentCommentId: "c-0" }),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(screen.queryByText("new wording here")).toBeNull();
|
||||||
|
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("canShowApply predicate", () => {
|
||||||
|
const c = (over?: Partial<IComment>): IComment =>
|
||||||
|
({ suggestedText: "x", ...over }) as IComment;
|
||||||
|
|
||||||
|
it("true when suggestion present, editable, not applied/resolved, top-level", () => {
|
||||||
|
expect(canShowApply(c(), true)).toBe(true);
|
||||||
|
});
|
||||||
|
it("false without edit permission", () => {
|
||||||
|
expect(canShowApply(c(), false)).toBe(false);
|
||||||
|
});
|
||||||
|
it("false when no suggestion", () => {
|
||||||
|
expect(canShowApply(c({ suggestedText: null }), true)).toBe(false);
|
||||||
|
});
|
||||||
|
it("false when already applied", () => {
|
||||||
|
expect(canShowApply(c({ suggestionAppliedAt: new Date() }), true)).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it("false when resolved", () => {
|
||||||
|
expect(canShowApply(c({ resolvedAt: new Date() }), true)).toBe(false);
|
||||||
|
});
|
||||||
|
it("false for a reply comment", () => {
|
||||||
|
expect(canShowApply(c({ parentCommentId: "p" }), true)).toBe(false);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Group, Text, Box } from "@mantine/core";
|
import { Group, Text, Box, Badge, Button } from "@mantine/core";
|
||||||
import { AiAgentBadge } from "@/components/ui/ai-agent-badge.tsx";
|
import { AgentAvatarStack } from "@/components/ui/agent-avatar-stack.tsx";
|
||||||
import React, { useEffect, useRef, useState } from "react";
|
import React, { useEffect, useRef, useState } from "react";
|
||||||
import classes from "./comment.module.css";
|
import classes from "./comment.module.css";
|
||||||
import { useAtom, useAtomValue } from "jotai";
|
import { useAtom, useAtomValue } from "jotai";
|
||||||
@@ -11,11 +11,13 @@ import CommentMenu from "@/features/comment/components/comment-menu";
|
|||||||
import ResolveComment from "@/features/comment/components/resolve-comment";
|
import ResolveComment from "@/features/comment/components/resolve-comment";
|
||||||
import { useHover } from "@mantine/hooks";
|
import { useHover } from "@mantine/hooks";
|
||||||
import {
|
import {
|
||||||
|
useApplySuggestionMutation,
|
||||||
useDeleteCommentMutation,
|
useDeleteCommentMutation,
|
||||||
useResolveCommentMutation,
|
useResolveCommentMutation,
|
||||||
useUpdateCommentMutation,
|
useUpdateCommentMutation,
|
||||||
} from "@/features/comment/queries/comment-query";
|
} from "@/features/comment/queries/comment-query";
|
||||||
import { IComment } from "@/features/comment/types/comment.types";
|
import { IComment } from "@/features/comment/types/comment.types";
|
||||||
|
import { canShowApply } from "@/features/comment/utils/suggestion";
|
||||||
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
@@ -24,6 +26,10 @@ interface CommentListItemProps {
|
|||||||
comment: IComment;
|
comment: IComment;
|
||||||
pageId: string;
|
pageId: string;
|
||||||
canComment: boolean;
|
canComment: boolean;
|
||||||
|
// Real page-edit permission (page.permissions.canEdit) — gates the suggestion
|
||||||
|
// "Apply" button. Distinct from `canComment`, which may be looser (viewers
|
||||||
|
// allowed to comment cannot apply edits).
|
||||||
|
canEdit?: boolean;
|
||||||
userSpaceRole?: string;
|
userSpaceRole?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,6 +37,7 @@ function CommentListItem({
|
|||||||
comment,
|
comment,
|
||||||
pageId,
|
pageId,
|
||||||
canComment,
|
canComment,
|
||||||
|
canEdit,
|
||||||
userSpaceRole,
|
userSpaceRole,
|
||||||
}: CommentListItemProps) {
|
}: CommentListItemProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -43,6 +50,7 @@ function CommentListItem({
|
|||||||
const updateCommentMutation = useUpdateCommentMutation();
|
const updateCommentMutation = useUpdateCommentMutation();
|
||||||
const deleteCommentMutation = useDeleteCommentMutation(comment.pageId);
|
const deleteCommentMutation = useDeleteCommentMutation(comment.pageId);
|
||||||
const resolveCommentMutation = useResolveCommentMutation();
|
const resolveCommentMutation = useResolveCommentMutation();
|
||||||
|
const applySuggestionMutation = useApplySuggestionMutation();
|
||||||
const [currentUser] = useAtom(currentUserAtom);
|
const [currentUser] = useAtom(currentUserAtom);
|
||||||
const createdAtAgo = useTimeAgo(comment.createdAt);
|
const createdAtAgo = useTimeAgo(comment.createdAt);
|
||||||
|
|
||||||
@@ -95,6 +103,18 @@ function CommentListItem({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleApplySuggestion() {
|
||||||
|
try {
|
||||||
|
await applySuggestionMutation.mutateAsync({
|
||||||
|
commentId: comment.id,
|
||||||
|
pageId: comment.pageId,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Errors surface via the mutation's onError notification (incl. 409).
|
||||||
|
console.error("Failed to apply suggestion:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function handleCommentClick(comment: IComment) {
|
function handleCommentClick(comment: IComment) {
|
||||||
const el = document.querySelector(
|
const el = document.querySelector(
|
||||||
`.comment-mark[data-comment-id="${comment.id}"]`,
|
`.comment-mark[data-comment-id="${comment.id}"]`,
|
||||||
@@ -119,24 +139,44 @@ function CommentListItem({
|
|||||||
return (
|
return (
|
||||||
<Box ref={ref} pb={6}>
|
<Box ref={ref} pb={6}>
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
|
{comment.createdSource === "agent" && comment.agent ? (
|
||||||
|
<AgentAvatarStack
|
||||||
|
agent={comment.agent}
|
||||||
|
launcher={comment.launcher}
|
||||||
|
aiChatId={comment.aiChatId}
|
||||||
|
showName={false}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
<CustomAvatar
|
<CustomAvatar
|
||||||
size="sm"
|
size="sm"
|
||||||
avatarUrl={comment.creator.avatarUrl}
|
avatarUrl={comment.creator.avatarUrl}
|
||||||
name={comment.creator.name}
|
name={comment.creator.name}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<div style={{ flex: 1 }}>
|
<div style={{ flex: 1 }}>
|
||||||
<Group justify="space-between" wrap="nowrap">
|
<Group justify="space-between" wrap="nowrap">
|
||||||
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
||||||
|
{comment.createdSource === "agent" && comment.agent ? (
|
||||||
|
<>
|
||||||
|
<Text size="xs" fw={600} lineClamp={1} lh={1.2}>
|
||||||
|
{comment.agent.name}
|
||||||
|
</Text>
|
||||||
|
{comment.launcher && (
|
||||||
|
<>
|
||||||
|
<Text size="xs" c="dimmed" fw={400} aria-hidden>
|
||||||
|
·
|
||||||
|
</Text>
|
||||||
|
<Text size="xs" c="dimmed" fw={400} lineClamp={1} lh={1.2}>
|
||||||
|
{comment.launcher.name}
|
||||||
|
</Text>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
<Text size="xs" fw={500} lineClamp={1} lh={1.2}>
|
<Text size="xs" fw={500} lineClamp={1} lh={1.2}>
|
||||||
{comment.creator.name}
|
{comment.creator.name}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
{comment.createdSource === "agent" && (
|
|
||||||
<AiAgentBadge
|
|
||||||
authorName={comment.creator?.name}
|
|
||||||
aiChatId={comment.aiChatId}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
@@ -191,6 +231,47 @@ function CommentListItem({
|
|||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Suggested-edit (#315): "было → стало" diff for a top-level comment
|
||||||
|
carrying a suggestion. Old text struck-through/red, new text green. */}
|
||||||
|
{!comment.parentCommentId && comment.suggestedText && (
|
||||||
|
<Box className={classes.suggestionBlock}>
|
||||||
|
{comment.selection && (
|
||||||
|
<Text size="xs" className={classes.suggestionOld}>
|
||||||
|
{comment.selection}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
<Text size="xs" className={classes.suggestionNew}>
|
||||||
|
{comment.suggestedText}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
{comment.suggestionAppliedAt ? (
|
||||||
|
<Badge
|
||||||
|
size="sm"
|
||||||
|
color="green"
|
||||||
|
variant="light"
|
||||||
|
mt={6}
|
||||||
|
aria-label={t("Applied")}
|
||||||
|
>
|
||||||
|
{t("Applied")}
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
canShowApply(comment, canEdit) && (
|
||||||
|
<Button
|
||||||
|
size="compact-xs"
|
||||||
|
variant="light"
|
||||||
|
color="green"
|
||||||
|
mt={6}
|
||||||
|
onClick={handleApplySuggestion}
|
||||||
|
loading={applySuggestionMutation.isPending}
|
||||||
|
disabled={applySuggestionMutation.isPending}
|
||||||
|
>
|
||||||
|
{t("Apply")}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
{!isEditing ? (
|
{!isEditing ? (
|
||||||
<CommentEditor defaultContent={content} editable={false} />
|
<CommentEditor defaultContent={content} editable={false} />
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -49,8 +49,10 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
|||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
||||||
|
|
||||||
|
const canEdit = page?.permissions?.canEdit ?? false;
|
||||||
|
|
||||||
const canComment =
|
const canComment =
|
||||||
(page?.permissions?.canEdit ?? false) ||
|
canEdit ||
|
||||||
(space?.settings?.comments?.allowViewerComments === true);
|
(space?.settings?.comments?.allowViewerComments === true);
|
||||||
|
|
||||||
// Separate active and resolved comments
|
// Separate active and resolved comments
|
||||||
@@ -137,6 +139,7 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
|||||||
comment={comment}
|
comment={comment}
|
||||||
pageId={page?.id}
|
pageId={page?.id}
|
||||||
canComment={canComment}
|
canComment={canComment}
|
||||||
|
canEdit={canEdit}
|
||||||
userSpaceRole={space?.membership?.role}
|
userSpaceRole={space?.membership?.role}
|
||||||
/>
|
/>
|
||||||
<MemoizedChildComments
|
<MemoizedChildComments
|
||||||
@@ -144,6 +147,7 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
|||||||
parentId={comment.id}
|
parentId={comment.id}
|
||||||
pageId={page?.id}
|
pageId={page?.id}
|
||||||
canComment={canComment}
|
canComment={canComment}
|
||||||
|
canEdit={canEdit}
|
||||||
userSpaceRole={space?.membership?.role}
|
userSpaceRole={space?.membership?.role}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -160,7 +164,14 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
|||||||
)}
|
)}
|
||||||
</Paper>
|
</Paper>
|
||||||
),
|
),
|
||||||
[comments, handleAddReply, isLoading, space?.membership?.role, canComment],
|
[
|
||||||
|
comments,
|
||||||
|
handleAddReply,
|
||||||
|
isLoading,
|
||||||
|
space?.membership?.role,
|
||||||
|
canComment,
|
||||||
|
canEdit,
|
||||||
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isCommentsLoading) {
|
if (isCommentsLoading) {
|
||||||
@@ -300,6 +311,7 @@ interface ChildCommentsProps {
|
|||||||
parentId: string;
|
parentId: string;
|
||||||
pageId: string;
|
pageId: string;
|
||||||
canComment: boolean;
|
canComment: boolean;
|
||||||
|
canEdit?: boolean;
|
||||||
userSpaceRole?: string;
|
userSpaceRole?: string;
|
||||||
}
|
}
|
||||||
const ChildComments = ({
|
const ChildComments = ({
|
||||||
@@ -307,6 +319,7 @@ const ChildComments = ({
|
|||||||
parentId,
|
parentId,
|
||||||
pageId,
|
pageId,
|
||||||
canComment,
|
canComment,
|
||||||
|
canEdit,
|
||||||
userSpaceRole,
|
userSpaceRole,
|
||||||
}: ChildCommentsProps) => {
|
}: ChildCommentsProps) => {
|
||||||
const getChildComments = useCallback(
|
const getChildComments = useCallback(
|
||||||
@@ -325,6 +338,7 @@ const ChildComments = ({
|
|||||||
comment={childComment}
|
comment={childComment}
|
||||||
pageId={pageId}
|
pageId={pageId}
|
||||||
canComment={canComment}
|
canComment={canComment}
|
||||||
|
canEdit={canEdit}
|
||||||
userSpaceRole={userSpaceRole}
|
userSpaceRole={userSpaceRole}
|
||||||
/>
|
/>
|
||||||
<MemoizedChildComments
|
<MemoizedChildComments
|
||||||
@@ -332,6 +346,7 @@ const ChildComments = ({
|
|||||||
parentId={childComment.id}
|
parentId={childComment.id}
|
||||||
pageId={pageId}
|
pageId={pageId}
|
||||||
canComment={canComment}
|
canComment={canComment}
|
||||||
|
canEdit={canEdit}
|
||||||
userSpaceRole={userSpaceRole}
|
userSpaceRole={userSpaceRole}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -21,6 +21,38 @@
|
|||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Suggested-edit (#315) "было → стало" diff block. */
|
||||||
|
.suggestionBlock {
|
||||||
|
margin-top: 8px;
|
||||||
|
margin-left: 6px;
|
||||||
|
padding: 6px;
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
|
border: 1px solid var(--mantine-color-default-border);
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-break: break-word;
|
||||||
|
max-width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.suggestionOld {
|
||||||
|
text-decoration: line-through;
|
||||||
|
color: var(--mantine-color-red-7);
|
||||||
|
background: var(--mantine-color-red-light);
|
||||||
|
border-radius: 2px;
|
||||||
|
padding: 1px 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.suggestionNew {
|
||||||
|
color: var(--mantine-color-green-9);
|
||||||
|
background: var(--mantine-color-green-light);
|
||||||
|
border-radius: 2px;
|
||||||
|
padding: 1px 3px;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
.commentEditor {
|
.commentEditor {
|
||||||
|
|
||||||
&[data-editable][data-surface="muted"] .ProseMirror:not(.focused) {
|
&[data-editable][data-surface="muted"] .ProseMirror:not(.focused) {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
InfiniteData,
|
InfiniteData,
|
||||||
} from "@tanstack/react-query";
|
} from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
|
applySuggestion,
|
||||||
createComment,
|
createComment,
|
||||||
deleteComment,
|
deleteComment,
|
||||||
getPageComments,
|
getPageComments,
|
||||||
@@ -176,6 +177,63 @@ function updateCommentInCache(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useApplySuggestionMutation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return useMutation<IComment, any, { commentId: string; pageId: string }>({
|
||||||
|
// No optimistic update: apply can fail with 409 (the commented text drifted),
|
||||||
|
// so we only mutate the cache once the server confirms.
|
||||||
|
mutationFn: ({ commentId }) => applySuggestion(commentId),
|
||||||
|
onSuccess: (data, variables) => {
|
||||||
|
const cache = queryClient.getQueryData(
|
||||||
|
RQ_KEY(variables.pageId),
|
||||||
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
|
|
||||||
|
if (cache) {
|
||||||
|
queryClient.setQueryData(
|
||||||
|
RQ_KEY(variables.pageId),
|
||||||
|
updateCommentInCache(cache, variables.commentId, (comment) => ({
|
||||||
|
...comment,
|
||||||
|
suggestionAppliedAt: data.suggestionAppliedAt,
|
||||||
|
suggestionAppliedById: data.suggestionAppliedById,
|
||||||
|
// The server auto-resolves the thread on apply — carry that through.
|
||||||
|
resolvedAt: data.resolvedAt,
|
||||||
|
resolvedById: data.resolvedById,
|
||||||
|
resolvedBy: data.resolvedBy,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
notifications.show({ message: t("Suggestion applied") });
|
||||||
|
},
|
||||||
|
onError: (err: any) => {
|
||||||
|
// 409 => the commented text changed since the suggestion was made. Surface
|
||||||
|
// a specific message (with the current text) rather than a generic error.
|
||||||
|
const status = err?.response?.status;
|
||||||
|
const currentText = err?.response?.data?.currentText;
|
||||||
|
if (status === 409 && typeof currentText === "string") {
|
||||||
|
const shortText =
|
||||||
|
currentText.length > 80
|
||||||
|
? `${currentText.slice(0, 80)}…`
|
||||||
|
: currentText;
|
||||||
|
notifications.show({
|
||||||
|
title: t(
|
||||||
|
"The commented text changed since this suggestion was made; it was not applied.",
|
||||||
|
),
|
||||||
|
message: shortText,
|
||||||
|
color: "red",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
notifications.show({
|
||||||
|
message: t("Failed to apply suggestion"),
|
||||||
|
color: "red",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function useResolveCommentMutation() {
|
export function useResolveCommentMutation() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|||||||
@@ -18,6 +18,13 @@ export async function resolveComment(data: IResolveComment): Promise<IComment> {
|
|||||||
return req.data;
|
return req.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function applySuggestion(commentId: string): Promise<IComment> {
|
||||||
|
// Mirrors resolveComment: let axios reject on non-2xx so the mutation can read
|
||||||
|
// the 409 body (`{ message, currentText }`) off err.response.data.
|
||||||
|
const req = await api.post("/comments/apply-suggestion", { commentId });
|
||||||
|
return req.data.data ?? req.data;
|
||||||
|
}
|
||||||
|
|
||||||
export async function updateComment(
|
export async function updateComment(
|
||||||
data: Partial<IComment>,
|
data: Partial<IComment>,
|
||||||
): Promise<IComment> {
|
): Promise<IComment> {
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { IUser } from "@/features/user/types/user.types";
|
import { IUser } from "@/features/user/types/user.types";
|
||||||
import { QueryParams } from "@/lib/types.ts";
|
import { QueryParams } from "@/lib/types.ts";
|
||||||
|
import type {
|
||||||
|
AgentInfo,
|
||||||
|
LauncherInfo,
|
||||||
|
} from "@/components/ui/agent-avatar-stack.tsx";
|
||||||
|
|
||||||
export interface IComment {
|
export interface IComment {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -24,6 +28,18 @@ export interface IComment {
|
|||||||
createdSource?: string;
|
createdSource?: string;
|
||||||
aiChatId?: string | null;
|
aiChatId?: string | null;
|
||||||
resolvedSource?: string | null;
|
resolvedSource?: string | null;
|
||||||
|
// Suggested-edit (#315): when an agent proposes a replacement for the
|
||||||
|
// commented `selection`, `suggestedText` holds the "стало" text. Once a user
|
||||||
|
// applies it server-side the backend stamps `suggestionAppliedAt` /
|
||||||
|
// `suggestionAppliedById` and auto-resolves the thread.
|
||||||
|
suggestedText?: string | null;
|
||||||
|
suggestionAppliedAt?: Date | string | null;
|
||||||
|
suggestionAppliedById?: string | null;
|
||||||
|
// Server-normalized "agent avatar stack" provenance (#300), present only when
|
||||||
|
// createdSource === "agent": `agent` is the front identity, `launcher` the
|
||||||
|
// human behind it (null for an external MCP agent).
|
||||||
|
agent?: AgentInfo | null;
|
||||||
|
launcher?: LauncherInfo | null;
|
||||||
yjsSelection?: {
|
yjsSelection?: {
|
||||||
anchor: any;
|
anchor: any;
|
||||||
head: any;
|
head: any;
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { IComment } from "@/features/comment/types/comment.types";
|
||||||
|
|
||||||
|
// Whether the suggested-edit (#315) "Apply" button should be shown for a
|
||||||
|
// comment: it must carry a suggestion, not already be applied or resolved, be a
|
||||||
|
// top-level comment, and the viewer must be able to edit the page.
|
||||||
|
export function canShowApply(comment: IComment, canEdit?: boolean): boolean {
|
||||||
|
return Boolean(
|
||||||
|
canEdit &&
|
||||||
|
comment.suggestedText &&
|
||||||
|
!comment.suggestionAppliedAt &&
|
||||||
|
!comment.resolvedAt &&
|
||||||
|
!comment.parentCommentId,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
|
||||||
|
// A disabled mic must explain WHY it is unavailable rather than silently saying
|
||||||
|
// "Start dictation". This renders MicButton in its idle+disabled state with a
|
||||||
|
// forwarded reason and asserts the accessible label resolves to that reason's
|
||||||
|
// text via the shared resolver (dictation-status.resolveUnavailableLabel).
|
||||||
|
|
||||||
|
// matchMedia (read by MantineProvider) is stubbed globally in vitest.setup.ts.
|
||||||
|
|
||||||
|
// Pass i18n keys through verbatim so we assert the exact resolved string.
|
||||||
|
vi.mock("react-i18next", () => ({
|
||||||
|
useTranslation: () => ({ t: (s: string) => s }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Keep both controllers inert and idle so MicButton renders the idle branch.
|
||||||
|
const idleCtl = {
|
||||||
|
status: "idle" as const,
|
||||||
|
start: vi.fn(async () => {}),
|
||||||
|
stop: vi.fn(),
|
||||||
|
cancel: vi.fn(),
|
||||||
|
audioLevel: 0,
|
||||||
|
errorMessage: null,
|
||||||
|
};
|
||||||
|
vi.mock("@/features/dictation/hooks/use-dictation", () => ({
|
||||||
|
useDictation: () => idleCtl,
|
||||||
|
}));
|
||||||
|
vi.mock("@/features/dictation/hooks/use-streaming-dictation", () => ({
|
||||||
|
useStreamingDictation: () => idleCtl,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { MicButton } from "./mic-button";
|
||||||
|
|
||||||
|
function renderButton(props: React.ComponentProps<typeof MicButton>) {
|
||||||
|
render(
|
||||||
|
<MantineProvider>
|
||||||
|
<MicButton {...props} />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("MicButton — disabled reason label", () => {
|
||||||
|
// jsdom has no MediaRecorder / mediaDevices, so isDictationSupported() would
|
||||||
|
// report "unsupported" and mask the forwarded reason. Stub both so the button
|
||||||
|
// is considered supported and the availability reason is what surfaces.
|
||||||
|
beforeEach(() => {
|
||||||
|
(globalThis as unknown as { MediaRecorder: unknown }).MediaRecorder =
|
||||||
|
class {};
|
||||||
|
Object.defineProperty(navigator, "mediaDevices", {
|
||||||
|
configurable: true,
|
||||||
|
value: { getUserMedia: vi.fn() },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
delete (globalThis as unknown as { MediaRecorder?: unknown }).MediaRecorder;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the cause-specific reason instead of 'Start dictation' when disabled with a reason", () => {
|
||||||
|
renderButton({ onText: () => {}, disabled: true, unavailableReason: "offline" });
|
||||||
|
const expected =
|
||||||
|
"No connection to the collaboration server — dictation unavailable";
|
||||||
|
// The reason surfaces as the accessible label (and the tooltip text).
|
||||||
|
const button = screen.getByRole("button", { name: expected });
|
||||||
|
expect(button).toBeDefined();
|
||||||
|
// It is marked disabled the Mantine way (data-disabled), NOT the native
|
||||||
|
// `disabled` attribute — otherwise pointer-events:none would kill the tooltip.
|
||||||
|
expect(button.getAttribute("data-disabled")).toBe("true");
|
||||||
|
expect(button.hasAttribute("disabled")).toBe(false);
|
||||||
|
// And it no longer silently reads "Start dictation".
|
||||||
|
expect(screen.queryByRole("button", { name: "Start dictation" })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads 'Start dictation' when enabled with no reason", () => {
|
||||||
|
renderButton({ onText: () => {} });
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Start dictation" }),
|
||||||
|
).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not advertise 'Start dictation' when disabled with no reason", () => {
|
||||||
|
// A consumer passing bare `disabled` (e.g. the AI chat's isStreaming) with no
|
||||||
|
// unavailableReason must not get a hoverable mic whose tooltip invites
|
||||||
|
// "Start dictation" on a click that is rejected.
|
||||||
|
renderButton({ onText: () => {}, disabled: true });
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("button", { name: "Start dictation" }),
|
||||||
|
).toBeNull();
|
||||||
|
const button = screen.getByRole("button");
|
||||||
|
expect(button.getAttribute("data-disabled")).toBe("true");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,6 +4,11 @@ import { IconMicrophone, IconPlayerStopFilled } from "@tabler/icons-react";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useDictation } from "@/features/dictation/hooks/use-dictation";
|
import { useDictation } from "@/features/dictation/hooks/use-dictation";
|
||||||
import { useStreamingDictation } from "@/features/dictation/hooks/use-streaming-dictation";
|
import { useStreamingDictation } from "@/features/dictation/hooks/use-streaming-dictation";
|
||||||
|
import {
|
||||||
|
isDictationSupported,
|
||||||
|
resolveUnavailableLabel,
|
||||||
|
type DictationUnavailableReason,
|
||||||
|
} from "@/features/dictation/dictation-status";
|
||||||
import classes from "./mic-button.module.css";
|
import classes from "./mic-button.module.css";
|
||||||
|
|
||||||
interface MicButtonProps {
|
interface MicButtonProps {
|
||||||
@@ -21,6 +26,9 @@ interface MicButtonProps {
|
|||||||
// When true, use the streaming (Silero-VAD) dictation controller, which emits
|
// When true, use the streaming (Silero-VAD) dictation controller, which emits
|
||||||
// text progressively as the user pauses; otherwise use the batch controller.
|
// text progressively as the user pauses; otherwise use the batch controller.
|
||||||
streaming?: boolean;
|
streaming?: boolean;
|
||||||
|
// When the mic is disabled for an availability reason, this is the cause the
|
||||||
|
// idle tooltip explains (e.g. pre-sync "connecting", "offline", "read-only").
|
||||||
|
unavailableReason?: DictationUnavailableReason;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,6 +45,7 @@ export const MicButton: FC<MicButtonProps> = ({
|
|||||||
color,
|
color,
|
||||||
iconSize,
|
iconSize,
|
||||||
streaming = false,
|
streaming = false,
|
||||||
|
unavailableReason,
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
// Call BOTH hooks unconditionally to respect the rules of hooks: which one is
|
// Call BOTH hooks unconditionally to respect the rules of hooks: which one is
|
||||||
@@ -46,7 +55,7 @@ export const MicButton: FC<MicButtonProps> = ({
|
|||||||
const batchCtl = useDictation({ onText, onStart });
|
const batchCtl = useDictation({ onText, onStart });
|
||||||
const streamingCtl = useStreamingDictation({ onText, onStart });
|
const streamingCtl = useStreamingDictation({ onText, onStart });
|
||||||
const ctl = streaming ? streamingCtl : batchCtl;
|
const ctl = streaming ? streamingCtl : batchCtl;
|
||||||
const { status, start, stop, audioLevel } = ctl;
|
const { status, start, stop, audioLevel, errorMessage } = ctl;
|
||||||
const resolvedIconSize = iconSize ?? (size === "lg" ? 18 : 16);
|
const resolvedIconSize = iconSize ?? (size === "lg" ? 18 : 16);
|
||||||
|
|
||||||
if (status === "recording") {
|
if (status === "recording") {
|
||||||
@@ -82,15 +91,28 @@ export const MicButton: FC<MicButtonProps> = ({
|
|||||||
) {
|
) {
|
||||||
// "loading" (streaming hook fetching the VAD model on first use) shows the
|
// "loading" (streaming hook fetching the VAD model on first use) shows the
|
||||||
// same spinner+disabled state so the first click is visibly acknowledged and
|
// same spinner+disabled state so the first click is visibly acknowledged and
|
||||||
// a confusing second click can't fire while the model loads.
|
// a confusing second click can't fire while the model loads. The error case
|
||||||
const label = status === "loading" ? t("Preparing…") : t("Transcribing…");
|
// explains the failure via the hook's resolved errorMessage instead of the
|
||||||
|
// transient "Transcribing…" label.
|
||||||
|
const label =
|
||||||
|
status === "error"
|
||||||
|
? (errorMessage ?? t("Transcription failed"))
|
||||||
|
: status === "loading"
|
||||||
|
? t("Preparing…")
|
||||||
|
: t("Transcribing…");
|
||||||
return (
|
return (
|
||||||
<Tooltip label={label} withArrow>
|
<Tooltip label={label} withArrow>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
size={size}
|
size={size}
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
color={color}
|
color={color}
|
||||||
disabled
|
// Mark disabled the Mantine way (data-disabled/aria-disabled) rather
|
||||||
|
// than the native `disabled` attribute: native `disabled` sets
|
||||||
|
// `pointer-events:none`, which suppresses hover so the Tooltip never
|
||||||
|
// fires. This is a status display with no click action to guard, so
|
||||||
|
// keeping it hoverable simply lets the error reason be read on hover.
|
||||||
|
data-disabled
|
||||||
|
aria-disabled
|
||||||
aria-label={label}
|
aria-label={label}
|
||||||
>
|
>
|
||||||
<Loader size="xs" />
|
<Loader size="xs" />
|
||||||
@@ -99,18 +121,56 @@ export const MicButton: FC<MicButtonProps> = ({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
// Idle branch. A grey/disabled mic must explain WHY it can't record. An
|
||||||
<Tooltip label={t("Start dictation")} withArrow>
|
// unsupported browser/context is detected here; otherwise the parent forwards
|
||||||
|
// a cause-specific reason. We must NOT pass the native `disabled` prop: Mantine
|
||||||
|
// renders `<button disabled>` with `pointer-events:none`, which suppresses
|
||||||
|
// hover so the Tooltip never fires. Instead mark it disabled the Mantine way
|
||||||
|
// (data-disabled/aria-disabled) — keeping it hoverable and in the a11y tree —
|
||||||
|
// and guard the click ourselves.
|
||||||
|
const unsupported = !isDictationSupported();
|
||||||
|
const isDisabled = disabled || unsupported;
|
||||||
|
const reason: DictationUnavailableReason | undefined = unsupported
|
||||||
|
? "unsupported"
|
||||||
|
: unavailableReason;
|
||||||
|
const reasonLabel = reason ? resolveUnavailableLabel(reason, t) : undefined;
|
||||||
|
// A disabled mic with a known reason surfaces it on hover; an enabled mic
|
||||||
|
// invites "Start dictation". But a mic disabled with NO reason (e.g. a
|
||||||
|
// consumer that passes bare `disabled` — the AI chat's isStreaming, with no
|
||||||
|
// unavailableReason) must NOT hover a misleading, actionable "Start dictation"
|
||||||
|
// tooltip on a control that rejects the click. In that case we render the icon
|
||||||
|
// without a Tooltip and give it a neutral accessible label instead.
|
||||||
|
const ariaLabel = reasonLabel ?? (isDisabled ? t("Dictation") : t("Start dictation"));
|
||||||
|
const icon = (
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
size={size}
|
size={size}
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
color={color}
|
color={color}
|
||||||
onClick={() => void start()}
|
onClick={(e) => {
|
||||||
disabled={disabled}
|
if (isDisabled) {
|
||||||
aria-label={t("Start dictation")}
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void start();
|
||||||
|
}}
|
||||||
|
data-disabled={isDisabled || undefined}
|
||||||
|
aria-disabled={isDisabled}
|
||||||
|
aria-label={ariaLabel}
|
||||||
>
|
>
|
||||||
<IconMicrophone size={resolvedIconSize} />
|
<IconMicrophone size={resolvedIconSize} />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
|
);
|
||||||
|
// Suppress the tooltip on a disabled mic that has nothing to explain — hovering
|
||||||
|
// a grey, unclickable mic should not advertise "Start dictation".
|
||||||
|
if (isDisabled && !reasonLabel) {
|
||||||
|
return icon;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Tooltip
|
||||||
|
label={reasonLabel ?? t("Start dictation")}
|
||||||
|
withArrow
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import {
|
||||||
|
classifyGetUserMediaError,
|
||||||
|
classifyTranscriptionError,
|
||||||
|
dictationErrorMessage,
|
||||||
|
resolveUnavailableLabel,
|
||||||
|
isDictationSupported,
|
||||||
|
} from "./dictation-status";
|
||||||
|
|
||||||
|
// Unit tests for the shared dictation-status resolvers (dictation-status.ts).
|
||||||
|
// Both dictation hooks and the mic button form their user-facing strings here,
|
||||||
|
// so a regression in the classification or message mapping would silently swap
|
||||||
|
// what a user reads when the mic is grey or a recording fails. A fake `t`
|
||||||
|
// returns its key verbatim so we assert the exact i18n key each branch selects.
|
||||||
|
const t = (k: string) => k;
|
||||||
|
|
||||||
|
describe("classifyGetUserMediaError", () => {
|
||||||
|
it("maps NotAllowedError / SecurityError to mic-denied", () => {
|
||||||
|
expect(classifyGetUserMediaError({ name: "NotAllowedError" })).toBe(
|
||||||
|
"mic-denied",
|
||||||
|
);
|
||||||
|
expect(classifyGetUserMediaError({ name: "SecurityError" })).toBe(
|
||||||
|
"mic-denied",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps NotFoundError / OverconstrainedError to no-mic", () => {
|
||||||
|
expect(classifyGetUserMediaError({ name: "NotFoundError" })).toBe("no-mic");
|
||||||
|
expect(classifyGetUserMediaError({ name: "OverconstrainedError" })).toBe(
|
||||||
|
"no-mic",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps NotReadableError / AbortError to mic-in-use", () => {
|
||||||
|
expect(classifyGetUserMediaError({ name: "NotReadableError" })).toBe(
|
||||||
|
"mic-in-use",
|
||||||
|
);
|
||||||
|
expect(classifyGetUserMediaError({ name: "AbortError" })).toBe(
|
||||||
|
"mic-in-use",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps anything else / undefined to unknown", () => {
|
||||||
|
expect(classifyGetUserMediaError({ name: "WeirdError" })).toBe("unknown");
|
||||||
|
expect(classifyGetUserMediaError(undefined)).toBe("unknown");
|
||||||
|
expect(classifyGetUserMediaError({})).toBe("unknown");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("classifyTranscriptionError", () => {
|
||||||
|
it("returns the verbatim server message when present", () => {
|
||||||
|
const err = { response: { status: 500, data: { message: "provider 404" } } };
|
||||||
|
expect(classifyTranscriptionError(err)).toEqual({
|
||||||
|
code: "transcription-failed",
|
||||||
|
serverMessage: "provider 404",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps 503 / 403 (no server message) to stt-not-configured", () => {
|
||||||
|
expect(classifyTranscriptionError({ response: { status: 503 } })).toEqual({
|
||||||
|
code: "stt-not-configured",
|
||||||
|
});
|
||||||
|
expect(classifyTranscriptionError({ response: { status: 403 } })).toEqual({
|
||||||
|
code: "stt-not-configured",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to transcription-failed with no server message otherwise", () => {
|
||||||
|
expect(classifyTranscriptionError({ response: { status: 500 } })).toEqual({
|
||||||
|
code: "transcription-failed",
|
||||||
|
});
|
||||||
|
expect(classifyTranscriptionError(new Error("network"))).toEqual({
|
||||||
|
code: "transcription-failed",
|
||||||
|
});
|
||||||
|
// Blank server message is ignored (does not win as verbatim text).
|
||||||
|
expect(
|
||||||
|
classifyTranscriptionError({ response: { data: { message: " " } } }),
|
||||||
|
).toEqual({ code: "transcription-failed" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("dictationErrorMessage", () => {
|
||||||
|
it("maps each code to the expected i18n key", () => {
|
||||||
|
expect(dictationErrorMessage("mic-denied", t)).toBe(
|
||||||
|
"Microphone access denied",
|
||||||
|
);
|
||||||
|
expect(dictationErrorMessage("no-mic", t)).toBe("No microphone found");
|
||||||
|
expect(dictationErrorMessage("mic-in-use", t)).toBe(
|
||||||
|
"Microphone is unavailable or already in use",
|
||||||
|
);
|
||||||
|
expect(dictationErrorMessage("no-media-devices", t)).toBe(
|
||||||
|
"Audio recording is not available in this browser/context",
|
||||||
|
);
|
||||||
|
expect(dictationErrorMessage("stt-not-configured", t)).toBe(
|
||||||
|
"Voice dictation is not configured",
|
||||||
|
);
|
||||||
|
expect(dictationErrorMessage("transcription-failed", t)).toBe(
|
||||||
|
"Transcription failed",
|
||||||
|
);
|
||||||
|
expect(dictationErrorMessage("recorder-failed", t)).toBe(
|
||||||
|
"Could not start recording",
|
||||||
|
);
|
||||||
|
expect(dictationErrorMessage("vad-init-failed", t)).toBe(
|
||||||
|
"Could not start recording",
|
||||||
|
);
|
||||||
|
expect(dictationErrorMessage("unknown", t)).toBe(
|
||||||
|
"Could not start recording",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the server message verbatim for transcription-failed (not the t key)", () => {
|
||||||
|
expect(
|
||||||
|
dictationErrorMessage("transcription-failed", t, {
|
||||||
|
serverMessage: "quota exceeded",
|
||||||
|
}),
|
||||||
|
).toBe("quota exceeded");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("appends the detail to recorder-failed / unknown", () => {
|
||||||
|
expect(
|
||||||
|
dictationErrorMessage("recorder-failed", t, { detail: "boom" }),
|
||||||
|
).toBe("Could not start recording: boom");
|
||||||
|
expect(dictationErrorMessage("unknown", t, { detail: "nope" })).toBe(
|
||||||
|
"Could not start recording: nope",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("appends the detail to transcription-failed when there is no server message", () => {
|
||||||
|
expect(
|
||||||
|
dictationErrorMessage("transcription-failed", t, { detail: "timeout" }),
|
||||||
|
).toBe("Transcription failed: timeout");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveUnavailableLabel", () => {
|
||||||
|
it("maps each reason to its expected i18n key", () => {
|
||||||
|
expect(resolveUnavailableLabel("connecting", t)).toBe(
|
||||||
|
"Dictation becomes available once the page finishes connecting",
|
||||||
|
);
|
||||||
|
expect(resolveUnavailableLabel("offline", t)).toBe(
|
||||||
|
"No connection to the collaboration server — dictation unavailable",
|
||||||
|
);
|
||||||
|
expect(resolveUnavailableLabel("read-only", t)).toBe(
|
||||||
|
"This page is read-only",
|
||||||
|
);
|
||||||
|
expect(resolveUnavailableLabel("unsupported", t)).toBe(
|
||||||
|
"Audio recording is not available in this browser/context",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("isDictationSupported", () => {
|
||||||
|
it("returns a boolean", () => {
|
||||||
|
expect(typeof isDictationSupported()).toBe("boolean");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
// Single source of truth for "why dictation is unavailable" and "why it failed".
|
||||||
|
// Both dictation hooks and the mic button pull their user-facing strings from
|
||||||
|
// the resolvers here so the wording lives in exactly one place.
|
||||||
|
|
||||||
|
export type DictationUnavailableReason =
|
||||||
|
| "connecting"
|
||||||
|
| "offline"
|
||||||
|
| "read-only"
|
||||||
|
| "unsupported";
|
||||||
|
|
||||||
|
export type DictationErrorCode =
|
||||||
|
| "no-media-devices"
|
||||||
|
| "mic-denied"
|
||||||
|
| "no-mic"
|
||||||
|
| "mic-in-use"
|
||||||
|
| "recorder-failed"
|
||||||
|
| "vad-init-failed"
|
||||||
|
| "stt-not-configured"
|
||||||
|
| "transcription-failed"
|
||||||
|
| "unknown";
|
||||||
|
|
||||||
|
// True if this browser/context can record audio.
|
||||||
|
export function isDictationSupported(): boolean {
|
||||||
|
return (
|
||||||
|
typeof MediaRecorder !== "undefined" &&
|
||||||
|
typeof navigator !== "undefined" &&
|
||||||
|
!!navigator.mediaDevices?.getUserMedia
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// getUserMedia / VAD.start rejection -> code, by DOMException .name.
|
||||||
|
export function classifyGetUserMediaError(err: unknown): DictationErrorCode {
|
||||||
|
const name = (err as { name?: string })?.name;
|
||||||
|
if (name === "NotAllowedError" || name === "SecurityError")
|
||||||
|
return "mic-denied";
|
||||||
|
if (name === "NotFoundError" || name === "OverconstrainedError")
|
||||||
|
return "no-mic";
|
||||||
|
if (name === "NotReadableError" || name === "AbortError") return "mic-in-use";
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transcription HTTP failure -> code (+ verbatim server message when present).
|
||||||
|
export function classifyTranscriptionError(err: unknown): {
|
||||||
|
code: DictationErrorCode;
|
||||||
|
serverMessage?: string;
|
||||||
|
} {
|
||||||
|
const resp = (
|
||||||
|
err as { response?: { status?: number; data?: { message?: string } } }
|
||||||
|
)?.response;
|
||||||
|
const serverMessage = resp?.data?.message;
|
||||||
|
if (serverMessage && serverMessage.trim().length > 0)
|
||||||
|
return { code: "transcription-failed", serverMessage };
|
||||||
|
if (resp?.status === 503 || resp?.status === 403)
|
||||||
|
return { code: "stt-not-configured" };
|
||||||
|
return { code: "transcription-failed" };
|
||||||
|
}
|
||||||
|
|
||||||
|
type TFn = (key: string) => string;
|
||||||
|
|
||||||
|
// Code -> user text. The ONE place runtime error strings are formed.
|
||||||
|
// serverMessage (verbatim) wins for transcription-failed; detail is appended
|
||||||
|
// to the generic "could not start"/"transcription failed" strings.
|
||||||
|
export function dictationErrorMessage(
|
||||||
|
code: DictationErrorCode,
|
||||||
|
t: TFn,
|
||||||
|
extra?: { serverMessage?: string; detail?: string },
|
||||||
|
): string {
|
||||||
|
const detail = extra?.detail;
|
||||||
|
switch (code) {
|
||||||
|
case "mic-denied":
|
||||||
|
return t("Microphone access denied");
|
||||||
|
case "no-mic":
|
||||||
|
return t("No microphone found");
|
||||||
|
case "mic-in-use":
|
||||||
|
return t("Microphone is unavailable or already in use");
|
||||||
|
case "no-media-devices":
|
||||||
|
return t("Audio recording is not available in this browser/context");
|
||||||
|
case "stt-not-configured":
|
||||||
|
return t("Voice dictation is not configured");
|
||||||
|
case "transcription-failed":
|
||||||
|
if (extra?.serverMessage && extra.serverMessage.trim().length > 0)
|
||||||
|
return extra.serverMessage;
|
||||||
|
return `${t("Transcription failed")}${detail ? `: ${detail}` : ""}`;
|
||||||
|
case "recorder-failed":
|
||||||
|
case "vad-init-failed":
|
||||||
|
case "unknown":
|
||||||
|
default:
|
||||||
|
return `${t("Could not start recording")}${detail ? `: ${detail}` : ""}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unavailable reason -> tooltip text (the ONE place these strings are formed).
|
||||||
|
export function resolveUnavailableLabel(
|
||||||
|
r: DictationUnavailableReason,
|
||||||
|
t: TFn,
|
||||||
|
): string {
|
||||||
|
switch (r) {
|
||||||
|
case "connecting":
|
||||||
|
return t("Dictation becomes available once the page finishes connecting");
|
||||||
|
case "offline":
|
||||||
|
return t(
|
||||||
|
"No connection to the collaboration server — dictation unavailable",
|
||||||
|
);
|
||||||
|
case "read-only":
|
||||||
|
return t("This page is read-only");
|
||||||
|
case "unsupported":
|
||||||
|
default:
|
||||||
|
return t("Audio recording is not available in this browser/context");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,11 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
|||||||
import { notifications } from "@mantine/notifications";
|
import { notifications } from "@mantine/notifications";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { transcribeAudio } from "@/features/dictation/services/dictation-service";
|
import { transcribeAudio } from "@/features/dictation/services/dictation-service";
|
||||||
|
import {
|
||||||
|
classifyGetUserMediaError,
|
||||||
|
classifyTranscriptionError,
|
||||||
|
dictationErrorMessage,
|
||||||
|
} from "@/features/dictation/dictation-status";
|
||||||
|
|
||||||
// "loading" is set only by the streaming hook while it lazily loads the VAD
|
// "loading" is set only by the streaming hook while it lazily loads the VAD
|
||||||
// model on first use; the batch hook never sets it. It exists so the streaming
|
// model on first use; the batch hook never sets it. It exists so the streaming
|
||||||
@@ -26,6 +31,8 @@ interface UseDictationResult {
|
|||||||
cancel: () => void;
|
cancel: () => void;
|
||||||
// Smoothed live microphone level in the 0..1 range while recording (0 when idle).
|
// Smoothed live microphone level in the 0..1 range while recording (0 when idle).
|
||||||
audioLevel: number;
|
audioLevel: number;
|
||||||
|
// The last error shown to the user (null until one occurs / on a new start).
|
||||||
|
errorMessage: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Candidate container/codec combinations in preference order. The first one the
|
// Candidate container/codec combinations in preference order. The first one the
|
||||||
@@ -67,6 +74,8 @@ export function useDictation(
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [status, setStatus] = useState<DictationStatus>("idle");
|
const [status, setStatus] = useState<DictationStatus>("idle");
|
||||||
const [audioLevel, setAudioLevel] = useState(0);
|
const [audioLevel, setAudioLevel] = useState(0);
|
||||||
|
// Last error message shown to the user; the mic button reads it for its tooltip.
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
// Keep the latest callbacks in a ref so the recorder's onstop closure always
|
// Keep the latest callbacks in a ref so the recorder's onstop closure always
|
||||||
// calls the current handlers without re-creating the recorder.
|
// calls the current handlers without re-creating the recorder.
|
||||||
@@ -194,15 +203,16 @@ export function useDictation(
|
|||||||
if (startingRef.current || recorderRef.current || streamRef.current) return;
|
if (startingRef.current || recorderRef.current || streamRef.current) return;
|
||||||
if (status !== "idle") return;
|
if (status !== "idle") return;
|
||||||
startingRef.current = true;
|
startingRef.current = true;
|
||||||
|
// Clear any stale error from a previous attempt.
|
||||||
|
setErrorMessage(null);
|
||||||
|
|
||||||
if (!navigator.mediaDevices?.getUserMedia) {
|
if (!navigator.mediaDevices?.getUserMedia) {
|
||||||
const reason =
|
const reason =
|
||||||
"navigator.mediaDevices.getUserMedia is unavailable in this context";
|
"navigator.mediaDevices.getUserMedia is unavailable in this context";
|
||||||
console.error("[dictation] " + reason);
|
console.error("[dictation] " + reason);
|
||||||
notifications.show({
|
const message = dictationErrorMessage("no-media-devices", t);
|
||||||
color: "red",
|
notifications.show({ color: "red", message });
|
||||||
message: t("Audio recording is not available in this browser/context"),
|
setErrorMessage(message);
|
||||||
});
|
|
||||||
setStatus("idle");
|
setStatus("idle");
|
||||||
startingRef.current = false;
|
startingRef.current = false;
|
||||||
return;
|
return;
|
||||||
@@ -215,19 +225,16 @@ export function useDictation(
|
|||||||
// Always log the full error for diagnosis (name, message, stack).
|
// Always log the full error for diagnosis (name, message, stack).
|
||||||
console.error("[dictation] getUserMedia failed", err);
|
console.error("[dictation] getUserMedia failed", err);
|
||||||
const name = (err as { name?: string })?.name;
|
const name = (err as { name?: string })?.name;
|
||||||
const detail = (err as { message?: string })?.message ?? String(err);
|
const rawDetail = (err as { message?: string })?.message ?? String(err);
|
||||||
let message: string;
|
// Prefix the DOMException name (e.g. "TypeError: …") so the generic
|
||||||
if (name === "NotAllowedError" || name === "SecurityError") {
|
// resolver branch reproduces this hook's original "Could not start
|
||||||
message = t("Microphone access denied");
|
// recording: <name>: <detail>" text. Each caller owns its own detail; the
|
||||||
} else if (name === "NotFoundError" || name === "OverconstrainedError") {
|
// streaming hook intentionally does not add the name.
|
||||||
message = t("No microphone found");
|
const detail = `${name ? `${name}: ` : ""}${rawDetail}`;
|
||||||
} else if (name === "NotReadableError" || name === "AbortError") {
|
const code = classifyGetUserMediaError(err);
|
||||||
message = t("Microphone is unavailable or already in use");
|
const message = dictationErrorMessage(code, t, { detail });
|
||||||
} else {
|
|
||||||
// Unknown failure: show the real reason instead of a generic string.
|
|
||||||
message = `${t("Could not start recording")}: ${name ? `${name}: ` : ""}${detail}`;
|
|
||||||
}
|
|
||||||
notifications.show({ color: "red", message });
|
notifications.show({ color: "red", message });
|
||||||
|
setErrorMessage(message);
|
||||||
setStatus("idle");
|
setStatus("idle");
|
||||||
startingRef.current = false;
|
startingRef.current = false;
|
||||||
return;
|
return;
|
||||||
@@ -249,10 +256,10 @@ export function useDictation(
|
|||||||
// The stream was acquired but the recorder failed to construct; stop the
|
// The stream was acquired but the recorder failed to construct; stop the
|
||||||
// tracks so the MediaStream does not leak before bailing out.
|
// tracks so the MediaStream does not leak before bailing out.
|
||||||
stopTracks();
|
stopTracks();
|
||||||
notifications.show({
|
const detail = (err as { message?: string })?.message ?? String(err);
|
||||||
color: "red",
|
const message = dictationErrorMessage("recorder-failed", t, { detail });
|
||||||
message: `${t("Could not start recording")}: ${(err as { message?: string })?.message ?? String(err)}`,
|
notifications.show({ color: "red", message });
|
||||||
});
|
setErrorMessage(message);
|
||||||
setStatus("idle");
|
setStatus("idle");
|
||||||
startingRef.current = false;
|
startingRef.current = false;
|
||||||
return;
|
return;
|
||||||
@@ -293,21 +300,14 @@ export function useDictation(
|
|||||||
.catch((err: unknown) => {
|
.catch((err: unknown) => {
|
||||||
// Log the full error for diagnosis (status + body + stack).
|
// Log the full error for diagnosis (status + body + stack).
|
||||||
console.error("[dictation] transcription failed", err);
|
console.error("[dictation] transcription failed", err);
|
||||||
const resp = (
|
const { code, serverMessage } = classifyTranscriptionError(err);
|
||||||
err as { response?: { status?: number; data?: { message?: string } } }
|
const detail = (err as { message?: string })?.message ?? String(err);
|
||||||
)?.response;
|
const message = dictationErrorMessage(code, t, {
|
||||||
const serverMsg = resp?.data?.message;
|
serverMessage,
|
||||||
let message: string;
|
detail,
|
||||||
if (serverMsg && serverMsg.trim().length > 0) {
|
});
|
||||||
// The server already explains the cause (e.g. provider 404, bad
|
|
||||||
// format, STT not configured) — show it verbatim.
|
|
||||||
message = serverMsg;
|
|
||||||
} else if (resp?.status === 503 || resp?.status === 403) {
|
|
||||||
message = t("Voice dictation is not configured");
|
|
||||||
} else {
|
|
||||||
message = `${t("Transcription failed")}: ${(err as { message?: string })?.message ?? String(err)}`;
|
|
||||||
}
|
|
||||||
notifications.show({ color: "red", message });
|
notifications.show({ color: "red", message });
|
||||||
|
setErrorMessage(message);
|
||||||
setStatus("error");
|
setStatus("error");
|
||||||
if (errorTimerRef.current !== null) {
|
if (errorTimerRef.current !== null) {
|
||||||
clearTimeout(errorTimerRef.current);
|
clearTimeout(errorTimerRef.current);
|
||||||
@@ -332,10 +332,10 @@ export function useDictation(
|
|||||||
stopTracks();
|
stopTracks();
|
||||||
recorderRef.current = null;
|
recorderRef.current = null;
|
||||||
startingRef.current = false;
|
startingRef.current = false;
|
||||||
notifications.show({
|
const detail = (err as { message?: string })?.message ?? String(err);
|
||||||
color: "red",
|
const message = dictationErrorMessage("recorder-failed", t, { detail });
|
||||||
message: `${t("Could not start recording")}: ${(err as { message?: string })?.message ?? String(err)}`,
|
notifications.show({ color: "red", message });
|
||||||
});
|
setErrorMessage(message);
|
||||||
setStatus("idle");
|
setStatus("idle");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -405,5 +405,5 @@ export function useDictation(
|
|||||||
};
|
};
|
||||||
}, [clearTimer, stopTracks, stopMeter]);
|
}, [clearTimer, stopTracks, stopMeter]);
|
||||||
|
|
||||||
return { status, start, stop, cancel, audioLevel };
|
return { status, start, stop, cancel, audioLevel, errorMessage };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ import { useTranslation } from "react-i18next";
|
|||||||
import { transcribeAudio } from "@/features/dictation/services/dictation-service";
|
import { transcribeAudio } from "@/features/dictation/services/dictation-service";
|
||||||
import { encodeWavPcm16 } from "@/features/dictation/utils/encode-wav";
|
import { encodeWavPcm16 } from "@/features/dictation/utils/encode-wav";
|
||||||
import type { DictationStatus } from "@/features/dictation/hooks/use-dictation";
|
import type { DictationStatus } from "@/features/dictation/hooks/use-dictation";
|
||||||
|
import {
|
||||||
|
classifyGetUserMediaError,
|
||||||
|
classifyTranscriptionError,
|
||||||
|
dictationErrorMessage,
|
||||||
|
} from "@/features/dictation/dictation-status";
|
||||||
|
|
||||||
// Lazily-imported MicVAD type. The runtime import happens inside start() so the
|
// Lazily-imported MicVAD type. The runtime import happens inside start() so the
|
||||||
// heavy onnxruntime-web / Silero model is code-split out of the main bundle and
|
// heavy onnxruntime-web / Silero model is code-split out of the main bundle and
|
||||||
@@ -27,6 +32,8 @@ interface UseStreamingDictationResult {
|
|||||||
cancel: () => void;
|
cancel: () => void;
|
||||||
// Smoothed live speech level in the 0..1 range while recording (0 when idle).
|
// Smoothed live speech level in the 0..1 range while recording (0 when idle).
|
||||||
audioLevel: number;
|
audioLevel: number;
|
||||||
|
// The last error shown to the user (null until one occurs / on a new start).
|
||||||
|
errorMessage: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sample rate of the audio MicVAD hands to onSpeechEnd (Silero VAD runs at 16k).
|
// Sample rate of the audio MicVAD hands to onSpeechEnd (Silero VAD runs at 16k).
|
||||||
@@ -60,6 +67,8 @@ export function useStreamingDictation(
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [status, setStatus] = useState<DictationStatus>("idle");
|
const [status, setStatus] = useState<DictationStatus>("idle");
|
||||||
const [audioLevel, setAudioLevel] = useState(0);
|
const [audioLevel, setAudioLevel] = useState(0);
|
||||||
|
// Last error message shown to the user; the mic button reads it for its tooltip.
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
// Keep the latest callbacks in a ref so async VAD/HTTP closures always call the
|
// Keep the latest callbacks in a ref so async VAD/HTTP closures always call the
|
||||||
// current handlers without re-creating the VAD.
|
// current handlers without re-creating the VAD.
|
||||||
@@ -158,26 +167,6 @@ export function useStreamingDictation(
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Map a transcription error to a user-facing message, mirroring the batch hook.
|
|
||||||
const transcriptionErrorMessage = useCallback(
|
|
||||||
(err: unknown): string => {
|
|
||||||
const resp = (
|
|
||||||
err as { response?: { status?: number; data?: { message?: string } } }
|
|
||||||
)?.response;
|
|
||||||
const serverMsg = resp?.data?.message;
|
|
||||||
if (serverMsg && serverMsg.trim().length > 0) {
|
|
||||||
// The server already explains the cause (e.g. provider 404, bad format,
|
|
||||||
// STT not configured) — show it verbatim.
|
|
||||||
return serverMsg;
|
|
||||||
}
|
|
||||||
if (resp?.status === 503 || resp?.status === 403) {
|
|
||||||
return t("Voice dictation is not configured");
|
|
||||||
}
|
|
||||||
return `${t("Transcription failed")}: ${(err as { message?: string })?.message ?? String(err)}`;
|
|
||||||
},
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Handle one ended speech segment: encode to WAV and transcribe. Results are
|
// Handle one ended speech segment: encode to WAV and transcribe. Results are
|
||||||
// buffered by seq and flushed in order. A single failed segment does NOT kill
|
// buffered by seq and flushed in order. A single failed segment does NOT kill
|
||||||
// the session: log + one notification, then advance past that seq so later
|
// the session: log + one notification, then advance past that seq so later
|
||||||
@@ -204,10 +193,14 @@ export function useStreamingDictation(
|
|||||||
if (epoch !== epochRef.current) return;
|
if (epoch !== epochRef.current) return;
|
||||||
// Log the full error for diagnosis (status + body + stack).
|
// Log the full error for diagnosis (status + body + stack).
|
||||||
console.error("[dictation] segment transcription failed", err);
|
console.error("[dictation] segment transcription failed", err);
|
||||||
notifications.show({
|
const { code, serverMessage } = classifyTranscriptionError(err);
|
||||||
color: "red",
|
const detail = (err as { message?: string })?.message ?? String(err);
|
||||||
message: transcriptionErrorMessage(err),
|
const message = dictationErrorMessage(code, t, {
|
||||||
|
serverMessage,
|
||||||
|
detail,
|
||||||
});
|
});
|
||||||
|
notifications.show({ color: "red", message });
|
||||||
|
setErrorMessage(message);
|
||||||
// Skip this seq so later segments can still flush in order.
|
// Skip this seq so later segments can still flush in order.
|
||||||
if (nextEmitSeqRef.current === seq) {
|
if (nextEmitSeqRef.current === seq) {
|
||||||
nextEmitSeqRef.current += 1;
|
nextEmitSeqRef.current += 1;
|
||||||
@@ -226,7 +219,7 @@ export function useStreamingDictation(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[drainResults, transcriptionErrorMessage],
|
[drainResults, t],
|
||||||
);
|
);
|
||||||
|
|
||||||
const start = useCallback(async (): Promise<void> => {
|
const start = useCallback(async (): Promise<void> => {
|
||||||
@@ -236,6 +229,8 @@ export function useStreamingDictation(
|
|||||||
if (startingRef.current || vadRef.current || activeRef.current) return;
|
if (startingRef.current || vadRef.current || activeRef.current) return;
|
||||||
if (status !== "idle") return;
|
if (status !== "idle") return;
|
||||||
startingRef.current = true;
|
startingRef.current = true;
|
||||||
|
// Clear any stale error from a previous attempt.
|
||||||
|
setErrorMessage(null);
|
||||||
|
|
||||||
// Notify the caller right when dictation begins (before any async work) so the
|
// Notify the caller right when dictation begins (before any async work) so the
|
||||||
// editor can snapshot the caret position.
|
// editor can snapshot the caret position.
|
||||||
@@ -354,10 +349,9 @@ export function useStreamingDictation(
|
|||||||
// actually runs.)
|
// actually runs.)
|
||||||
console.error("[dictation] VAD init failed", err);
|
console.error("[dictation] VAD init failed", err);
|
||||||
const detail = (err as { message?: string })?.message ?? String(err);
|
const detail = (err as { message?: string })?.message ?? String(err);
|
||||||
notifications.show({
|
const message = dictationErrorMessage("vad-init-failed", t, { detail });
|
||||||
color: "red",
|
notifications.show({ color: "red", message });
|
||||||
message: `${t("Could not start recording")}: ${detail}`,
|
setErrorMessage(message);
|
||||||
});
|
|
||||||
// Defensive: if MicVAD.new partially succeeded before throwing, make sure we
|
// Defensive: if MicVAD.new partially succeeded before throwing, make sure we
|
||||||
// don't leak it.
|
// don't leak it.
|
||||||
destroyVad();
|
destroyVad();
|
||||||
@@ -379,19 +373,11 @@ export function useStreamingDictation(
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Always log the full error for diagnosis (name, message, stack).
|
// Always log the full error for diagnosis (name, message, stack).
|
||||||
console.error("[dictation] VAD.start failed", err);
|
console.error("[dictation] VAD.start failed", err);
|
||||||
const name = (err as { name?: string })?.name;
|
|
||||||
const detail = (err as { message?: string })?.message ?? String(err);
|
const detail = (err as { message?: string })?.message ?? String(err);
|
||||||
let message: string;
|
const code = classifyGetUserMediaError(err);
|
||||||
if (name === "NotAllowedError" || name === "SecurityError") {
|
const message = dictationErrorMessage(code, t, { detail });
|
||||||
message = t("Microphone access denied");
|
|
||||||
} else if (name === "NotFoundError" || name === "OverconstrainedError") {
|
|
||||||
message = t("No microphone found");
|
|
||||||
} else if (name === "NotReadableError" || name === "AbortError") {
|
|
||||||
message = t("Microphone is unavailable or already in use");
|
|
||||||
} else {
|
|
||||||
message = `${t("Could not start recording")}: ${detail}`;
|
|
||||||
}
|
|
||||||
notifications.show({ color: "red", message });
|
notifications.show({ color: "red", message });
|
||||||
|
setErrorMessage(message);
|
||||||
activeRef.current = false;
|
activeRef.current = false;
|
||||||
destroyVad();
|
destroyVad();
|
||||||
setStatus("idle");
|
setStatus("idle");
|
||||||
@@ -470,5 +456,5 @@ export function useStreamingDictation(
|
|||||||
};
|
};
|
||||||
}, [clearTimer, destroyVad]);
|
}, [clearTimer, destroyVad]);
|
||||||
|
|
||||||
return { status, start, stop, cancel, audioLevel };
|
return { status, start, stop, cancel, audioLevel, errorMessage };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { atom } from "jotai";
|
import { atom } from "jotai";
|
||||||
import { Editor } from "@tiptap/core";
|
import { Editor } from "@tiptap/core";
|
||||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||||
|
import type { DictationUnavailableReason } from "@/features/dictation/dictation-status";
|
||||||
|
|
||||||
export const pageEditorAtom = atom<Editor | null>(null);
|
export const pageEditorAtom = atom<Editor | null>(null);
|
||||||
|
|
||||||
@@ -15,3 +16,15 @@ export const showLinkMenuAtom = atom(false);
|
|||||||
// Current page's edit mode — initialized from the user's saved preference on
|
// Current page's edit mode — initialized from the user's saved preference on
|
||||||
// first load, can be toggled locally without persisting to the server.
|
// first load, can be toggled locally without persisting to the server.
|
||||||
export const currentPageEditModeAtom = atom<PageEditMode>(PageEditMode.Edit);
|
export const currentPageEditModeAtom = atom<PageEditMode>(PageEditMode.Edit);
|
||||||
|
|
||||||
|
// Whether the dictation mic can start, and (when it can't) the cause-specific
|
||||||
|
// reason the mic button surfaces as a tooltip. Published by the page editor,
|
||||||
|
// consumed by DictationGroup -> MicButton.
|
||||||
|
export type DictationAvailability = {
|
||||||
|
isEditable: boolean;
|
||||||
|
reason: DictationUnavailableReason | null;
|
||||||
|
};
|
||||||
|
export const dictationAvailabilityAtom = atom<DictationAvailability>({
|
||||||
|
isEditable: false,
|
||||||
|
reason: null,
|
||||||
|
});
|
||||||
|
|||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, act } from "@testing-library/react";
|
||||||
|
import { Provider, createStore } from "jotai";
|
||||||
|
import { dictationAvailabilityAtom } from "@/features/editor/atoms/editor-atoms.ts";
|
||||||
|
|
||||||
|
// Regression test for the byline mic staying stuck disabled (#311 / #309): on a
|
||||||
|
// page the user can edit, the mic must un-grey once the body becomes editable.
|
||||||
|
// #311 first fixed this by reading `editor.isEditable` via `useEditorState`; #309
|
||||||
|
// superseded that with a reactive `dictationAvailabilityAtom` that page-editor
|
||||||
|
// publishes (carrying both the editable gate AND the unavailable reason). The mic
|
||||||
|
// now gates on `dictationAvailability.isEditable`, so a change to that atom must
|
||||||
|
// re-render the group and flip the disabled state (jotai drives the subscription).
|
||||||
|
|
||||||
|
// Detectable stand-in that surfaces the `disabled` prop the component computes.
|
||||||
|
vi.mock("@/features/dictation/components/mic-button", () => ({
|
||||||
|
MicButton: ({ disabled }: any) => (
|
||||||
|
<button data-testid="mic" disabled={disabled} />
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { DictationGroup } from "./dictation-group";
|
||||||
|
|
||||||
|
// Minimal editor stand-in matching the surface DictationGroup uses (handleStart /
|
||||||
|
// handleText). The disabled gate no longer reads this — it reads the atom.
|
||||||
|
function makeFakeEditor() {
|
||||||
|
return {
|
||||||
|
isEditable: false,
|
||||||
|
isDestroyed: false,
|
||||||
|
state: { selection: { from: 0, to: 0 }, doc: { content: { size: 0 } } },
|
||||||
|
} as any;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("DictationGroup editable reactivity (#309 atom / #311)", () => {
|
||||||
|
it("re-enables the mic when dictationAvailability flips isEditable false -> true", () => {
|
||||||
|
const editor = makeFakeEditor();
|
||||||
|
const store = createStore();
|
||||||
|
// Pre-sync: page editor publishes not-editable (with a reason).
|
||||||
|
store.set(dictationAvailabilityAtom, {
|
||||||
|
isEditable: false,
|
||||||
|
reason: "connecting",
|
||||||
|
});
|
||||||
|
|
||||||
|
const { getByTestId } = render(
|
||||||
|
<Provider store={store}>
|
||||||
|
<DictationGroup editor={editor} />
|
||||||
|
</Provider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Not editable yet -> disabled (preserves the #218 pre-sync intent).
|
||||||
|
expect(getByTestId("mic").hasAttribute("disabled")).toBe(true);
|
||||||
|
|
||||||
|
// Collab sync -> page editor republishes editable; the atom change must
|
||||||
|
// re-render the group and enable the mic.
|
||||||
|
act(() => {
|
||||||
|
store.set(dictationAvailabilityAtom, { isEditable: true, reason: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(getByTestId("mic").hasAttribute("disabled")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { FC, useRef } from "react";
|
import { FC, useRef } from "react";
|
||||||
import type { Editor } from "@tiptap/react";
|
import { Editor } from "@tiptap/react";
|
||||||
import { useAtomValue } from "jotai";
|
import { useAtomValue } from "jotai";
|
||||||
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
|
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||||
|
import { dictationAvailabilityAtom } from "@/features/editor/atoms/editor-atoms.ts";
|
||||||
import { MicButton } from "@/features/dictation/components/mic-button";
|
import { MicButton } from "@/features/dictation/components/mic-button";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -16,6 +17,8 @@ export const DictationGroup: FC<Props> = ({ editor, color, iconSize }) => {
|
|||||||
const workspace = useAtomValue(workspaceAtom);
|
const workspace = useAtomValue(workspaceAtom);
|
||||||
const streamingDictation =
|
const streamingDictation =
|
||||||
workspace?.settings?.ai?.dictationStreaming === true;
|
workspace?.settings?.ai?.dictationStreaming === true;
|
||||||
|
// Cause-specific reason the mic is unavailable (published by the page editor).
|
||||||
|
const dictationAvailability = useAtomValue(dictationAvailabilityAtom);
|
||||||
// Caret snapshot taken when dictation starts (where the first segment lands).
|
// Caret snapshot taken when dictation starts (where the first segment lands).
|
||||||
const rangeRef = useRef<{ from: number; to: number } | null>(null);
|
const rangeRef = useRef<{ from: number; to: number } | null>(null);
|
||||||
// Running insertion point: after each inserted segment we remember the caret
|
// Running insertion point: after each inserted segment we remember the caret
|
||||||
@@ -80,7 +83,8 @@ export const DictationGroup: FC<Props> = ({ editor, color, iconSize }) => {
|
|||||||
streaming={streamingDictation}
|
streaming={streamingDictation}
|
||||||
onStart={handleStart}
|
onStart={handleStart}
|
||||||
onText={handleText}
|
onText={handleText}
|
||||||
disabled={!editor.isEditable}
|
disabled={!dictationAvailability.isEditable}
|
||||||
|
unavailableReason={dictationAvailability.reason ?? undefined}
|
||||||
color={color}
|
color={color}
|
||||||
iconSize={iconSize}
|
iconSize={iconSize}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { WebSocketStatus } from "@hocuspocus/provider";
|
import { WebSocketStatus } from "@hocuspocus/provider";
|
||||||
import { isCollabSynced, isBodyEditable } from "./editor-sync-state";
|
import {
|
||||||
|
isCollabSynced,
|
||||||
|
isBodyEditable,
|
||||||
|
computeDictationAvailability,
|
||||||
|
} from "./editor-sync-state";
|
||||||
|
|
||||||
describe("isCollabSynced", () => {
|
describe("isCollabSynced", () => {
|
||||||
it("is true only when Connected and synced", () => {
|
it("is true only when Connected and synced", () => {
|
||||||
@@ -30,3 +34,77 @@ describe("isBodyEditable (pre-sync data-loss gate, #218)", () => {
|
|||||||
expect(isBodyEditable({ ...base, inEditMode: false })).toBe(false);
|
expect(isBodyEditable({ ...base, inEditMode: false })).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("computeDictationAvailability (mic reason precedence, #309)", () => {
|
||||||
|
const base = {
|
||||||
|
editable: true,
|
||||||
|
inEditMode: true,
|
||||||
|
showStatic: false,
|
||||||
|
isDisconnected: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("is available with no reason once synced (showStatic false)", () => {
|
||||||
|
expect(computeDictationAvailability(base)).toEqual({
|
||||||
|
isEditable: true,
|
||||||
|
reason: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports 'offline' during pre-sync while disconnected", () => {
|
||||||
|
expect(
|
||||||
|
computeDictationAvailability({
|
||||||
|
...base,
|
||||||
|
showStatic: true,
|
||||||
|
isDisconnected: true,
|
||||||
|
}),
|
||||||
|
).toEqual({ isEditable: false, reason: "offline" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports 'connecting' during pre-sync while still connecting", () => {
|
||||||
|
expect(
|
||||||
|
computeDictationAvailability({
|
||||||
|
...base,
|
||||||
|
showStatic: true,
|
||||||
|
isDisconnected: false,
|
||||||
|
}),
|
||||||
|
).toEqual({ isEditable: false, reason: "connecting" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports 'read-only' without edit permission", () => {
|
||||||
|
expect(
|
||||||
|
computeDictationAvailability({ ...base, editable: false }),
|
||||||
|
).toEqual({ isEditable: false, reason: "read-only" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports 'read-only' when not in edit mode", () => {
|
||||||
|
expect(
|
||||||
|
computeDictationAvailability({ ...base, inEditMode: false }),
|
||||||
|
).toEqual({ isEditable: false, reason: "read-only" });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Lack of edit permission takes precedence over the pre-sync reason: a
|
||||||
|
// read-only viewer who is ALSO inside the pre-sync window (showStatic) must
|
||||||
|
// still read "read-only", never "offline"/"connecting". This pins the
|
||||||
|
// `opts.editable &&` guard on the pre-sync branch.
|
||||||
|
it("prefers 'read-only' over pre-sync when a read-only viewer is disconnected", () => {
|
||||||
|
expect(
|
||||||
|
computeDictationAvailability({
|
||||||
|
editable: false,
|
||||||
|
inEditMode: true,
|
||||||
|
showStatic: true,
|
||||||
|
isDisconnected: true,
|
||||||
|
}),
|
||||||
|
).toEqual({ isEditable: false, reason: "read-only" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prefers 'read-only' over pre-sync when a read-only viewer is still connecting", () => {
|
||||||
|
expect(
|
||||||
|
computeDictationAvailability({
|
||||||
|
editable: false,
|
||||||
|
inEditMode: true,
|
||||||
|
showStatic: true,
|
||||||
|
isDisconnected: false,
|
||||||
|
}),
|
||||||
|
).toEqual({ isEditable: false, reason: "read-only" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { WebSocketStatus } from "@hocuspocus/provider";
|
import { WebSocketStatus } from "@hocuspocus/provider";
|
||||||
|
import type { DictationUnavailableReason } from "@/features/dictation/dictation-status";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The collab document is usable only once the provider is Connected AND has
|
* The collab document is usable only once the provider is Connected AND has
|
||||||
@@ -30,3 +31,32 @@ export function isBodyEditable(opts: {
|
|||||||
}): boolean {
|
}): boolean {
|
||||||
return opts.editable && opts.inEditMode && !opts.showStatic;
|
return opts.editable && opts.inEditMode && !opts.showStatic;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether dictation can start and, when it can't, the cause-specific reason the
|
||||||
|
* mic button surfaces. Derives editability from `isBodyEditable` (the single,
|
||||||
|
* tested gate) so the published `isEditable` can never diverge from the actual
|
||||||
|
* body-editable state and make the tooltip lie (#309).
|
||||||
|
*
|
||||||
|
* `isDisconnected` is the caller's own boolean (collab connection is in the
|
||||||
|
* Disconnected state), passed in so this module stays free of the collab enum.
|
||||||
|
*/
|
||||||
|
export function computeDictationAvailability(opts: {
|
||||||
|
editable: boolean;
|
||||||
|
inEditMode: boolean;
|
||||||
|
showStatic: boolean;
|
||||||
|
isDisconnected: boolean;
|
||||||
|
}): { isEditable: boolean; reason: DictationUnavailableReason | null } {
|
||||||
|
const isEditable = isBodyEditable({
|
||||||
|
editable: opts.editable,
|
||||||
|
inEditMode: opts.inEditMode,
|
||||||
|
showStatic: opts.showStatic,
|
||||||
|
});
|
||||||
|
if (isEditable) return { isEditable, reason: null };
|
||||||
|
// Permitted to edit and in edit mode but not yet synced (showStatic) → pre-sync.
|
||||||
|
if (opts.editable && opts.inEditMode && opts.showStatic) {
|
||||||
|
return { isEditable, reason: opts.isDisconnected ? "offline" : "connecting" };
|
||||||
|
}
|
||||||
|
// No edit permission or not in edit mode.
|
||||||
|
return { isEditable, reason: "read-only" };
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { Editor } from "@tiptap/core";
|
||||||
|
import { Document } from "@tiptap/extension-document";
|
||||||
|
import { Paragraph } from "@tiptap/extension-paragraph";
|
||||||
|
import { Text } from "@tiptap/extension-text";
|
||||||
|
import { ySyncPluginKey } from "@tiptap/y-tiptap";
|
||||||
|
import {
|
||||||
|
CustomTypography,
|
||||||
|
undoGuardKey,
|
||||||
|
findChangedRange,
|
||||||
|
mapRangeThroughChange,
|
||||||
|
} from "./custom-typography";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PR #296 — the collab-safe typography undo-guard is exercised through the REAL
|
||||||
|
* editor path: a fresh Editor with the CustomTypography extension, transactions
|
||||||
|
* tagged exactly the way prosemirror-history / y-tiptap tag undo & remote
|
||||||
|
* changes (`setMeta("history$", …)` and `setMeta(ySyncPluginKey, …)`), plus
|
||||||
|
* direct unit tests of the two pure diff helpers. No hand-poke of plugin state.
|
||||||
|
*
|
||||||
|
* ARMING MECHANISM (verified against custom-typography.ts source):
|
||||||
|
* - A transaction arms the guard only when it is BOTH history/remote
|
||||||
|
* (`getMeta("history$")` truthy, or `isChangeOrigin` via the ySync meta)
|
||||||
|
* AND an undo/redo (`getMeta("history$")` truthy, or ySync
|
||||||
|
* `isUndoRedoOperation`), AND its whole-doc diff is a REPLACE
|
||||||
|
* (change.oldTo > change.from && change.newTo > change.from).
|
||||||
|
* - `history$` is the stringified PluginKey of the single prosemirror-history
|
||||||
|
* plugin; ProseMirror stores meta under `key.key`, so setMeta("history$")
|
||||||
|
* in a test is read identically by the extension's getMeta("history$").
|
||||||
|
*/
|
||||||
|
|
||||||
|
const singlePara = (text: string) => ({
|
||||||
|
type: "doc",
|
||||||
|
content: [{ type: "paragraph", content: [{ type: "text", text }] }],
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeEditor = (text: string) =>
|
||||||
|
new Editor({
|
||||||
|
extensions: [Document, Paragraph, Text, CustomTypography],
|
||||||
|
content: singlePara(text),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Build a before/after EditorState pair by applying one plain transaction.
|
||||||
|
const mutate = (text: string, apply: (tr: any, schema: any) => void) => {
|
||||||
|
const editor = new Editor({
|
||||||
|
extensions: [Document, Paragraph, Text],
|
||||||
|
content: singlePara(text),
|
||||||
|
});
|
||||||
|
const before = editor.state;
|
||||||
|
const tr = before.tr;
|
||||||
|
apply(tr, before.schema);
|
||||||
|
editor.view.dispatch(tr);
|
||||||
|
const after = editor.state;
|
||||||
|
return { before, after, editor };
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("findChangedRange", () => {
|
||||||
|
it("returns null for identical docs", () => {
|
||||||
|
const editor = new Editor({
|
||||||
|
extensions: [Document, Paragraph, Text],
|
||||||
|
content: singlePara("hello"),
|
||||||
|
});
|
||||||
|
expect(findChangedRange(editor.state, editor.state)).toBeNull();
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the minimal range for a normal middle insertion", () => {
|
||||||
|
// "hello world" (text at 1..12); insert "there " at pos 6.
|
||||||
|
const { before, after, editor } = mutate("hello world", (tr) =>
|
||||||
|
tr.insertText("there ", 6),
|
||||||
|
);
|
||||||
|
expect(findChangedRange(before, after)).toEqual({
|
||||||
|
from: 6,
|
||||||
|
oldTo: 6,
|
||||||
|
newTo: 12,
|
||||||
|
});
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes the INSERTION overlapping-bounds branch (repeated content)", () => {
|
||||||
|
// Insert one more 'a' into "aaaaa" at pos 3. findDiffStart lands at the end
|
||||||
|
// (6) while findDiffEnd reports an end BEFORE it ({a:1,b:2}); both ends must
|
||||||
|
// be pushed forward by the same delta -> a non-degenerate range.
|
||||||
|
const { before, after, editor } = mutate("aaaaa", (tr) =>
|
||||||
|
tr.insertText("a", 3),
|
||||||
|
);
|
||||||
|
const change = findChangedRange(before, after)!;
|
||||||
|
expect(change).toEqual({ from: 6, oldTo: 6, newTo: 7 });
|
||||||
|
// Invariant the guard logic relies on: never degenerate.
|
||||||
|
expect(change.from).toBeLessThanOrEqual(change.oldTo);
|
||||||
|
expect(change.from).toBeLessThanOrEqual(change.newTo);
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes the DELETION overlapping-bounds branch (F2 fix)", () => {
|
||||||
|
// Delete one repeated 'a' from the middle of "aaaaa" ([3,4)). Here
|
||||||
|
// findDiffEnd reports newTo < start, the symmetric case the old one-sided
|
||||||
|
// normalization missed -> it used to yield a degenerate range (newTo < from).
|
||||||
|
const { before, after, editor } = mutate("aaaaa", (tr) => tr.delete(3, 4));
|
||||||
|
const change = findChangedRange(before, after)!;
|
||||||
|
expect(change).toEqual({ from: 5, oldTo: 6, newTo: 5 });
|
||||||
|
// The whole point of F2: from <= newTo (and from <= oldTo) still holds.
|
||||||
|
expect(change.from).toBeLessThanOrEqual(change.newTo);
|
||||||
|
expect(change.from).toBeLessThanOrEqual(change.oldTo);
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes a multi-char repeated deletion (F2 fix)", () => {
|
||||||
|
const { before, after, editor } = mutate("aaaaa", (tr) => tr.delete(2, 4));
|
||||||
|
const change = findChangedRange(before, after)!;
|
||||||
|
expect(change).toEqual({ from: 4, oldTo: 6, newTo: 4 });
|
||||||
|
expect(change.from).toBeLessThanOrEqual(change.newTo);
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("mapRangeThroughChange", () => {
|
||||||
|
const range = { from: 5, to: 10 };
|
||||||
|
|
||||||
|
it("RELEASES on a strict intersection (edit inside the guarded range)", () => {
|
||||||
|
// change straddles the interior of the guard.
|
||||||
|
expect(
|
||||||
|
mapRangeThroughChange(range, { from: 6, oldTo: 8, newTo: 7 }),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT release on a boundary touch at the guard END", () => {
|
||||||
|
// Edit begins exactly at range.to (10): from < to is false -> no intersect.
|
||||||
|
expect(
|
||||||
|
mapRangeThroughChange(range, { from: 10, oldTo: 10, newTo: 12 }),
|
||||||
|
).toEqual(range);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT release on a boundary touch at the guard START", () => {
|
||||||
|
// Edit ends exactly at range.from (5): oldTo > from is false -> no intersect;
|
||||||
|
// it is treated as a change fully before, shifting the guard.
|
||||||
|
expect(
|
||||||
|
mapRangeThroughChange(range, { from: 3, oldTo: 5, newTo: 8 }),
|
||||||
|
).toEqual({ from: 8, to: 13 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("SHIFTS the guard for a change fully before it", () => {
|
||||||
|
// Insert 2 chars entirely before the range (oldTo 3 <= from 5): +2 delta.
|
||||||
|
expect(
|
||||||
|
mapRangeThroughChange(range, { from: 2, oldTo: 3, newTo: 5 }),
|
||||||
|
).toEqual({ from: 7, to: 12 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves the guard untouched for a change fully after it", () => {
|
||||||
|
expect(
|
||||||
|
mapRangeThroughChange(range, { from: 12, oldTo: 14, newTo: 16 }),
|
||||||
|
).toBe(range);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("undo-guard arming (integration)", () => {
|
||||||
|
it("arms {from, to:newTo} on a LOCAL undo-replace (history meta)", () => {
|
||||||
|
// Undo of an em-dash substitution: "a—b" restored to "a--b" — the em-dash
|
||||||
|
// (pos 2..3) is REPLACED by "--", tagged with the history plugin's meta.
|
||||||
|
const editor = makeEditor("a—b");
|
||||||
|
const { state } = editor;
|
||||||
|
const tr = state.tr
|
||||||
|
.replaceWith(2, 3, state.schema.text("--"))
|
||||||
|
.setMeta("history$", { redo: false });
|
||||||
|
editor.view.dispatch(tr);
|
||||||
|
|
||||||
|
expect(editor.state.doc.textContent).toBe("a--b");
|
||||||
|
// from = diff start (2), to = newTo = end of the inserted "--" (4).
|
||||||
|
expect(undoGuardKey.getState(editor.state)).toEqual({ from: 2, to: 4 });
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT arm on a REMOTE change-origin replace (no undo meta)", () => {
|
||||||
|
// Same replace, but tagged only as a y-sync remote change: history/remote
|
||||||
|
// yes, undo/redo NO -> must not arm.
|
||||||
|
const editor = makeEditor("a—b");
|
||||||
|
const { state } = editor;
|
||||||
|
const tr = state.tr
|
||||||
|
.replaceWith(2, 3, state.schema.text("--"))
|
||||||
|
.setMeta(ySyncPluginKey, { isChangeOrigin: true });
|
||||||
|
editor.view.dispatch(tr);
|
||||||
|
|
||||||
|
expect(editor.state.doc.textContent).toBe("a--b");
|
||||||
|
expect(undoGuardKey.getState(editor.state)).toBeNull();
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT arm on an ordinary local edit", () => {
|
||||||
|
const editor = makeEditor("a—b");
|
||||||
|
editor.view.dispatch(
|
||||||
|
editor.state.tr.replaceWith(2, 3, editor.state.schema.text("--")),
|
||||||
|
);
|
||||||
|
expect(undoGuardKey.getState(editor.state)).toBeNull();
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("undo-guard release / shift (integration)", () => {
|
||||||
|
it("RELEASES when a later edit lands inside the guarded region", () => {
|
||||||
|
const editor = makeEditor("a—b");
|
||||||
|
editor.view.dispatch(
|
||||||
|
editor.state.tr
|
||||||
|
.replaceWith(2, 3, editor.state.schema.text("--"))
|
||||||
|
.setMeta("history$", { redo: false }),
|
||||||
|
);
|
||||||
|
const guard = undoGuardKey.getState(editor.state)!;
|
||||||
|
expect(guard).toEqual({ from: 2, to: 4 });
|
||||||
|
|
||||||
|
// Type a character inside the restored region -> guard is dropped.
|
||||||
|
editor.view.dispatch(editor.state.tr.insertText("x", guard.from + 1));
|
||||||
|
expect(undoGuardKey.getState(editor.state)).toBeNull();
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps and SHIFTS the guard when a later edit lands before it", () => {
|
||||||
|
const editor = makeEditor("zz a—b");
|
||||||
|
// "zz a—b": em-dash at pos 5; replace the 'a' at 4..5 with "--" to arm.
|
||||||
|
editor.view.dispatch(
|
||||||
|
editor.state.tr
|
||||||
|
.replaceWith(4, 5, editor.state.schema.text("--"))
|
||||||
|
.setMeta("history$", { redo: false }),
|
||||||
|
);
|
||||||
|
const guard = undoGuardKey.getState(editor.state)!;
|
||||||
|
expect(guard).toEqual({ from: 4, to: 6 });
|
||||||
|
|
||||||
|
// Insert one char at the very start (before the guard) -> guard shifts +1.
|
||||||
|
editor.view.dispatch(editor.state.tr.insertText("Q", 1));
|
||||||
|
expect(undoGuardKey.getState(editor.state)).toEqual({ from: 5, to: 7 });
|
||||||
|
editor.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import { InputRule } from "@tiptap/core";
|
||||||
|
import {
|
||||||
|
Plugin,
|
||||||
|
PluginKey,
|
||||||
|
type EditorState,
|
||||||
|
type Transaction,
|
||||||
|
} from "@tiptap/pm/state";
|
||||||
|
import { Typography } from "@tiptap/extension-typography";
|
||||||
|
import { isChangeOrigin } from "@tiptap/extension-collaboration";
|
||||||
|
import { ySyncPluginKey } from "@tiptap/y-tiptap";
|
||||||
|
|
||||||
|
// Region restored by the latest undo — while it is intact, typography
|
||||||
|
// input rules overlapping it must not fire again.
|
||||||
|
interface UndoGuardRange {
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exported for tests: the plugin key lets a test read the armed guard state,
|
||||||
|
// and the two pure helpers below are unit-tested directly.
|
||||||
|
export const undoGuardKey = new PluginKey<UndoGuardRange | null>(
|
||||||
|
"typographyUndoGuard",
|
||||||
|
);
|
||||||
|
|
||||||
|
// prosemirror-history does not export its plugin key, so template-editor
|
||||||
|
// undo/redo is detected via the stable stringified key. Only one
|
||||||
|
// PluginKey("history") exists in the dependency tree, so "history$" is stable.
|
||||||
|
const HISTORY_META = "history$";
|
||||||
|
|
||||||
|
const isUndoRedoTransaction = (tr: Transaction): boolean => {
|
||||||
|
if (tr.getMeta(HISTORY_META)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Read yjs undo/redo meta via the real ySyncPluginKey object (imported, not
|
||||||
|
// a fragile stringified key), which y-tiptap sets on Y.UndoManager changes.
|
||||||
|
const ySyncMeta = tr.getMeta(ySyncPluginKey) as
|
||||||
|
| { isUndoRedoOperation?: boolean }
|
||||||
|
| undefined;
|
||||||
|
return !!ySyncMeta?.isUndoRedoOperation;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface DocChange {
|
||||||
|
from: number;
|
||||||
|
oldTo: number;
|
||||||
|
newTo: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute the minimal changed region between two docs. yjs undo/redo (and any
|
||||||
|
// remote change) arrives as a whole-document replace step, so the transaction
|
||||||
|
// step maps are useless — diff the docs to recover the real minimal change.
|
||||||
|
// Returns null when the docs are identical.
|
||||||
|
export const findChangedRange = (
|
||||||
|
oldState: EditorState,
|
||||||
|
newState: EditorState,
|
||||||
|
): DocChange | null => {
|
||||||
|
const start = oldState.doc.content.findDiffStart(newState.doc.content);
|
||||||
|
const end = oldState.doc.content.findDiffEnd(newState.doc.content);
|
||||||
|
if (start == null || end == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
let { a: oldTo, b: newTo } = end;
|
||||||
|
// findDiffEnd can report an end BEFORE the diff start when the changed text
|
||||||
|
// abuts repeated content (insertion -> oldTo<start, deletion -> newTo<start).
|
||||||
|
// Push both ends forward by the same delta so the range stays non-degenerate
|
||||||
|
// (from <= oldTo and from <= newTo), matching ProseMirror's own diff bounds.
|
||||||
|
const minTo = Math.min(oldTo, newTo);
|
||||||
|
if (minTo < start) {
|
||||||
|
const delta = start - minTo;
|
||||||
|
oldTo += delta;
|
||||||
|
newTo += delta;
|
||||||
|
}
|
||||||
|
return { from: start, oldTo, newTo };
|
||||||
|
};
|
||||||
|
|
||||||
|
// Map an armed guard range across a single document change described by a diff.
|
||||||
|
// Returns null when the change touches the guarded text itself (the restored
|
||||||
|
// substitution was edited, so the guard must be released).
|
||||||
|
export const mapRangeThroughChange = (
|
||||||
|
range: UndoGuardRange,
|
||||||
|
change: DocChange,
|
||||||
|
): UndoGuardRange | null => {
|
||||||
|
// Strict intersection: an edit exactly at a guard boundary (e.g. the user
|
||||||
|
// typing the suppressed space right after the restored text, or deleting it)
|
||||||
|
// must NOT drop the guard.
|
||||||
|
if (change.from < range.to && change.oldTo > range.from) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// Change fully before the guard: shift the guard by the length delta.
|
||||||
|
if (change.oldTo <= range.from) {
|
||||||
|
const delta = change.newTo - change.oldTo;
|
||||||
|
return { from: range.from + delta, to: range.to + delta };
|
||||||
|
}
|
||||||
|
// Change fully after the guard: positions are unaffected.
|
||||||
|
return range;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Detect history/remote transactions that may arrive as a whole-document
|
||||||
|
// replace step: prosemirror-history undo/redo, or any yjs remote-origin change
|
||||||
|
// (isChangeOrigin is the canonical predicate already used across the app).
|
||||||
|
const isHistoryOrRemoteTransaction = (tr: Transaction): boolean =>
|
||||||
|
!!tr.getMeta(HISTORY_META) || isChangeOrigin(tr);
|
||||||
|
|
||||||
|
export const CustomTypography = Typography.extend({
|
||||||
|
addProseMirrorPlugins() {
|
||||||
|
return [
|
||||||
|
...(this.parent?.() ?? []),
|
||||||
|
new Plugin({
|
||||||
|
key: undoGuardKey,
|
||||||
|
state: {
|
||||||
|
init: () => null,
|
||||||
|
apply(tr, prev, oldState, newState): UndoGuardRange | null {
|
||||||
|
if (tr.docChanged && isHistoryOrRemoteTransaction(tr)) {
|
||||||
|
const change = findChangedRange(oldState, newState);
|
||||||
|
if (change == null) {
|
||||||
|
// Attribute-only or otherwise content-neutral change: keep the
|
||||||
|
// guard.
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
// Arm the guard only when the LOCAL user's undo/redo REPLACED text
|
||||||
|
// (deleted + inserted) — the signature of reverting an input-rule
|
||||||
|
// substitution. Pure insertions/deletions and remote peer edits
|
||||||
|
// must not arm it.
|
||||||
|
if (
|
||||||
|
isUndoRedoTransaction(tr) &&
|
||||||
|
change.oldTo > change.from &&
|
||||||
|
change.newTo > change.from
|
||||||
|
) {
|
||||||
|
return { from: change.from, to: change.newTo };
|
||||||
|
}
|
||||||
|
// Non-arming history/remote change: map the existing guard through
|
||||||
|
// the real diff instead of the (whole-document) step map.
|
||||||
|
if (!prev) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return mapRangeThroughChange(prev, change);
|
||||||
|
}
|
||||||
|
if (!prev) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!tr.docChanged) {
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
// Ordinary local edit: minimal step maps are accurate and cheap.
|
||||||
|
let range: UndoGuardRange | null = prev;
|
||||||
|
for (const stepMap of tr.mapping.maps) {
|
||||||
|
const { from: rangeFrom, to: rangeTo } = range;
|
||||||
|
let touched = false;
|
||||||
|
stepMap.forEach((fromA, toA) => {
|
||||||
|
if (fromA < rangeTo && toA > rangeFrom) {
|
||||||
|
touched = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (touched) {
|
||||||
|
range = null;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
range = {
|
||||||
|
from: stepMap.map(rangeFrom, 1),
|
||||||
|
to: stepMap.map(rangeTo, -1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return range && range.to > range.from ? range : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
|
||||||
|
addInputRules() {
|
||||||
|
// Wrap every typography rule: skip it when its match overlaps the text
|
||||||
|
// just restored by undo, so an undone substitution is not re-applied.
|
||||||
|
return (this.parent?.() ?? []).map(
|
||||||
|
(rule) =>
|
||||||
|
new InputRule({
|
||||||
|
find: rule.find,
|
||||||
|
undoable: rule.undoable,
|
||||||
|
handler: (props) => {
|
||||||
|
const guard = undoGuardKey.getState(props.state);
|
||||||
|
if (
|
||||||
|
guard &&
|
||||||
|
props.range.from < guard.to &&
|
||||||
|
props.range.to > guard.from
|
||||||
|
) {
|
||||||
|
// Returning null skips this rule and lets the typed character
|
||||||
|
// be inserted as plain text.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return rule.handler(props);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -6,7 +6,7 @@ import { TaskList, TaskItem } from "@tiptap/extension-list";
|
|||||||
import { Placeholder, CharacterCount, UndoRedo } from "@tiptap/extensions";
|
import { Placeholder, CharacterCount, UndoRedo } from "@tiptap/extensions";
|
||||||
import { Superscript } from "@tiptap/extension-superscript";
|
import { Superscript } from "@tiptap/extension-superscript";
|
||||||
import SubScript from "@tiptap/extension-subscript";
|
import SubScript from "@tiptap/extension-subscript";
|
||||||
import { Typography } from "@tiptap/extension-typography";
|
import { CustomTypography } from "./custom-typography";
|
||||||
import { TextStyle } from "@tiptap/extension-text-style";
|
import { TextStyle } from "@tiptap/extension-text-style";
|
||||||
import { Color } from "@tiptap/extension-color";
|
import { Color } from "@tiptap/extension-color";
|
||||||
import { Youtube } from "@tiptap/extension-youtube";
|
import { Youtube } from "@tiptap/extension-youtube";
|
||||||
@@ -245,7 +245,9 @@ export const mainExtensions = [
|
|||||||
return ReactMarkViewRenderer(SpoilerView);
|
return ReactMarkViewRenderer(SpoilerView);
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
Typography,
|
// Typography with an undo guard: does not re-apply a substitution the user
|
||||||
|
// just undid (e.g. Ctrl+Z on "1/2" -> "½" followed by another space).
|
||||||
|
CustomTypography,
|
||||||
TrailingNode,
|
TrailingNode,
|
||||||
GlobalDragHandle.configure({
|
GlobalDragHandle.configure({
|
||||||
customNodes: ["transclusionSource", "transclusionReference", "pageEmbed"],
|
customNodes: ["transclusionSource", "transclusionReference", "pageEmbed"],
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { normalizeTableColumnWidths } from "./markdown-clipboard";
|
import { htmlToMarkdown } from "@docmost/editor-ext";
|
||||||
|
import {
|
||||||
|
normalizeTableColumnWidths,
|
||||||
|
classifyClipboardSelection,
|
||||||
|
} from "./markdown-clipboard";
|
||||||
|
|
||||||
// normalizeTableColumnWidths mutates a DOM subtree (jsdom provides document).
|
// normalizeTableColumnWidths mutates a DOM subtree (jsdom provides document).
|
||||||
function root(html: string): HTMLElement {
|
function root(html: string): HTMLElement {
|
||||||
@@ -124,3 +128,171 @@ describe("normalizeTableColumnWidths", () => {
|
|||||||
).toEqual([null, null]);
|
).toEqual([null, null]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("classifyClipboardSelection", () => {
|
||||||
|
it("serializes a list of 2+ items as markdown", () => {
|
||||||
|
expect(
|
||||||
|
classifyClipboardSelection([{ name: "bulletList", childCount: 2 }]),
|
||||||
|
).toEqual({ asMarkdown: true, wrapBareRows: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves a single-item list as plain text", () => {
|
||||||
|
expect(
|
||||||
|
classifyClipboardSelection([{ name: "bulletList", childCount: 1 }]),
|
||||||
|
).toEqual({ asMarkdown: false, wrapBareRows: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serializes a whole table without wrapping bare rows", () => {
|
||||||
|
expect(
|
||||||
|
classifyClipboardSelection([{ name: "table", childCount: 3 }]),
|
||||||
|
).toEqual({ asMarkdown: true, wrapBareRows: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serializes a partial cell selection (bare rows) and flags wrapping", () => {
|
||||||
|
expect(
|
||||||
|
classifyClipboardSelection([
|
||||||
|
{ name: "tableRow", childCount: 2 },
|
||||||
|
{ name: "tableRow", childCount: 2 },
|
||||||
|
]),
|
||||||
|
).toEqual({ asMarkdown: true, wrapBareRows: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves plain paragraphs as plain text", () => {
|
||||||
|
expect(
|
||||||
|
classifyClipboardSelection([{ name: "paragraph", childCount: 1 }]),
|
||||||
|
).toEqual({ asMarkdown: false, wrapBareRows: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not wrap when rows are mixed with other block types", () => {
|
||||||
|
expect(
|
||||||
|
classifyClipboardSelection([
|
||||||
|
{ name: "tableRow", childCount: 2 },
|
||||||
|
{ name: "paragraph", childCount: 1 },
|
||||||
|
]),
|
||||||
|
).toEqual({ asMarkdown: false, wrapBareRows: false });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Output-level tests for the table clipboard regression: copying a table must
|
||||||
|
// yield a real GFM pipe table, NOT one-value-per-line concatenated cells.
|
||||||
|
// These exercise the actual markdown produced by htmlToMarkdown (the same
|
||||||
|
// serializer step the clipboardTextSerializer runs), so they pin the OUTPUT
|
||||||
|
// shape that the classifier-flag tests above do not cover.
|
||||||
|
describe("table clipboard markdown output (htmlToMarkdown)", () => {
|
||||||
|
// Trim each line and drop blanks so structural assertions are whitespace-robust.
|
||||||
|
function lines(md: string): string[] {
|
||||||
|
return md
|
||||||
|
.split("\n")
|
||||||
|
.map((l) => l.trim())
|
||||||
|
.filter((l) => l.length > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A GFM separator row like "| --- | --- |" (any number of columns), tolerant
|
||||||
|
// of the padding turndown emits.
|
||||||
|
function isSeparatorRow(line: string): boolean {
|
||||||
|
const compact = line.replace(/\s+/g, "");
|
||||||
|
return /^\|(?:-{3,}\|)+$/.test(compact);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split a pipe-delimited row into trimmed cell values.
|
||||||
|
function cells(line: string): string[] {
|
||||||
|
return line
|
||||||
|
.replace(/^\|/, "")
|
||||||
|
.replace(/\|$/, "")
|
||||||
|
.split("|")
|
||||||
|
.map((c) => c.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
it("serializes a header-less partial cell selection (bare rows) as a valid GFM pipe table", () => {
|
||||||
|
// Mirror the serializer's `wrapBareRows` branch exactly: bare <tr> nodes are
|
||||||
|
// wrapped in <table><tbody> and htmlToMarkdown(div.innerHTML) is called.
|
||||||
|
// See markdown-clipboard.ts clipboardTextSerializer:
|
||||||
|
// const table = document.createElement("table");
|
||||||
|
// const tbody = document.createElement("tbody");
|
||||||
|
// tbody.appendChild(fragment); table.appendChild(tbody);
|
||||||
|
// div.appendChild(table);
|
||||||
|
// return htmlToMarkdown(div.innerHTML);
|
||||||
|
const div = document.createElement("div");
|
||||||
|
const table = document.createElement("table");
|
||||||
|
const tbody = document.createElement("tbody");
|
||||||
|
for (const [c1, c2] of [
|
||||||
|
["a", "b"],
|
||||||
|
["c", "d"],
|
||||||
|
]) {
|
||||||
|
const tr = document.createElement("tr");
|
||||||
|
const td1 = document.createElement("td");
|
||||||
|
td1.textContent = c1;
|
||||||
|
const td2 = document.createElement("td");
|
||||||
|
td2.textContent = c2;
|
||||||
|
tr.appendChild(td1);
|
||||||
|
tr.appendChild(td2);
|
||||||
|
tbody.appendChild(tr);
|
||||||
|
}
|
||||||
|
table.appendChild(tbody);
|
||||||
|
div.appendChild(table);
|
||||||
|
|
||||||
|
const md = htmlToMarkdown(div.innerHTML);
|
||||||
|
const ls = lines(md);
|
||||||
|
|
||||||
|
// Valid GFM: a header/data separator row is present (an empty header is
|
||||||
|
// synthesized by the GFM turndown plugin for a header-less table — fine).
|
||||||
|
expect(ls.some(isSeparatorRow)).toBe(true);
|
||||||
|
// NOT the old broken "one value per line" shape: every line is pipe-delimited
|
||||||
|
// and no line is a bare cell value on its own.
|
||||||
|
expect(ls.every((l) => l.includes("|"))).toBe(true);
|
||||||
|
expect(md).not.toMatch(/^\s*(a|b|c|d)\s*$/m);
|
||||||
|
// The cell values land in real pipe-delimited data rows.
|
||||||
|
const dataRows = ls.filter((l) => !isSeparatorRow(l)).map(cells);
|
||||||
|
expect(dataRows).toContainEqual(["a", "b"]);
|
||||||
|
expect(dataRows).toContainEqual(["c", "d"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serializes a whole table with a header row as a proper GFM table (headline regression)", () => {
|
||||||
|
// Mirror the serializer's non-wrap branch: the full <table> node is appended
|
||||||
|
// directly (div.appendChild(fragment)) and htmlToMarkdown(div.innerHTML) runs.
|
||||||
|
const div = document.createElement("div");
|
||||||
|
const table = document.createElement("table");
|
||||||
|
|
||||||
|
const thead = document.createElement("thead");
|
||||||
|
const headerRow = document.createElement("tr");
|
||||||
|
for (const h of ["Name", "Age"]) {
|
||||||
|
const th = document.createElement("th");
|
||||||
|
th.textContent = h;
|
||||||
|
headerRow.appendChild(th);
|
||||||
|
}
|
||||||
|
thead.appendChild(headerRow);
|
||||||
|
table.appendChild(thead);
|
||||||
|
|
||||||
|
const tbody = document.createElement("tbody");
|
||||||
|
for (const [name, age] of [
|
||||||
|
["Alice", "30"],
|
||||||
|
["Bob", "25"],
|
||||||
|
]) {
|
||||||
|
const tr = document.createElement("tr");
|
||||||
|
const td1 = document.createElement("td");
|
||||||
|
td1.textContent = name;
|
||||||
|
const td2 = document.createElement("td");
|
||||||
|
td2.textContent = age;
|
||||||
|
tr.appendChild(td1);
|
||||||
|
tr.appendChild(td2);
|
||||||
|
tbody.appendChild(tr);
|
||||||
|
}
|
||||||
|
table.appendChild(tbody);
|
||||||
|
div.appendChild(table);
|
||||||
|
|
||||||
|
const md = htmlToMarkdown(div.innerHTML);
|
||||||
|
const ls = lines(md);
|
||||||
|
|
||||||
|
// Proper GFM structure: separator row + all rows pipe-delimited.
|
||||||
|
expect(ls.some(isSeparatorRow)).toBe(true);
|
||||||
|
expect(ls.every((l) => l.includes("|"))).toBe(true);
|
||||||
|
|
||||||
|
const rows = ls.filter((l) => !isSeparatorRow(l)).map(cells);
|
||||||
|
// Header row comes first, followed by both data rows.
|
||||||
|
expect(rows[0]).toEqual(["Name", "Age"]);
|
||||||
|
expect(rows).toContainEqual(["Alice", "30"]);
|
||||||
|
expect(rows).toContainEqual(["Bob", "25"]);
|
||||||
|
// Headline regression: the table is NOT concatenated one-value-per-line.
|
||||||
|
expect(md).not.toMatch(/^\s*(Name|Age|Alice|Bob|30|25)\s*$/m);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -27,24 +27,36 @@ export const MarkdownClipboard = Extension.create({
|
|||||||
key: new PluginKey("markdownClipboard"),
|
key: new PluginKey("markdownClipboard"),
|
||||||
props: {
|
props: {
|
||||||
clipboardTextSerializer: (slice) => {
|
clipboardTextSerializer: (slice) => {
|
||||||
const listTypes = ["bulletList", "orderedList", "taskList"];
|
const topLevelNodes: { name: string; childCount: number }[] = [];
|
||||||
let topLevelCount = 0;
|
|
||||||
let hasList = false;
|
|
||||||
slice.content.forEach((node) => {
|
slice.content.forEach((node) => {
|
||||||
if (listTypes.includes(node.type.name)) {
|
topLevelNodes.push({
|
||||||
hasList = true;
|
name: node.type.name,
|
||||||
topLevelCount += node.childCount;
|
childCount: node.childCount,
|
||||||
} else {
|
});
|
||||||
topLevelCount++;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!hasList || topLevelCount < 2) return null;
|
const { asMarkdown, wrapBareRows } =
|
||||||
|
classifyClipboardSelection(topLevelNodes);
|
||||||
|
if (!asMarkdown) return null;
|
||||||
|
|
||||||
const div = document.createElement("div");
|
const div = document.createElement("div");
|
||||||
const serializer = DOMSerializer.fromSchema(this.editor.schema);
|
const serializer = DOMSerializer.fromSchema(this.editor.schema);
|
||||||
const fragment = serializer.serializeFragment(slice.content);
|
const fragment = serializer.serializeFragment(slice.content);
|
||||||
|
|
||||||
|
if (wrapBareRows) {
|
||||||
|
// A partial table cell-selection serializes to bare <tr> nodes
|
||||||
|
// (prosemirror-tables returns the whole `table` node only when the
|
||||||
|
// entire table is selected). Bare <tr> would be foster-parented
|
||||||
|
// away by the HTML parser inside htmlToMarkdown, so wrap them in
|
||||||
|
// <table><tbody> first for the GFM turndown rule to detect them.
|
||||||
|
const table = document.createElement("table");
|
||||||
|
const tbody = document.createElement("tbody");
|
||||||
|
tbody.appendChild(fragment);
|
||||||
|
table.appendChild(tbody);
|
||||||
|
div.appendChild(table);
|
||||||
|
} else {
|
||||||
div.appendChild(fragment);
|
div.appendChild(fragment);
|
||||||
|
}
|
||||||
return htmlToMarkdown(div.innerHTML);
|
return htmlToMarkdown(div.innerHTML);
|
||||||
},
|
},
|
||||||
handlePaste: (view, event, slice) => {
|
handlePaste: (view, event, slice) => {
|
||||||
@@ -153,6 +165,55 @@ export const MarkdownClipboard = Extension.create({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decide whether a copied slice's plain-text clipboard payload should be
|
||||||
|
* serialized as Markdown (instead of ProseMirror's default text serializer,
|
||||||
|
* which joins block leaves with newlines — the "one value per line" bug for
|
||||||
|
* tables).
|
||||||
|
*
|
||||||
|
* Serialize as Markdown for structured content:
|
||||||
|
* - lists with 2+ total items (a single copied bullet stays literal text);
|
||||||
|
* - a whole table (top-level `table` node);
|
||||||
|
* - a partial table cell-selection, which prosemirror-tables copies as bare
|
||||||
|
* `tableRow` nodes (only a full-table selection yields a `table` node).
|
||||||
|
*
|
||||||
|
* `wrapBareRows` flags the bare-rows case so the caller wraps the serialized
|
||||||
|
* <tr> nodes in <table><tbody> before the HTML->Markdown step. Plain paragraphs
|
||||||
|
* return asMarkdown=false so a simple text copy stays literal, and internal
|
||||||
|
* copy/paste keeps using the richer text/html clipboard payload.
|
||||||
|
*/
|
||||||
|
export function classifyClipboardSelection(
|
||||||
|
nodes: { name: string; childCount: number }[],
|
||||||
|
): { asMarkdown: boolean; wrapBareRows: boolean } {
|
||||||
|
const listTypes = ["bulletList", "orderedList", "taskList"];
|
||||||
|
let topLevelCount = 0;
|
||||||
|
let hasList = false;
|
||||||
|
let hasTable = false;
|
||||||
|
let tableRowCount = 0;
|
||||||
|
let nonRowCount = 0;
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (listTypes.includes(node.name)) {
|
||||||
|
hasList = true;
|
||||||
|
topLevelCount += node.childCount;
|
||||||
|
nonRowCount++;
|
||||||
|
} else {
|
||||||
|
if (node.name === "table") hasTable = true;
|
||||||
|
if (node.name === "tableRow") tableRowCount++;
|
||||||
|
else nonRowCount++;
|
||||||
|
topLevelCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bare tableRow nodes at the top level only occur for a partial cell
|
||||||
|
// selection; a slice never mixes bare rows with other block types, so
|
||||||
|
// "every top-level node is a row" is a safe signal to wrap-and-serialize.
|
||||||
|
const wrapBareRows = tableRowCount > 0 && nonRowCount === 0;
|
||||||
|
const asMarkdown =
|
||||||
|
(hasList && topLevelCount >= 2) || hasTable || wrapBareRows;
|
||||||
|
return { asMarkdown, wrapBareRows };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reorder/dedup the footnotes of a SELF-CONTAINED pasted markdown block to the
|
* Reorder/dedup the footnotes of a SELF-CONTAINED pasted markdown block to the
|
||||||
* canonical invariant (the live footnoteSyncPlugin never reorders an existing
|
* canonical invariant (the live footnoteSyncPlugin never reorders an existing
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
import { renderHook, act } from "@testing-library/react";
|
import { renderHook, act } from "@testing-library/react";
|
||||||
import { useScrollPosition } from "./use-scroll-position";
|
import { useScrollPosition, hasSavedReadingPosition } from "./use-scroll-position";
|
||||||
|
|
||||||
const KEY_PREFIX = "gitmost:scroll-position:";
|
const KEY_PREFIX = "gitmost:scroll-position:";
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ describe("useScrollPosition", () => {
|
|||||||
expect(window.scrollTo).toHaveBeenCalledWith({ top: 500, behavior: "auto" });
|
expect(window.scrollTo).toHaveBeenCalledWith({ top: 500, behavior: "auto" });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("(a3) restores at most once per mount even if called again", () => {
|
it("(a3) is idempotent: re-asserting the same target does not scroll again", () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
window.sessionStorage.setItem(`${KEY_PREFIX}once`, "500");
|
window.sessionStorage.setItem(`${KEY_PREFIX}once`, "500");
|
||||||
setScrollHeight(2000); // tall enough to restore synchronously
|
setScrollHeight(2000); // tall enough to restore synchronously
|
||||||
@@ -111,8 +111,12 @@ describe("useScrollPosition", () => {
|
|||||||
});
|
});
|
||||||
expect(window.scrollTo).toHaveBeenCalledTimes(1);
|
expect(window.scrollTo).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// Simulate the browser now being at the restored position.
|
||||||
|
setScrollY(500);
|
||||||
|
|
||||||
// A second call (e.g. the wiring effect re-running on [showStatic, editor,
|
// A second call (e.g. the wiring effect re-running on [showStatic, editor,
|
||||||
// restoreScrollPosition]) must NOT scroll again and yank the reader.
|
// restoreScrollPosition]) must NOT scroll again: the redundancy guard sees
|
||||||
|
// the window is already at the target and does nothing.
|
||||||
act(() => {
|
act(() => {
|
||||||
result.current.restoreScrollPosition();
|
result.current.restoreScrollPosition();
|
||||||
});
|
});
|
||||||
@@ -162,6 +166,84 @@ describe("useScrollPosition", () => {
|
|||||||
expect(window.scrollTo).not.toHaveBeenCalled();
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("(g) does not restore if the reader scrolled (wheel) before restore fires", () => {
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}g1`, "500");
|
||||||
|
setScrollHeight(2000); // tall enough to restore synchronously
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useScrollPosition("g1"));
|
||||||
|
|
||||||
|
// The reader shows scroll intent before restore is triggered.
|
||||||
|
act(() => {
|
||||||
|
window.dispatchEvent(new Event("wheel"));
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
result.current.restoreScrollPosition();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("(h) aborts an in-flight restore poll when the reader scrolls", () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}h1`, "500");
|
||||||
|
setInnerHeight(800);
|
||||||
|
setScrollHeight(100); // maxScroll = -700: target not reachable yet, so it polls.
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useScrollPosition("h1"));
|
||||||
|
act(() => {
|
||||||
|
result.current.restoreScrollPosition();
|
||||||
|
});
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled(); // still polling
|
||||||
|
|
||||||
|
// The reader takes over mid-poll: this cancels the in-flight poll.
|
||||||
|
act(() => {
|
||||||
|
window.dispatchEvent(new Event("wheel"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Content of the page grows tall enough and time passes: the cancelled poll
|
||||||
|
// must NOT resurrect and yank the reader.
|
||||||
|
setScrollHeight(2000);
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(5000);
|
||||||
|
});
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("(i) a non-scroll keydown does NOT abort restore", () => {
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}i1`, "500");
|
||||||
|
setScrollHeight(2000); // tall enough to restore synchronously
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useScrollPosition("i1"));
|
||||||
|
|
||||||
|
// A non-scroll key (e.g. typing, a shortcut) must NOT count as scroll intent.
|
||||||
|
act(() => {
|
||||||
|
window.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
result.current.restoreScrollPosition();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Restore still happens: the innocuous keypress did not disable it.
|
||||||
|
expect(window.scrollTo).toHaveBeenCalledWith({ top: 500, behavior: "auto" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("(j) a scroll keydown (Space) DOES abort restore", () => {
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}j1`, "500");
|
||||||
|
setScrollHeight(2000); // tall enough to restore synchronously
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useScrollPosition("j1"));
|
||||||
|
|
||||||
|
// Space scrolls the page: this is real scroll intent and must abort restore.
|
||||||
|
act(() => {
|
||||||
|
window.dispatchEvent(new KeyboardEvent("keydown", { key: " " }));
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
result.current.restoreScrollPosition();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it("(c) does nothing when nothing is saved or the saved value is <= 0", () => {
|
it("(c) does nothing when nothing is saved or the saved value is <= 0", () => {
|
||||||
// Nothing saved.
|
// Nothing saved.
|
||||||
const a = renderHook(() => useScrollPosition("nope"));
|
const a = renderHook(() => useScrollPosition("nope"));
|
||||||
@@ -221,6 +303,55 @@ describe("useScrollPosition", () => {
|
|||||||
expect(window.scrollTo).toHaveBeenCalledWith({ top: 200, behavior: "auto" });
|
expect(window.scrollTo).toHaveBeenCalledWith({ top: 200, behavior: "auto" });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("(k) shares ONE timeout budget across re-triggers (does not restart the clock)", () => {
|
||||||
|
// The static->live editor swap re-invokes restore. The shared budget
|
||||||
|
// (restoreStartRef) must measure the MAX_RESTORE_WAIT_MS (5000) deadline
|
||||||
|
// from the FIRST trigger, not restart it on every re-trigger. This pins
|
||||||
|
// the `if (restoreStartRef.current === null)` guard: a mutant that resets
|
||||||
|
// `restoreStartRef.current = Date.now()` on every trigger would push the
|
||||||
|
// deadline out to t=8000 (3000 + 5000) and fail the t=5000 assertion below.
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.setSystemTime(0);
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}k1`, "5000");
|
||||||
|
setInnerHeight(800);
|
||||||
|
setScrollHeight(1000); // maxScroll = 200, never reaches 5000 -> it polls.
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useScrollPosition("k1"));
|
||||||
|
|
||||||
|
// First trigger at t=0: starts the shared budget and begins polling.
|
||||||
|
act(() => {
|
||||||
|
result.current.restoreScrollPosition();
|
||||||
|
});
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// Advance to t=3000 (still polling: content short, not yet timed out).
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(3000);
|
||||||
|
});
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// Second trigger at t=3000 (the swap re-assert). Under the real code the
|
||||||
|
// budget is shared, so `start` stays 0; under the reset-mutant it becomes 3000.
|
||||||
|
act(() => {
|
||||||
|
result.current.restoreScrollPosition();
|
||||||
|
});
|
||||||
|
|
||||||
|
// At t=4900 the FIRST budget has not yet elapsed (4900 - 0 < 5000): no clamp.
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(1900);
|
||||||
|
});
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// At t=5000 the shared budget (measured from t=0) times out and clamps to the
|
||||||
|
// furthest reachable position (maxScroll = 200). The reset-mutant, measuring
|
||||||
|
// from t=3000, would still be waiting (5000 - 3000 = 2000 < 5000) and would
|
||||||
|
// NOT have scrolled here -> this assertion fails against that mutant.
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(100);
|
||||||
|
});
|
||||||
|
expect(window.scrollTo).toHaveBeenCalledWith({ top: 200, behavior: "auto" });
|
||||||
|
});
|
||||||
|
|
||||||
it("(e) never throws when storage access throws", () => {
|
it("(e) never throws when storage access throws", () => {
|
||||||
const err = new Error("storage denied");
|
const err = new Error("storage denied");
|
||||||
vi.spyOn(window.sessionStorage, "getItem").mockImplementation(() => {
|
vi.spyOn(window.sessionStorage, "getItem").mockImplementation(() => {
|
||||||
@@ -241,3 +372,23 @@ describe("useScrollPosition", () => {
|
|||||||
}).not.toThrow();
|
}).not.toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("hasSavedReadingPosition", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false when nothing is saved for the page", () => {
|
||||||
|
expect(hasSavedReadingPosition("none")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false when the saved value is 0 (page stays at the top)", () => {
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}zero`, "0");
|
||||||
|
expect(hasSavedReadingPosition("zero")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns true when a positive position is saved", () => {
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}deep`, "500");
|
||||||
|
expect(hasSavedReadingPosition("deep")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useCallback, useEffect, useRef } from "react";
|
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||||
|
import type { Editor } from "@tiptap/react";
|
||||||
|
|
||||||
// Throttle interval for persisting the scroll position while the user reads.
|
// Throttle interval for persisting the scroll position while the user reads.
|
||||||
const SAVE_THROTTLE_MS = 250;
|
const SAVE_THROTTLE_MS = 250;
|
||||||
@@ -13,6 +14,18 @@ const RESTORE_POLL_MS = 100;
|
|||||||
// "remember where I was reading" feature (self-limiting, no cross-tab leak).
|
// "remember where I was reading" feature (self-limiting, no cross-tab leak).
|
||||||
const STORAGE_PREFIX = "gitmost:scroll-position:";
|
const STORAGE_PREFIX = "gitmost:scroll-position:";
|
||||||
|
|
||||||
|
// Keys that scroll the window. Only these count as scroll intent for keydown;
|
||||||
|
// other keys (shortcuts, modifiers, typing) must NOT disable scroll restore.
|
||||||
|
const SCROLL_KEYS = new Set([
|
||||||
|
"ArrowUp",
|
||||||
|
"ArrowDown",
|
||||||
|
"PageUp",
|
||||||
|
"PageDown",
|
||||||
|
"Home",
|
||||||
|
"End",
|
||||||
|
" ", // Space (and Shift+Space) scroll the page
|
||||||
|
]);
|
||||||
|
|
||||||
function storageKey(pageId: string): string {
|
function storageKey(pageId: string): string {
|
||||||
return `${STORAGE_PREFIX}${pageId}`;
|
return `${STORAGE_PREFIX}${pageId}`;
|
||||||
}
|
}
|
||||||
@@ -44,36 +57,56 @@ function writeStorage(pageId: string, scrollY: number): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a positive reading position is saved for this page — i.e. the page
|
||||||
|
* will be scrolled away from the top on load. Used by the title editor to avoid
|
||||||
|
* auto-focusing (and thus placing the caret in) the now-off-screen title.
|
||||||
|
* Returns false when nothing is saved or storage is unavailable.
|
||||||
|
*/
|
||||||
|
export function hasSavedReadingPosition(pageId: string): boolean {
|
||||||
|
const y = readStorage(pageId);
|
||||||
|
return typeof y === "number" && y > 0;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persists and restores the window scroll position per page so a reader keeps
|
* Persists and restores the window scroll position per page so a reader keeps
|
||||||
* their place across a reload (F5) or reopening the document.
|
* their place across a reload (F5) or reopening the document.
|
||||||
*
|
*
|
||||||
* Returns `restoreScrollPosition`, which the page editor calls once the live
|
* Returns `restoreScrollPosition`, which the page editor calls from two triggers
|
||||||
* (non-static) content is laid out. The two scroll mechanisms are mutually
|
* (early, while the static/cached content is laid out, and again after the
|
||||||
* exclusive: if the URL has a `#hash` anchor, the existing anchor-scroll logic
|
* static->live editor swap); it is idempotent, so re-asserting the same target is
|
||||||
* wins and restore is a no-op.
|
* a no-op. The two scroll mechanisms are mutually exclusive: if the URL has a
|
||||||
|
* `#hash` anchor, the existing anchor-scroll logic wins and restore is a no-op.
|
||||||
*/
|
*/
|
||||||
export function useScrollPosition(pageId: string): {
|
export function useScrollPosition(pageId: string): {
|
||||||
restoreScrollPosition: () => void;
|
restoreScrollPosition: () => void;
|
||||||
} {
|
} {
|
||||||
// CONTRACT: this hook assumes PageEditor REMOUNTS per page — page.tsx renders
|
// CONTRACT: this hook assumes PageEditor REMOUNTS per page — page.tsx renders
|
||||||
// `<MemoizedFullEditor key={page.id} ...>`, so switching pages creates a fresh
|
// `<MemoizedFullEditor key={page.id} ...>`, so switching pages creates a fresh
|
||||||
// hook instance with fresh refs. These refs latch per-mount and are NOT reset
|
// hook instance with fresh refs. Restore is idempotent and interaction-gated
|
||||||
// when `pageId` changes in place (only the effect re-runs on [pageId]). If that
|
// (not single-shot): it may be called from several triggers and re-asserts the
|
||||||
// `key={page.id}` is ever removed, restore would silently break on the 2nd page
|
// SAME captured target, which is a no-op once the window is already positioned.
|
||||||
// (refs would hold the first page's target / already-restored flag) — in that
|
// The per-mount refs that latch are `initialTargetRef` (the captured target)
|
||||||
// case the refs must be reset on a pageId change.
|
// and `userInteractedRef` (the reader has taken over scrolling). They are NOT
|
||||||
|
// reset when `pageId` changes in place (only the effect re-runs on [pageId]).
|
||||||
|
// If that `key={page.id}` is ever removed, restore would silently break on the
|
||||||
|
// 2nd page (refs would hold the first page's target / interaction flag) — in
|
||||||
|
// that case the refs must be reset on a pageId change.
|
||||||
//
|
//
|
||||||
// The target Y captured synchronously at mount, BEFORE any scroll/visibility
|
// The target Y captured synchronously at mount, BEFORE any scroll/visibility
|
||||||
// handler can overwrite the stored value with a fresh 0 (the page starts
|
// handler can overwrite the stored value with a fresh 0 (the page starts
|
||||||
// scrolled to top on load). `null` means "not yet captured".
|
// scrolled to top on load). `null` means "not yet captured".
|
||||||
const initialTargetRef = useRef<number | null>(null);
|
const initialTargetRef = useRef<number | null>(null);
|
||||||
// Guards so restore runs at most once per page mount.
|
// Set once the reader shows unambiguous scroll intent; restore must never yank
|
||||||
const hasRestoredRef = useRef(false);
|
// a reader who has already started scrolling.
|
||||||
|
const userInteractedRef = useRef(false);
|
||||||
// Holds the in-flight restore poll timer so the cleanup can cancel it: without
|
// Holds the in-flight restore poll timer so the cleanup can cancel it: without
|
||||||
// this, a fast SPA navigation away mid-poll would let the old page's poll fire
|
// this, a fast SPA navigation away mid-poll would let the old page's poll fire
|
||||||
// window.scrollTo against the NEW page's document (visible wrong-page scroll).
|
// window.scrollTo against the NEW page's document (visible wrong-page scroll).
|
||||||
const pollTimerRef = useRef<number | null>(null);
|
const pollTimerRef = useRef<number | null>(null);
|
||||||
|
// Timestamp of the FIRST restore attempt so re-triggers (e.g. the static→live
|
||||||
|
// editor swap) share ONE bounded timeout budget instead of restarting it.
|
||||||
|
const restoreStartRef = useRef<number | null>(null);
|
||||||
|
|
||||||
// Capture the previously-saved value synchronously during render, before the
|
// Capture the previously-saved value synchronously during render, before the
|
||||||
// effect below registers handlers that would persist the current (0) scrollY.
|
// effect below registers handlers that would persist the current (0) scrollY.
|
||||||
@@ -114,14 +147,43 @@ export function useScrollPosition(pageId: string): {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// User scroll-intent signals. wheel and touch are unconditional scroll
|
||||||
|
// intent; keydown is filtered to actual scroll keys only (SCROLL_KEYS) so
|
||||||
|
// shortcuts, lone modifiers, and typing do not abort restore. Our own
|
||||||
|
// window.scrollTo does NOT emit these, so restore can never self-abort via
|
||||||
|
// them. Once the reader shows intent we mark it and cancel any in-flight
|
||||||
|
// restore poll so restore can never yank them back. (Scrollbar-drag via
|
||||||
|
// pointer is an accepted small gap — it is not covered here.)
|
||||||
|
const onUserIntent = (event: Event) => {
|
||||||
|
// wheel/touchstart are unambiguous scroll intent; for keydown, only real
|
||||||
|
// scroll keys count — a shortcut or typing must not abort restore.
|
||||||
|
if (
|
||||||
|
event.type === "keydown" &&
|
||||||
|
!SCROLL_KEYS.has((event as KeyboardEvent).key)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
userInteractedRef.current = true;
|
||||||
|
if (pollTimerRef.current !== null) {
|
||||||
|
window.clearTimeout(pollTimerRef.current);
|
||||||
|
pollTimerRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
window.addEventListener("scroll", onScroll, { passive: true });
|
window.addEventListener("scroll", onScroll, { passive: true });
|
||||||
window.addEventListener("pagehide", onPageHide);
|
window.addEventListener("pagehide", onPageHide);
|
||||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||||
|
window.addEventListener("wheel", onUserIntent, { passive: true });
|
||||||
|
window.addEventListener("touchstart", onUserIntent, { passive: true });
|
||||||
|
window.addEventListener("keydown", onUserIntent);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener("scroll", onScroll);
|
window.removeEventListener("scroll", onScroll);
|
||||||
window.removeEventListener("pagehide", onPageHide);
|
window.removeEventListener("pagehide", onPageHide);
|
||||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||||
|
window.removeEventListener("wheel", onUserIntent);
|
||||||
|
window.removeEventListener("touchstart", onUserIntent);
|
||||||
|
window.removeEventListener("keydown", onUserIntent);
|
||||||
if (throttleTimer !== null) {
|
if (throttleTimer !== null) {
|
||||||
window.clearTimeout(throttleTimer);
|
window.clearTimeout(throttleTimer);
|
||||||
throttleTimer = null;
|
throttleTimer = null;
|
||||||
@@ -137,9 +199,8 @@ export function useScrollPosition(pageId: string): {
|
|||||||
}, [pageId]);
|
}, [pageId]);
|
||||||
|
|
||||||
const restoreScrollPosition = useCallback(() => {
|
const restoreScrollPosition = useCallback(() => {
|
||||||
// Run at most once per page mount.
|
// The reader took over — never yank them back.
|
||||||
if (hasRestoredRef.current) return;
|
if (userInteractedRef.current) return;
|
||||||
hasRestoredRef.current = true;
|
|
||||||
|
|
||||||
// Anchor priority: a `#hash` in the URL is handled by useEditorScroll.
|
// Anchor priority: a `#hash` in the URL is handled by useEditorScroll.
|
||||||
if (window.location.hash) return;
|
if (window.location.hash) return;
|
||||||
@@ -148,9 +209,26 @@ export function useScrollPosition(pageId: string): {
|
|||||||
// Nothing meaningful to restore to.
|
// Nothing meaningful to restore to.
|
||||||
if (targetY <= 0) return;
|
if (targetY <= 0) return;
|
||||||
|
|
||||||
const start = Date.now();
|
// Cancel any in-flight poll before (re)starting, so overlapping triggers can
|
||||||
|
// never run two concurrent polls against the same target.
|
||||||
|
if (pollTimerRef.current !== null) {
|
||||||
|
window.clearTimeout(pollTimerRef.current);
|
||||||
|
pollTimerRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Share one timeout budget across re-triggers instead of restarting it.
|
||||||
|
if (restoreStartRef.current === null) {
|
||||||
|
restoreStartRef.current = Date.now();
|
||||||
|
}
|
||||||
|
const start = restoreStartRef.current;
|
||||||
|
|
||||||
const tryRestore = () => {
|
const tryRestore = () => {
|
||||||
|
// Bail mid-poll if the reader started scrolling while we were waiting.
|
||||||
|
if (userInteractedRef.current) {
|
||||||
|
pollTimerRef.current = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const maxScroll =
|
const maxScroll =
|
||||||
document.documentElement.scrollHeight - window.innerHeight;
|
document.documentElement.scrollHeight - window.innerHeight;
|
||||||
const timedOut = Date.now() - start >= MAX_RESTORE_WAIT_MS;
|
const timedOut = Date.now() - start >= MAX_RESTORE_WAIT_MS;
|
||||||
@@ -158,10 +236,12 @@ export function useScrollPosition(pageId: string): {
|
|||||||
// Restore once the content is tall enough to reach the target, or bail out
|
// Restore once the content is tall enough to reach the target, or bail out
|
||||||
// after the timeout and scroll as far as currently possible.
|
// after the timeout and scroll as far as currently possible.
|
||||||
if (maxScroll >= targetY || timedOut) {
|
if (maxScroll >= targetY || timedOut) {
|
||||||
window.scrollTo({
|
const top = Math.min(targetY, Math.max(maxScroll, 0));
|
||||||
top: Math.min(targetY, Math.max(maxScroll, 0)),
|
// Redundancy guard: re-asserting the SAME target when already positioned
|
||||||
behavior: "auto",
|
// is a no-op, so this hook can be called from multiple triggers safely.
|
||||||
});
|
if (Math.abs(window.scrollY - top) > 1) {
|
||||||
|
window.scrollTo({ top, behavior: "auto" });
|
||||||
|
}
|
||||||
pollTimerRef.current = null;
|
pollTimerRef.current = null;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -175,3 +255,37 @@ export function useScrollPosition(pageId: string): {
|
|||||||
|
|
||||||
return { restoreScrollPosition };
|
return { restoreScrollPosition };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wires `useScrollPosition` to the page editor's static->live swap lifecycle.
|
||||||
|
*
|
||||||
|
* Extracted from PageEditor so the exact restore triggers (their deps and the
|
||||||
|
* post-swap `&& editor` guard) are directly unit-testable rather than mirrored.
|
||||||
|
* Behaviour is unchanged: `restoreScrollPosition` is idempotent, so re-asserting
|
||||||
|
* the same target from either trigger is a no-op.
|
||||||
|
*
|
||||||
|
* @param pageId the page whose scroll position is persisted/restored.
|
||||||
|
* @param editor the tiptap editor instance, or `null` until it is ready.
|
||||||
|
* @param showStatic whether the static (cached) content is still shown.
|
||||||
|
*/
|
||||||
|
export function useScrollRestoreOnSwap(
|
||||||
|
pageId: string,
|
||||||
|
editor: Editor | null,
|
||||||
|
showStatic: boolean,
|
||||||
|
): void {
|
||||||
|
const { restoreScrollPosition } = useScrollPosition(pageId);
|
||||||
|
|
||||||
|
// Restore as early as the static (cached) content is laid out, before paint,
|
||||||
|
// so the reader's position is applied without a visible jump. Aborts itself if
|
||||||
|
// the reader has already started scrolling (handled inside the hook).
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
restoreScrollPosition();
|
||||||
|
}, [restoreScrollPosition]);
|
||||||
|
|
||||||
|
// Re-assert once after the static -> live editor swap in case the swap reset
|
||||||
|
// the window scroll. Idempotent: a no-op when the position is already correct,
|
||||||
|
// and a no-op after the reader has interacted.
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (!showStatic && editor) restoreScrollPosition();
|
||||||
|
}, [showStatic, editor, restoreScrollPosition]);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { renderHook, act } from "@testing-library/react";
|
||||||
|
import type { RefObject } from "react";
|
||||||
|
import { useSwapHeightReservation } from "./use-swap-height-reservation";
|
||||||
|
|
||||||
|
// Controllable fake requestAnimationFrame. jsdom's rAF is timer-driven and hard
|
||||||
|
// to step deterministically, so we install a manual queue: `tickRaf()` drains the
|
||||||
|
// callbacks scheduled so far (a callback that reschedules enqueues a new one for
|
||||||
|
// the NEXT tick), letting each test advance the release loop frame by frame.
|
||||||
|
let rafQueue: Array<{ id: number; cb: FrameRequestCallback }> = [];
|
||||||
|
let nextRafId = 1;
|
||||||
|
let realRaf: typeof globalThis.requestAnimationFrame;
|
||||||
|
let realCancel: typeof globalThis.cancelAnimationFrame;
|
||||||
|
|
||||||
|
function tickRaf(): void {
|
||||||
|
const current = rafQueue;
|
||||||
|
rafQueue = [];
|
||||||
|
for (const { cb } of current) cb(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A mutable stand-in for the live-content container. The hook only reads
|
||||||
|
// `scrollHeight`, so tests drive the release condition by mutating this.
|
||||||
|
function makeMenuRef(): {
|
||||||
|
ref: RefObject<HTMLElement | null>;
|
||||||
|
setScrollHeight: (h: number) => void;
|
||||||
|
} {
|
||||||
|
const el = { scrollHeight: 0 };
|
||||||
|
return {
|
||||||
|
ref: { current: el } as unknown as RefObject<HTMLElement | null>,
|
||||||
|
setScrollHeight: (h: number) => {
|
||||||
|
el.scrollHeight = h;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const H = 1000;
|
||||||
|
|
||||||
|
describe("useSwapHeightReservation", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
rafQueue = [];
|
||||||
|
nextRafId = 1;
|
||||||
|
realRaf = globalThis.requestAnimationFrame;
|
||||||
|
realCancel = globalThis.cancelAnimationFrame;
|
||||||
|
globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {
|
||||||
|
const id = nextRafId++;
|
||||||
|
rafQueue.push({ id, cb });
|
||||||
|
return id;
|
||||||
|
}) as typeof globalThis.requestAnimationFrame;
|
||||||
|
globalThis.cancelAnimationFrame = ((id: number) => {
|
||||||
|
rafQueue = rafQueue.filter((e) => e.id !== id);
|
||||||
|
}) as typeof globalThis.cancelAnimationFrame;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
globalThis.requestAnimationFrame = realRaf;
|
||||||
|
globalThis.cancelAnimationFrame = realCancel;
|
||||||
|
vi.useRealTimers();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
// (a) reserve-on-swap: the captured height becomes `reservedHeight`, the value
|
||||||
|
// that drives the swap wrapper's minHeight. Captured while static is still up,
|
||||||
|
// then the swap flips showStatic; before any release frame runs the reservation
|
||||||
|
// is held at exactly H.
|
||||||
|
it("(a) holds the captured height as reservedHeight after the swap (drives minHeight)", () => {
|
||||||
|
const { ref, setScrollHeight } = makeMenuRef();
|
||||||
|
setScrollHeight(0); // live content not laid out yet -> release cannot fire.
|
||||||
|
const { result, rerender } = renderHook(
|
||||||
|
({ showStatic }) => useSwapHeightReservation(showStatic, ref),
|
||||||
|
{ initialProps: { showStatic: true } },
|
||||||
|
);
|
||||||
|
|
||||||
|
// Capture happens synchronously at the swap point (static still shown).
|
||||||
|
act(() => {
|
||||||
|
result.current.captureReservation(H);
|
||||||
|
});
|
||||||
|
// The swap flips to the live branch.
|
||||||
|
rerender({ showStatic: false });
|
||||||
|
|
||||||
|
expect(result.current.reservedHeight).toBe(H);
|
||||||
|
});
|
||||||
|
|
||||||
|
// (b) release when the live content is tall enough. Guard is `>=`: with
|
||||||
|
// liveHeight === H the reservation releases. This FAILS if the guard direction
|
||||||
|
// were `<` (liveHeight === H is not `< H`, so it would never release).
|
||||||
|
it("(b) releases once live content reaches the reserved height", () => {
|
||||||
|
const { ref, setScrollHeight } = makeMenuRef();
|
||||||
|
setScrollHeight(0);
|
||||||
|
const { result, rerender } = renderHook(
|
||||||
|
({ showStatic }) => useSwapHeightReservation(showStatic, ref),
|
||||||
|
{ initialProps: { showStatic: true } },
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.captureReservation(H);
|
||||||
|
});
|
||||||
|
rerender({ showStatic: false });
|
||||||
|
expect(result.current.reservedHeight).toBe(H); // still reserved (short live doc)
|
||||||
|
|
||||||
|
// Live editor finishes laying out to the reserved height.
|
||||||
|
setScrollHeight(H);
|
||||||
|
act(() => {
|
||||||
|
tickRaf();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.reservedHeight).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
// (c) cap escape: the live content never reaches the reserved height, so the
|
||||||
|
// height match never fires; the reservation must still release at the 4000ms
|
||||||
|
// cap (no stuck reservation / dead space). This FAILS if there were no cap: the
|
||||||
|
// loop would poll forever while scrollHeight stays below H.
|
||||||
|
it("(c) releases at the 4000ms cap when live content stays too short", () => {
|
||||||
|
// Only fake Date so `Date.now()` (the cap clock) is controllable; leave our
|
||||||
|
// manual rAF queue in place (default fake timers would replace it).
|
||||||
|
vi.useFakeTimers({ toFake: ["Date"] });
|
||||||
|
vi.setSystemTime(0);
|
||||||
|
const { ref, setScrollHeight } = makeMenuRef();
|
||||||
|
setScrollHeight(H - 100); // always shorter than reserved -> height match never fires.
|
||||||
|
const { result, rerender } = renderHook(
|
||||||
|
({ showStatic }) => useSwapHeightReservation(showStatic, ref),
|
||||||
|
{ initialProps: { showStatic: true } },
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.captureReservation(H);
|
||||||
|
});
|
||||||
|
rerender({ showStatic: false });
|
||||||
|
|
||||||
|
// A few frames pass but time has not reached the cap: still reserved.
|
||||||
|
act(() => {
|
||||||
|
tickRaf();
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
tickRaf();
|
||||||
|
});
|
||||||
|
expect(result.current.reservedHeight).toBe(H);
|
||||||
|
|
||||||
|
// Advance past the cap; the next frame releases even though the live content
|
||||||
|
// is still shorter than the reservation.
|
||||||
|
vi.setSystemTime(4001);
|
||||||
|
act(() => {
|
||||||
|
tickRaf();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.reservedHeight).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
// (d) non-swap: without a capture (and while static is shown) there is no
|
||||||
|
// reservation and the release loop never arms, so no rAF is scheduled.
|
||||||
|
it("(d) reserves nothing and arms no loop when the swap never happens", () => {
|
||||||
|
const { ref } = makeMenuRef();
|
||||||
|
const { result } = renderHook(() =>
|
||||||
|
useSwapHeightReservation(true, ref),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.current.reservedHeight).toBeNull();
|
||||||
|
expect(rafQueue.length).toBe(0); // release loop never armed
|
||||||
|
act(() => {
|
||||||
|
tickRaf();
|
||||||
|
});
|
||||||
|
expect(result.current.reservedHeight).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { RefObject, useCallback, useEffect, useState } from "react";
|
||||||
|
|
||||||
|
// Last-resort release deadline. The primary release is the live-content height
|
||||||
|
// match below; this cap only exists so a slow/short live doc can never pin the
|
||||||
|
// reservation forever. It is generous (well past when the live content normally
|
||||||
|
// reaches the reserved height — it renders the SAME content as the static copy)
|
||||||
|
// so a slow load doesn't release mid-render and reintroduce the collapse.
|
||||||
|
const RELEASE_CAP_MS = 4000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reserves the document height across the static -> live editor swap.
|
||||||
|
*
|
||||||
|
* The live editor lays out its content over a few frames, so replacing the
|
||||||
|
* (full-height) static copy with it momentarily shrinks the document; the
|
||||||
|
* browser then clamps window scroll to the top, which yanked the reader off
|
||||||
|
* their restored reading position (and threw their scroll to 0 if they were
|
||||||
|
* scrolling at that moment). Pinning a min-height on the swap wrapper keeps the
|
||||||
|
* document tall through the swap so the scroll position simply survives (#266).
|
||||||
|
* `reservedHeight === null` means no reservation is active.
|
||||||
|
*
|
||||||
|
* The capture is intentionally a CALLBACK the page editor invokes, NOT something
|
||||||
|
* this hook derives by watching `showStatic`. The height MUST be read
|
||||||
|
* synchronously while the static content is still mounted (full natural height),
|
||||||
|
* right before the flip to the live branch. By the time any post-transition
|
||||||
|
* effect here could run, `showStatic` is already false and the wrapper shows the
|
||||||
|
* live/collapsed content, so `offsetHeight` would be wrong. So page-editor calls
|
||||||
|
* `captureReservation(wrapper.offsetHeight)` inside its collab-sync effect,
|
||||||
|
* before `setShowStatic(false)`, preserving that exact timing.
|
||||||
|
*
|
||||||
|
* @param showStatic whether the static (cached) content is still shown.
|
||||||
|
* @param menuContainerRef the live-branch content container. It is a descendant
|
||||||
|
* of the swap wrapper inside the live branch, so its `scrollHeight` is the live
|
||||||
|
* content height (not inflated by the ancestor min-height reservation).
|
||||||
|
*/
|
||||||
|
export function useSwapHeightReservation(
|
||||||
|
showStatic: boolean,
|
||||||
|
menuContainerRef: RefObject<HTMLElement | null>,
|
||||||
|
): {
|
||||||
|
reservedHeight: number | null;
|
||||||
|
captureReservation: (height: number | null) => void;
|
||||||
|
} {
|
||||||
|
const [reservedHeight, setReservedHeight] = useState<number | null>(null);
|
||||||
|
|
||||||
|
// Capture the current (static, full-height) content height BEFORE the swap so
|
||||||
|
// the wrapper can reserve it while the live editor lays out — otherwise the
|
||||||
|
// transient shrink clamps window scroll to the top. The caller reads
|
||||||
|
// `offsetHeight` synchronously at the swap point and hands it here.
|
||||||
|
const captureReservation = useCallback(
|
||||||
|
(height: number | null) => setReservedHeight(height),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Release the reserved height once the live editor's content has laid out to
|
||||||
|
// at least the reserved height (so removing the reservation cannot collapse
|
||||||
|
// the document). The primary release is that height match; the cap is only a
|
||||||
|
// last-resort so we never pin forever. A shorter-than-reserved live doc (rare:
|
||||||
|
// stale/longer cache) releases at the cap, leaving only harmless bottom dead
|
||||||
|
// space until then.
|
||||||
|
useEffect(() => {
|
||||||
|
if (showStatic || reservedHeight == null) return;
|
||||||
|
let raf = 0;
|
||||||
|
const startedAt = Date.now();
|
||||||
|
const check = () => {
|
||||||
|
const liveHeight = menuContainerRef.current?.scrollHeight ?? 0;
|
||||||
|
if (
|
||||||
|
liveHeight >= reservedHeight ||
|
||||||
|
Date.now() - startedAt > RELEASE_CAP_MS
|
||||||
|
) {
|
||||||
|
setReservedHeight(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(check);
|
||||||
|
};
|
||||||
|
raf = requestAnimationFrame(check);
|
||||||
|
return () => cancelAnimationFrame(raf);
|
||||||
|
}, [showStatic, reservedHeight, menuContainerRef]);
|
||||||
|
|
||||||
|
return { reservedHeight, captureReservation };
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { renderHook, act } from "@testing-library/react";
|
||||||
|
import { useTitleAutofocus } from "./use-title-autofocus";
|
||||||
|
|
||||||
|
const KEY_PREFIX = "gitmost:scroll-position:";
|
||||||
|
|
||||||
|
function fakeEditor(overrides = {}) {
|
||||||
|
return { isInitialized: true, commands: { focus: vi.fn() }, ...overrides } as any;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("useTitleAutofocus", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
vi.useFakeTimers();
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips auto-focus when a saved reading position exists", () => {
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}saved`, "500");
|
||||||
|
const editor = fakeEditor();
|
||||||
|
renderHook(() => useTitleAutofocus(editor, "saved"));
|
||||||
|
act(() => vi.advanceTimersByTime(300));
|
||||||
|
expect(editor.commands.focus).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("auto-focuses a new page (no saved position) with scrollIntoView: false", () => {
|
||||||
|
const editor = fakeEditor();
|
||||||
|
renderHook(() => useTitleAutofocus(editor, "fresh"));
|
||||||
|
act(() => vi.advanceTimersByTime(300));
|
||||||
|
expect(editor.commands.focus).toHaveBeenCalledWith("end", { scrollIntoView: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not focus before initialization", () => {
|
||||||
|
const editor = fakeEditor({ isInitialized: false });
|
||||||
|
renderHook(() => useTitleAutofocus(editor, "fresh2"));
|
||||||
|
act(() => vi.advanceTimersByTime(300));
|
||||||
|
expect(editor.commands.focus).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("cancels the pending focus on unmount", () => {
|
||||||
|
const editor = fakeEditor();
|
||||||
|
const { unmount } = renderHook(() => useTitleAutofocus(editor, "fresh3"));
|
||||||
|
unmount();
|
||||||
|
act(() => vi.advanceTimersByTime(300));
|
||||||
|
expect(editor.commands.focus).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import type { Editor } from "@tiptap/react";
|
||||||
|
import { hasSavedReadingPosition } from "./use-scroll-position";
|
||||||
|
|
||||||
|
// Delay before auto-focusing the title on load — guards a tiptap init race
|
||||||
|
// ("Cannot access view['hasFocus']" if focused too early).
|
||||||
|
const TITLE_AUTOFOCUS_DELAY_MS = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auto-focus the page title shortly after mount — UNLESS a saved reading position
|
||||||
|
* will be restored (then the viewport scrolls away from the top, and focusing the
|
||||||
|
* top-of-page title would drop the caret off-screen). When it does focus, it uses
|
||||||
|
* `{ scrollIntoView: false }` so placing the caret never moves the viewport
|
||||||
|
* (tiptap's focus scrolls the focused node into view by default, which otherwise
|
||||||
|
* yanks the window to the top and fights scroll-position restoration).
|
||||||
|
*
|
||||||
|
* Extracted from TitleEditor so this exact decision is unit-testable.
|
||||||
|
*
|
||||||
|
* CONTRACT: relies on TitleEditor remounting per page (page.tsx renders
|
||||||
|
* `<MemoizedFullEditor key={page.id}>`), so `hasSavedScrollRef` is captured fresh
|
||||||
|
* per page. It is read synchronously on first render, before any scroll-save
|
||||||
|
* handler can clobber the stored value to 0 — matching `useScrollPosition`'s own
|
||||||
|
* synchronous capture of `initialTargetRef`.
|
||||||
|
*/
|
||||||
|
export function useTitleAutofocus(
|
||||||
|
titleEditor: Editor | null,
|
||||||
|
pageId: string,
|
||||||
|
): void {
|
||||||
|
const hasSavedScrollRef = useRef<boolean | null>(null);
|
||||||
|
if (hasSavedScrollRef.current === null) {
|
||||||
|
hasSavedScrollRef.current = hasSavedReadingPosition(pageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (hasSavedScrollRef.current) return;
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
// guard against "Cannot access view['hasFocus']" before init
|
||||||
|
if (!titleEditor?.isInitialized) return;
|
||||||
|
titleEditor?.commands?.focus("end", { scrollIntoView: false });
|
||||||
|
}, TITLE_AUTOFOCUS_DELAY_MS);
|
||||||
|
// Clear the pending focus if the editor changes or the component unmounts
|
||||||
|
// (also fixes the previously-uncancelled timer).
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [titleEditor]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { render, act } from "@testing-library/react";
|
||||||
|
import type { Editor } from "@tiptap/react";
|
||||||
|
import { useScrollRestoreOnSwap } from "./hooks/use-scroll-position";
|
||||||
|
|
||||||
|
const KEY_PREFIX = "gitmost:scroll-position:";
|
||||||
|
|
||||||
|
// NOTE ON SCOPE (F2 — reviewer-approved lighter variant).
|
||||||
|
//
|
||||||
|
// The real UX wiring lives in the exported `useScrollRestoreOnSwap` hook (two
|
||||||
|
// useLayoutEffects around useScrollPosition), which PageEditor calls with the
|
||||||
|
// same signature. A FULL PageEditor component test is impractical here and has no
|
||||||
|
// precedent in this client: PageEditor directly constructs a
|
||||||
|
// HocuspocusProviderWebsocket + IndexeddbPersistence, a tiptap `useEditor` with
|
||||||
|
// collab extensions, reads jotai atoms, react-router params, the shared
|
||||||
|
// `queryClient` from main.tsx, i18n, and mounts ~12 editor menu children. Worse,
|
||||||
|
// the static->live swap (`showStatic` -> false) is gated on
|
||||||
|
// `isCollabSynced(status, isLocalSynced && isRemoteSynced)`, which can only flip
|
||||||
|
// by driving the mocked collab provider's async sync callbacks. The heaviest
|
||||||
|
// component-test precedent in the repo (comment-hover-preview.test.tsx) mounts a
|
||||||
|
// single leaf component with ONE mocked query; nothing mounts a feature root of
|
||||||
|
// this weight. Reproducing all of that would test the mocks, not the wiring.
|
||||||
|
//
|
||||||
|
// So this file tests the REAL `useScrollRestoreOnSwap` hook — the exact code
|
||||||
|
// PageEditor imports and calls — driving its `showStatic`/`editor` inputs the way
|
||||||
|
// the swap does. Because it exercises the real hook (not a copy), dropping the
|
||||||
|
// `&& editor` guard or changing the effect deps makes these tests fail; they
|
||||||
|
// guard the production code directly (verified: removing `&& editor` reddens the
|
||||||
|
// first test).
|
||||||
|
//
|
||||||
|
// Both tests observe the real effect via `window.scrollTo`. The stubbed
|
||||||
|
// `window.scrollTo` never mutates `window.scrollY`, and the target is left
|
||||||
|
// unreached, so every restore invocation that passes the guard yields exactly one
|
||||||
|
// `scrollTo` call — making the call count a faithful proxy for restore invocations.
|
||||||
|
|
||||||
|
function setScrollY(value: number): void {
|
||||||
|
Object.defineProperty(window, "scrollY", { configurable: true, value });
|
||||||
|
}
|
||||||
|
function setScrollHeight(value: number): void {
|
||||||
|
Object.defineProperty(document.documentElement, "scrollHeight", {
|
||||||
|
configurable: true,
|
||||||
|
value,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function setInnerHeight(value: number): void {
|
||||||
|
Object.defineProperty(window, "innerHeight", { configurable: true, value });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Minimal stand-in for the tiptap editor: the hook only truthiness-checks it.
|
||||||
|
const fakeEditor = { id: "editor" } as unknown as Editor;
|
||||||
|
|
||||||
|
// Thin host that calls the REAL hook so a rerender drives showStatic/editor
|
||||||
|
// exactly like the page-editor swap does.
|
||||||
|
function Host({
|
||||||
|
pageId,
|
||||||
|
showStatic,
|
||||||
|
editor,
|
||||||
|
}: {
|
||||||
|
pageId: string;
|
||||||
|
showStatic: boolean;
|
||||||
|
editor: Editor | null;
|
||||||
|
}) {
|
||||||
|
useScrollRestoreOnSwap(pageId, editor, showStatic);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("PageEditor scroll-restore wiring (useScrollRestoreOnSwap)", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
setScrollY(0);
|
||||||
|
setScrollHeight(0);
|
||||||
|
setInnerHeight(800);
|
||||||
|
window.scrollTo = vi.fn();
|
||||||
|
window.location.hash = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
vi.useRealTimers();
|
||||||
|
window.location.hash = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
it("re-invokes restore after the swap, with the [showStatic, editor] deps/guard", () => {
|
||||||
|
// Target is immediately reachable, so each restore that passes the guard
|
||||||
|
// scrolls synchronously. `window.scrollY` stays 0 (stubbed scrollTo never
|
||||||
|
// updates it), so scrollTo is called once per effective restore — a proxy for
|
||||||
|
// the restore invocation count.
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}guard`, "500");
|
||||||
|
setInnerHeight(800);
|
||||||
|
setScrollHeight(2000); // maxScroll = 1200 >= 500: reachable, no polling.
|
||||||
|
|
||||||
|
// Pre-swap: static content shown, live editor not ready. Only the early
|
||||||
|
// pre-paint restore fires; the post-swap effect's guard (!showStatic) blocks it.
|
||||||
|
const { rerender } = render(
|
||||||
|
<Host pageId="guard" showStatic={true} editor={null} />,
|
||||||
|
);
|
||||||
|
expect(window.scrollTo).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// Collab reports synced (showStatic flips false) but the editor is not ready
|
||||||
|
// yet: the swap effect re-runs (deps [showStatic, editor] changed) but the
|
||||||
|
// `&& editor` guard must keep it a no-op. The early effect does NOT re-fire
|
||||||
|
// (its dep [restoreScrollPosition] is a stable useCallback([])).
|
||||||
|
// (Pins the guard: dropping `&& editor` would restore against a null editor,
|
||||||
|
// producing a 2nd scrollTo and failing this expectation.)
|
||||||
|
rerender(<Host pageId="guard" showStatic={false} editor={null} />);
|
||||||
|
expect(window.scrollTo).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// The static -> live swap completes (showStatic false AND editor present): the
|
||||||
|
// post-swap effect re-asserts the restore exactly once more, driven solely by
|
||||||
|
// the [showStatic, editor] deps changing.
|
||||||
|
rerender(<Host pageId="guard" showStatic={false} editor={fakeEditor} />);
|
||||||
|
expect(window.scrollTo).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("the post-swap re-assert drives a REAL restore (window.scrollTo) via the hook", () => {
|
||||||
|
// End-to-end through the real useScrollPosition (inside the hook): the swap
|
||||||
|
// re-invocation is the CAUSE of the scroll (nothing scrolls before it).
|
||||||
|
vi.useFakeTimers();
|
||||||
|
window.sessionStorage.setItem(`${KEY_PREFIX}peg`, "500");
|
||||||
|
setInnerHeight(800);
|
||||||
|
setScrollHeight(100); // maxScroll = -700: target not reachable yet -> polls.
|
||||||
|
|
||||||
|
// Pre-swap: the early restore runs but content is too short, so it starts
|
||||||
|
// polling (a pending timer) without scrolling. We never advance timers, so the
|
||||||
|
// early poll cannot fire on its own — isolating the swap as the sole cause.
|
||||||
|
const { rerender } = render(
|
||||||
|
<Host pageId="peg" showStatic={true} editor={null} />,
|
||||||
|
);
|
||||||
|
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// The live content is now laid out tall enough to reach the target.
|
||||||
|
setScrollHeight(2000); // maxScroll = 1200 >= 500
|
||||||
|
|
||||||
|
// The static -> live swap: the post-swap useLayoutEffect re-invokes the real
|
||||||
|
// hook, whose synchronous tryRestore now reaches the target and scrolls.
|
||||||
|
act(() => {
|
||||||
|
rerender(<Host pageId="peg" showStatic={false} editor={fakeEditor} />);
|
||||||
|
});
|
||||||
|
expect(window.scrollTo).toHaveBeenCalledWith({ top: 500, behavior: "auto" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -27,11 +27,12 @@ import {
|
|||||||
collabExtensions,
|
collabExtensions,
|
||||||
mainExtensions,
|
mainExtensions,
|
||||||
} from "@/features/editor/extensions/extensions";
|
} from "@/features/editor/extensions/extensions";
|
||||||
import { useAtom, useAtomValue } from "jotai";
|
import { useAtom, useAtomValue, useSetAtom } from "jotai";
|
||||||
import useCollaborationUrl from "@/features/editor/hooks/use-collaboration-url";
|
import useCollaborationUrl from "@/features/editor/hooks/use-collaboration-url";
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||||
import {
|
import {
|
||||||
currentPageEditModeAtom,
|
currentPageEditModeAtom,
|
||||||
|
dictationAvailabilityAtom,
|
||||||
pageEditorAtom,
|
pageEditorAtom,
|
||||||
yjsConnectionStatusAtom,
|
yjsConnectionStatusAtom,
|
||||||
} from "@/features/editor/atoms/editor-atoms";
|
} from "@/features/editor/atoms/editor-atoms";
|
||||||
@@ -78,7 +79,8 @@ import { PageEditMode } from "@/features/user/types/user.types.ts";
|
|||||||
import { jwtDecode } from "jwt-decode";
|
import { jwtDecode } from "jwt-decode";
|
||||||
import { searchSpotlight } from "@/features/search/constants.ts";
|
import { searchSpotlight } from "@/features/search/constants.ts";
|
||||||
import { useEditorScroll } from "./hooks/use-editor-scroll";
|
import { useEditorScroll } from "./hooks/use-editor-scroll";
|
||||||
import { useScrollPosition } from "./hooks/use-scroll-position";
|
import { useScrollRestoreOnSwap } from "./hooks/use-scroll-position";
|
||||||
|
import { useSwapHeightReservation } from "./hooks/use-swap-height-reservation";
|
||||||
import { EditorLinkMenu } from "@/features/editor/components/link/link-menu";
|
import { EditorLinkMenu } from "@/features/editor/components/link/link-menu";
|
||||||
import ColumnsMenu from "@/features/editor/components/columns/columns-menu.tsx";
|
import ColumnsMenu from "@/features/editor/components/columns/columns-menu.tsx";
|
||||||
import { TransclusionLookupProvider } from "@/features/editor/components/transclusion/transclusion-lookup-context";
|
import { TransclusionLookupProvider } from "@/features/editor/components/transclusion/transclusion-lookup-context";
|
||||||
@@ -87,6 +89,7 @@ import { PageEmbedAncestryProvider } from "@/features/editor/components/page-emb
|
|||||||
import PageEmbedPicker from "@/features/editor/components/page-embed/page-embed-picker";
|
import PageEmbedPicker from "@/features/editor/components/page-embed/page-embed-picker";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
|
computeDictationAvailability,
|
||||||
isBodyEditable,
|
isBodyEditable,
|
||||||
isCollabSynced,
|
isCollabSynced,
|
||||||
} from "@/features/editor/editor-sync-state";
|
} from "@/features/editor/editor-sync-state";
|
||||||
@@ -138,12 +141,12 @@ export default function PageEditor({
|
|||||||
const { pageSlug } = useParams();
|
const { pageSlug } = useParams();
|
||||||
const slugId = extractPageSlugId(pageSlug);
|
const slugId = extractPageSlugId(pageSlug);
|
||||||
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
|
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
|
||||||
|
const setDictationAvailability = useSetAtom(dictationAvailabilityAtom);
|
||||||
const canScroll = useCallback(
|
const canScroll = useCallback(
|
||||||
() => Boolean(isComponentMounted.current && editorRef.current),
|
() => Boolean(isComponentMounted.current && editorRef.current),
|
||||||
[isComponentMounted],
|
[isComponentMounted],
|
||||||
);
|
);
|
||||||
const { handleScrollTo } = useEditorScroll({ canScroll });
|
const { handleScrollTo } = useEditorScroll({ canScroll });
|
||||||
const { restoreScrollPosition } = useScrollPosition(pageId);
|
|
||||||
// Providers only created once per pageId
|
// Providers only created once per pageId
|
||||||
const providersRef = useRef<{
|
const providersRef = useRef<{
|
||||||
local: IndexeddbPersistence;
|
local: IndexeddbPersistence;
|
||||||
@@ -450,6 +453,22 @@ export default function PageEditor({
|
|||||||
const hasConnectedOnceRef = useRef(false);
|
const hasConnectedOnceRef = useRef(false);
|
||||||
const [showStatic, setShowStatic] = useState(true);
|
const [showStatic, setShowStatic] = useState(true);
|
||||||
|
|
||||||
|
// Reserved height held across the static -> live editor swap. The live editor
|
||||||
|
// lays out its content over a few frames, so replacing the (full-height) static
|
||||||
|
// copy with it momentarily shrinks the document; the browser then clamps window
|
||||||
|
// scroll to the top, which yanked the reader off their restored reading position
|
||||||
|
// (and threw their scroll to 0 if they were scrolling at that moment). Pinning a
|
||||||
|
// min-height on the swap wrapper keeps the document tall through the swap so the
|
||||||
|
// scroll position simply survives. `null` = no reservation active.
|
||||||
|
const swapWrapperRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
// Reserve/release wiring lives in the hook so its capture trigger and release
|
||||||
|
// guard/cap are directly unit-testable. Capture stays synchronous at the swap
|
||||||
|
// point (see the collab-sync effect below); the hook only owns the release.
|
||||||
|
const { reservedHeight, captureReservation } = useSwapHeightReservation(
|
||||||
|
showStatic,
|
||||||
|
menuContainerRef,
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
if (yjsConnectionStatus === WebSocketStatus.Connecting || !isSynced) {
|
if (yjsConnectionStatus === WebSocketStatus.Connecting || !isSynced) {
|
||||||
@@ -472,25 +491,55 @@ export default function PageEditor({
|
|||||||
);
|
);
|
||||||
}, [currentPageEditMode, editor, editable, showStatic]);
|
}, [currentPageEditMode, editor, editable, showStatic]);
|
||||||
|
|
||||||
|
// Publish whether dictation can start and, if not, the cause-specific reason
|
||||||
|
// the mic button surfaces. Recomputed on the same signals that drive body
|
||||||
|
// editability so the tooltip never lies about the current state.
|
||||||
|
useEffect(() => {
|
||||||
|
setDictationAvailability(
|
||||||
|
computeDictationAvailability({
|
||||||
|
editable,
|
||||||
|
inEditMode: currentPageEditMode === PageEditMode.Edit,
|
||||||
|
showStatic,
|
||||||
|
isDisconnected: yjsConnectionStatus === WebSocketStatus.Disconnected,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}, [
|
||||||
|
editable,
|
||||||
|
currentPageEditMode,
|
||||||
|
showStatic,
|
||||||
|
yjsConnectionStatus,
|
||||||
|
setDictationAvailability,
|
||||||
|
]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (
|
if (
|
||||||
!hasConnectedOnceRef.current &&
|
!hasConnectedOnceRef.current &&
|
||||||
isCollabSynced(yjsConnectionStatus, isSynced)
|
isCollabSynced(yjsConnectionStatus, isSynced)
|
||||||
) {
|
) {
|
||||||
hasConnectedOnceRef.current = true;
|
hasConnectedOnceRef.current = true;
|
||||||
|
// Capture the current (static, full-height) content height BEFORE the swap
|
||||||
|
// so the wrapper can reserve it while the live editor lays out — otherwise
|
||||||
|
// the transient shrink clamps window scroll to the top.
|
||||||
|
captureReservation(swapWrapperRef.current?.offsetHeight ?? null);
|
||||||
setShowStatic(false);
|
setShowStatic(false);
|
||||||
}
|
}
|
||||||
}, [yjsConnectionStatus, isSynced]);
|
}, [yjsConnectionStatus, isSynced]);
|
||||||
|
|
||||||
// Restore the saved reading position once the live content is laid out.
|
// Restore the reader's scroll position across the static -> live editor swap.
|
||||||
useEffect(() => {
|
// The wiring (early pre-paint restore + post-swap re-assert) lives in the hook
|
||||||
if (!showStatic && editor) restoreScrollPosition();
|
// so its triggers/guard are directly unit-testable.
|
||||||
}, [showStatic, editor, restoreScrollPosition]);
|
useScrollRestoreOnSwap(pageId, editor, showStatic);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TransclusionLookupProvider>
|
<TransclusionLookupProvider>
|
||||||
<PageEmbedLookupProvider>
|
<PageEmbedLookupProvider>
|
||||||
<PageEmbedAncestryProvider hostPageId={pageId}>
|
<PageEmbedAncestryProvider hostPageId={pageId}>
|
||||||
|
<div
|
||||||
|
ref={swapWrapperRef}
|
||||||
|
style={
|
||||||
|
reservedHeight != null ? { minHeight: reservedHeight } : undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
{showStatic ? (
|
{showStatic ? (
|
||||||
<div style={{ position: "relative" }}>
|
<div style={{ position: "relative" }}>
|
||||||
{/* Surface the pre-sync read-only window so edits typed before the
|
{/* Surface the pre-sync read-only window so edits typed before the
|
||||||
@@ -578,6 +627,7 @@ export default function PageEditor({
|
|||||||
></div>
|
></div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
</PageEmbedAncestryProvider>
|
</PageEmbedAncestryProvider>
|
||||||
</PageEmbedLookupProvider>
|
</PageEmbedLookupProvider>
|
||||||
</TransclusionLookupProvider>
|
</TransclusionLookupProvider>
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import localEmitter from "@/lib/local-emitter.ts";
|
|||||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||||
import { searchSpotlight } from "@/features/search/constants.ts";
|
import { searchSpotlight } from "@/features/search/constants.ts";
|
||||||
import { platformModifierKey } from "@/lib";
|
import { platformModifierKey } from "@/lib";
|
||||||
|
import { useTitleAutofocus } from "@/features/editor/hooks/use-title-autofocus";
|
||||||
|
|
||||||
export interface TitleEditorProps {
|
export interface TitleEditorProps {
|
||||||
pageId: string;
|
pageId: string;
|
||||||
@@ -167,13 +168,7 @@ export function TitleEditor({
|
|||||||
}
|
}
|
||||||
}, [pageId, title, titleEditor]);
|
}, [pageId, title, titleEditor]);
|
||||||
|
|
||||||
useEffect(() => {
|
useTitleAutofocus(titleEditor, pageId);
|
||||||
setTimeout(() => {
|
|
||||||
// guard against Cannot access view['hasFocus'] error
|
|
||||||
if (!titleEditor?.isInitialized) return;
|
|
||||||
titleEditor?.commands?.focus("end");
|
|
||||||
}, 300);
|
|
||||||
}, [titleEditor]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
import { describe, it, expect, vi, afterEach, beforeAll } from "vitest";
|
||||||
|
import { render, screen, cleanup, within } from "@testing-library/react";
|
||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
|
||||||
|
// Mantine Tooltip mounts its label lazily on hover via Floating UI, which is
|
||||||
|
// flaky under jsdom. Replace ONLY the Tooltip with a thin wrapper that renders
|
||||||
|
// the label inline (keeping Badge/Switch/etc. real), so the provenance label —
|
||||||
|
// the contract we care about — is deterministically queryable.
|
||||||
|
vi.mock("@mantine/core", async () => {
|
||||||
|
const actual =
|
||||||
|
await vi.importActual<typeof import("@mantine/core")>("@mantine/core");
|
||||||
|
const Tooltip = ({
|
||||||
|
label,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
label?: React.ReactNode;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
}) => (
|
||||||
|
<>
|
||||||
|
{children}
|
||||||
|
<span data-testid="tooltip-label">{label}</span>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
Tooltip.Group = ({ children }: { children?: React.ReactNode }) => (
|
||||||
|
<>{children}</>
|
||||||
|
);
|
||||||
|
return { ...actual, Tooltip };
|
||||||
|
});
|
||||||
|
|
||||||
|
// jsdom lacks matchMedia, which MantineProvider's color-scheme hook needs.
|
||||||
|
beforeAll(() => {
|
||||||
|
if (!window.matchMedia) {
|
||||||
|
window.matchMedia = (query: string) =>
|
||||||
|
({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addListener: () => {},
|
||||||
|
removeListener: () => {},
|
||||||
|
addEventListener: () => {},
|
||||||
|
removeEventListener: () => {},
|
||||||
|
dispatchEvent: () => false,
|
||||||
|
}) as unknown as MediaQueryList;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Mocks for the heavy / networked module graph ---------------------------
|
||||||
|
// HistoryItem pulls in i18n, jotai atoms (ai-chat / history), a config-backed
|
||||||
|
// avatar and a time formatter. The provenance-badge contract is the unit under
|
||||||
|
// test, so we stub everything else down to inert, deterministic renders and
|
||||||
|
// keep the real Mantine Badge/Tooltip so role/label queries are meaningful.
|
||||||
|
|
||||||
|
// i18n: interpolate {{name}} so the git-sync tooltip carries the author name,
|
||||||
|
// letting us assert provenance attribution without a real i18n backend.
|
||||||
|
vi.mock("react-i18next", () => ({
|
||||||
|
useTranslation: () => ({
|
||||||
|
t: (key: string, vars?: Record<string, unknown>) =>
|
||||||
|
vars && typeof vars.name !== "undefined"
|
||||||
|
? key.replace("{{name}}", String(vars.name))
|
||||||
|
: key,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// jotai setters: the badges call useSetAtom; return inert setters so a click on
|
||||||
|
// the (deep-linkable) AiAgentBadge would fire these — proving the git-sync badge
|
||||||
|
// does NOT wire any of them.
|
||||||
|
const setAiChatWindowOpen = vi.fn();
|
||||||
|
const setActiveChatId = vi.fn();
|
||||||
|
const setDraft = vi.fn();
|
||||||
|
const setHistoryModalOpen = vi.fn();
|
||||||
|
vi.mock("jotai", async () => {
|
||||||
|
const actual = await vi.importActual<typeof import("jotai")>("jotai");
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
useSetAtom: (atom: unknown) => {
|
||||||
|
switch (atom) {
|
||||||
|
case aiChatWindowOpenAtom:
|
||||||
|
return setAiChatWindowOpen;
|
||||||
|
case activeAiChatIdAtom:
|
||||||
|
return setActiveChatId;
|
||||||
|
case aiChatDraftAtom:
|
||||||
|
return setDraft;
|
||||||
|
case historyAtoms:
|
||||||
|
return setHistoryModalOpen;
|
||||||
|
default:
|
||||||
|
return vi.fn();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Atoms are imported only as identity tokens for the useSetAtom switch above.
|
||||||
|
vi.mock("@/features/ai-chat/atoms/ai-chat-atom.ts", () => ({
|
||||||
|
activeAiChatIdAtom: { __tag: "activeAiChatIdAtom" },
|
||||||
|
aiChatWindowOpenAtom: { __tag: "aiChatWindowOpenAtom" },
|
||||||
|
aiChatDraftAtom: { __tag: "aiChatDraftAtom" },
|
||||||
|
}));
|
||||||
|
vi.mock("@/features/page-history/atoms/history-atoms.ts", () => ({
|
||||||
|
historyAtoms: { __tag: "historyAtoms" },
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Avatar reaches into config (getAvatarUrl) — stub to a plain element.
|
||||||
|
vi.mock("@/components/ui/custom-avatar.tsx", () => ({
|
||||||
|
CustomAvatar: ({ name }: { name?: string }) => (
|
||||||
|
<span data-testid="avatar">{name}</span>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Deterministic, locale-free date string.
|
||||||
|
vi.mock("@/lib/time", () => ({
|
||||||
|
formattedDate: () => "2026-06-21",
|
||||||
|
}));
|
||||||
|
|
||||||
|
import HistoryItem from "./history-item";
|
||||||
|
import {
|
||||||
|
activeAiChatIdAtom,
|
||||||
|
aiChatWindowOpenAtom,
|
||||||
|
aiChatDraftAtom,
|
||||||
|
} from "@/features/ai-chat/atoms/ai-chat-atom.ts";
|
||||||
|
import { historyAtoms } from "@/features/page-history/atoms/history-atoms.ts";
|
||||||
|
import type { IPageHistory } from "@/features/page-history/types/page.types";
|
||||||
|
|
||||||
|
function makeItem(overrides: Partial<IPageHistory> = {}): IPageHistory {
|
||||||
|
return {
|
||||||
|
id: "h1",
|
||||||
|
pageId: "p1",
|
||||||
|
title: "Title",
|
||||||
|
slug: "slug",
|
||||||
|
icon: "",
|
||||||
|
coverPhoto: "",
|
||||||
|
version: 1,
|
||||||
|
lastUpdatedById: "u1",
|
||||||
|
workspaceId: "w1",
|
||||||
|
createdAt: "2026-06-21T00:00:00.000Z",
|
||||||
|
updatedAt: "2026-06-21T00:00:00.000Z",
|
||||||
|
lastUpdatedBy: { id: "u1", name: "Alice", avatarUrl: "" },
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderItem(item: IPageHistory) {
|
||||||
|
return render(
|
||||||
|
<MantineProvider>
|
||||||
|
<HistoryItem
|
||||||
|
historyItem={item}
|
||||||
|
index={0}
|
||||||
|
onSelect={vi.fn()}
|
||||||
|
isActive={false}
|
||||||
|
/>
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("HistoryItem git-sync provenance badge", () => {
|
||||||
|
// Test 1: the git-sync badge renders ONLY for lastUpdatedSource === 'git-sync'.
|
||||||
|
it("renders the Git sync badge only when lastUpdatedSource is 'git-sync'", () => {
|
||||||
|
renderItem(makeItem({ lastUpdatedSource: "git-sync" }));
|
||||||
|
expect(screen.getByText("Git sync")).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["agent", "agent"],
|
||||||
|
["user", "user"],
|
||||||
|
["undefined", undefined],
|
||||||
|
])(
|
||||||
|
"does NOT render the Git sync badge when lastUpdatedSource is %s",
|
||||||
|
(_label, source) => {
|
||||||
|
renderItem(makeItem({ lastUpdatedSource: source }));
|
||||||
|
expect(screen.queryByText("Git sync")).toBeNull();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Test 2: provenance attribution + the git-sync badge is NOT interactive.
|
||||||
|
it("attributes the git-sync provenance to the correct author and is not clickable", () => {
|
||||||
|
renderItem(
|
||||||
|
makeItem({
|
||||||
|
lastUpdatedSource: "git-sync",
|
||||||
|
lastUpdatedBy: { id: "u2", name: "Bob", avatarUrl: "" },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const badge = screen.getByText("Git sync");
|
||||||
|
|
||||||
|
// Provenance attribution: the tooltip label carries the author name (the
|
||||||
|
// git-sync badge passes authorName -> "Synced from Git on behalf of {{name}}").
|
||||||
|
expect(screen.getByText("Synced from Git on behalf of Bob")).toBeTruthy();
|
||||||
|
|
||||||
|
// The git-sync badge must NOT behave like AiAgentBadge: the badge element
|
||||||
|
// itself is not a button, carries no role=button and no tabIndex, and
|
||||||
|
// clicking it must not trigger any ai-chat deep-link. (The surrounding
|
||||||
|
// history-row IS an UnstyledButton — that is the row's own select affordance,
|
||||||
|
// not the badge — so we scope these checks to the badge element.)
|
||||||
|
const badgeRoot = (badge.closest("[class*='mantine-Badge-root']") ??
|
||||||
|
badge) as HTMLElement;
|
||||||
|
expect(badgeRoot.getAttribute("role")).not.toBe("button");
|
||||||
|
expect(badgeRoot.getAttribute("tabindex")).toBeNull();
|
||||||
|
expect(badgeRoot.tagName.toLowerCase()).not.toBe("button");
|
||||||
|
// No interactive descendant button lives inside the badge itself.
|
||||||
|
expect(within(badgeRoot).queryByRole("button")).toBeNull();
|
||||||
|
|
||||||
|
badgeRoot.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
expect(setActiveChatId).not.toHaveBeenCalled();
|
||||||
|
expect(setAiChatWindowOpen).not.toHaveBeenCalled();
|
||||||
|
expect(setDraft).not.toHaveBeenCalled();
|
||||||
|
expect(setHistoryModalOpen).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Sanity contrast: the agent provenance IS interactive when it carries an
|
||||||
|
// aiChatId — proving the not-clickable assertion above is real. The old text
|
||||||
|
// `AiAgentBadge` was superseded by `AgentAvatarStack` (#300), which becomes a
|
||||||
|
// role=button deep-link (and fires the ai-chat atoms) when an aiChatId is present.
|
||||||
|
it("contrast: the agent stack is a deep-link button when it has an aiChatId", () => {
|
||||||
|
renderItem(
|
||||||
|
makeItem({
|
||||||
|
lastUpdatedSource: "agent",
|
||||||
|
agent: { name: "Zeta" },
|
||||||
|
lastUpdatedAiChatId: "chat-1",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// The agent glyph lives inside the clickable stack; walk up to its role=button.
|
||||||
|
const root = screen.getByTestId("agent-glyph").closest("[role='button']");
|
||||||
|
expect(root).not.toBeNull();
|
||||||
|
(root as HTMLElement).dispatchEvent(
|
||||||
|
new MouseEvent("click", { bubbles: true }),
|
||||||
|
);
|
||||||
|
expect(setActiveChatId).toHaveBeenCalledWith("chat-1");
|
||||||
|
expect(setAiChatWindowOpen).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Text, Group, UnstyledButton, Avatar, Tooltip } from "@mantine/core";
|
import { Text, Group, UnstyledButton, Avatar, Tooltip } from "@mantine/core";
|
||||||
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||||
import { AiAgentBadge } from "@/components/ui/ai-agent-badge.tsx";
|
import { GitSyncBadge } from "@/components/ui/git-sync-badge.tsx";
|
||||||
|
import { AgentAvatarStack } from "@/components/ui/agent-avatar-stack.tsx";
|
||||||
import { formattedDate } from "@/lib/time";
|
import { formattedDate } from "@/lib/time";
|
||||||
import classes from "./css/history.module.css";
|
import classes from "./css/history.module.css";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
@@ -41,6 +42,7 @@ const HistoryItem = memo(function HistoryItem({
|
|||||||
const contributors = historyItem.contributors;
|
const contributors = historyItem.contributors;
|
||||||
const hasContributors = contributors && contributors.length > 0;
|
const hasContributors = contributors && contributors.length > 0;
|
||||||
const isAgentEdit = historyItem.lastUpdatedSource === "agent";
|
const isAgentEdit = historyItem.lastUpdatedSource === "agent";
|
||||||
|
const isGitSyncEdit = historyItem.lastUpdatedSource === "git-sync";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<UnstyledButton
|
<UnstyledButton
|
||||||
@@ -99,15 +101,20 @@ const HistoryItem = memo(function HistoryItem({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isAgentEdit && (
|
{isAgentEdit && historyItem.agent && (
|
||||||
<AiAgentBadge
|
<AgentAvatarStack
|
||||||
authorName={historyItem.lastUpdatedBy?.name}
|
agent={historyItem.agent}
|
||||||
|
launcher={historyItem.launcher}
|
||||||
aiChatId={historyItem.lastUpdatedAiChatId}
|
aiChatId={historyItem.lastUpdatedAiChatId}
|
||||||
// The history row owns the modal: close it when the badge deep-links
|
// The history row owns the modal: close it when the stack deep-links
|
||||||
// into the chat (the badge no longer reaches into page-history).
|
// into the chat (the stack no longer reaches into page-history).
|
||||||
onActivate={() => setHistoryModalOpen(false)}
|
onActivate={() => setHistoryModalOpen(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{isGitSyncEdit && (
|
||||||
|
<GitSyncBadge authorName={historyItem.lastUpdatedBy?.name} />
|
||||||
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
</UnstyledButton>
|
</UnstyledButton>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
import type {
|
||||||
|
AgentInfo,
|
||||||
|
LauncherInfo,
|
||||||
|
} from "@/components/ui/agent-avatar-stack.tsx";
|
||||||
|
|
||||||
interface IPageHistoryUser {
|
interface IPageHistoryUser {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -24,4 +29,9 @@ export interface IPageHistory {
|
|||||||
// (when present) deep-links to the chat that produced the edit.
|
// (when present) deep-links to the chat that produced the edit.
|
||||||
lastUpdatedSource?: string;
|
lastUpdatedSource?: string;
|
||||||
lastUpdatedAiChatId?: string | null;
|
lastUpdatedAiChatId?: string | null;
|
||||||
|
// Server-normalized "agent avatar stack" provenance (#300), present only when
|
||||||
|
// lastUpdatedSource === "agent": `agent` is the front identity, `launcher` the
|
||||||
|
// human behind it (null for an external MCP agent).
|
||||||
|
agent?: AgentInfo | null;
|
||||||
|
launcher?: LauncherInfo | null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,11 @@
|
|||||||
import { Button, Group, Paper, Text } from "@mantine/core";
|
import {
|
||||||
|
ActionIcon,
|
||||||
|
Button,
|
||||||
|
Group,
|
||||||
|
Paper,
|
||||||
|
Text,
|
||||||
|
Tooltip,
|
||||||
|
} from "@mantine/core";
|
||||||
import { IconClockHour4, IconTrash } from "@tabler/icons-react";
|
import { IconClockHour4, IconTrash } from "@tabler/icons-react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Trans, useTranslation } from "react-i18next";
|
import { Trans, useTranslation } from "react-i18next";
|
||||||
@@ -70,7 +77,14 @@ export function TemporaryNoteBanner({ slugId }: TemporaryNoteBannerProps) {
|
|||||||
return (
|
return (
|
||||||
<Paper radius="sm" mb="md" px="md" py="xs" bg="orange.0">
|
<Paper radius="sm" mb="md" px="md" py="xs" bg="orange.0">
|
||||||
<Group justify="space-between" wrap="wrap" gap="sm">
|
<Group justify="space-between" wrap="wrap" gap="sm">
|
||||||
<Group gap="xs" wrap="nowrap" style={{ flex: 1, minWidth: 0 }}>
|
{/* A non-zero flex-basis lets the outer wrap="wrap" drop the buttons to
|
||||||
|
their own row on narrow screens; flex:1 (basis 0) never wraps and
|
||||||
|
instead crushes the text into a one-word-per-line ladder. */}
|
||||||
|
<Group
|
||||||
|
gap="xs"
|
||||||
|
wrap="nowrap"
|
||||||
|
style={{ flex: "1 1 16rem", minWidth: 0 }}
|
||||||
|
>
|
||||||
<IconClockHour4
|
<IconClockHour4
|
||||||
size={18}
|
size={18}
|
||||||
stroke={1.5}
|
stroke={1.5}
|
||||||
@@ -87,7 +101,9 @@ export function TemporaryNoteBanner({ slugId }: TemporaryNoteBannerProps) {
|
|||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<Group gap="xs" wrap="nowrap">
|
<>
|
||||||
|
{/* Desktop: full labeled buttons. */}
|
||||||
|
<Group gap="xs" wrap="nowrap" visibleFrom="sm">
|
||||||
<Button
|
<Button
|
||||||
size="xs"
|
size="xs"
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
@@ -109,6 +125,34 @@ export function TemporaryNoteBanner({ slugId }: TemporaryNoteBannerProps) {
|
|||||||
{t("Make permanent")}
|
{t("Make permanent")}
|
||||||
</Button>
|
</Button>
|
||||||
</Group>
|
</Group>
|
||||||
|
{/* Mobile: icon-only actions so they never overflow the narrow row. */}
|
||||||
|
<Group gap="xs" wrap="nowrap" hiddenFrom="sm">
|
||||||
|
<Tooltip label={t("Move to trash")} withArrow>
|
||||||
|
<ActionIcon
|
||||||
|
size="lg"
|
||||||
|
variant="subtle"
|
||||||
|
color="red"
|
||||||
|
onClick={handleTrashNow}
|
||||||
|
loading={isDeleting}
|
||||||
|
aria-label={t("Move to trash")}
|
||||||
|
>
|
||||||
|
<IconTrash size={18} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip label={t("Make permanent")} withArrow>
|
||||||
|
<ActionIcon
|
||||||
|
size="lg"
|
||||||
|
variant="light"
|
||||||
|
color="orange"
|
||||||
|
onClick={handleMakePermanent}
|
||||||
|
loading={toggleTemporary.isPending}
|
||||||
|
aria-label={t("Make permanent")}
|
||||||
|
>
|
||||||
|
<IconClockHour4 size={18} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
</Group>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|||||||
@@ -13,20 +13,30 @@ export type OpenMap = Record<string, boolean>;
|
|||||||
// `OpenMap | Promise<OpenMap>` and break the functional-updater setter below).
|
// `OpenMap | Promise<OpenMap>` and break the functional-updater setter below).
|
||||||
const openTreeNodesStorage = createJSONStorage<OpenMap>(() => localStorage);
|
const openTreeNodesStorage = createJSONStorage<OpenMap>(() => localStorage);
|
||||||
|
|
||||||
|
// Single source of truth for the open-map localStorage key prefix. Exported so
|
||||||
|
// the logout cache sweep (tree-data-atom.ts) removes keys by the SAME prefix
|
||||||
|
// used to write them — a rename here can never silently desync the cleanup.
|
||||||
|
export const OPEN_TREE_NODES_KEY_PREFIX = "openTreeNodes:";
|
||||||
|
|
||||||
// One persisted open/closed map per (workspace, user). Scoping the localStorage
|
// One persisted open/closed map per (workspace, user). Scoping the localStorage
|
||||||
// key prevents accounts that share a browser origin from leaking tree state.
|
// key prevents accounts that share a browser origin from leaking tree state.
|
||||||
// `getOnInit: true` reads localStorage synchronously at atom init (not on mount),
|
// `getOnInit: true` reads localStorage synchronously at atom init (not on mount),
|
||||||
// so the first render already has the saved state — no collapse-then-expand
|
// so the first render already has the saved state — no collapse-then-expand
|
||||||
// flicker on reload, and writes never run against an un-hydrated empty map.
|
// flicker on reload, and writes never run against an un-hydrated empty map.
|
||||||
const openTreeNodesFamily = atomFamily((scopeKey: string) =>
|
const openTreeNodesFamily = atomFamily((scopeKey: string) =>
|
||||||
atomWithStorage<OpenMap>(`openTreeNodes:${scopeKey}`, {}, openTreeNodesStorage, {
|
atomWithStorage<OpenMap>(
|
||||||
getOnInit: true,
|
`${OPEN_TREE_NODES_KEY_PREFIX}${scopeKey}`,
|
||||||
}),
|
{},
|
||||||
|
openTreeNodesStorage,
|
||||||
|
{ getOnInit: true },
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Resolve the storage scope from the current user. Fall back to "anon" for the
|
// Resolve the storage scope from the current user. Fall back to "anon" for the
|
||||||
// workspace/user parts when nothing is loaded yet (logged out / first paint).
|
// workspace/user parts when nothing is loaded yet (logged out / first paint).
|
||||||
const scopeKeyAtom = atom((get) => {
|
// Shared by the open-map atom below and the persisted tree-data atom
|
||||||
|
// (tree-data-atom.ts) so both caches are scoped identically.
|
||||||
|
export const scopeKeyAtom = atom((get) => {
|
||||||
const currentUser = get(currentUserAtom);
|
const currentUser = get(currentUserAtom);
|
||||||
const workspaceId = currentUser?.workspace?.id ?? "anon";
|
const workspaceId = currentUser?.workspace?.id ?? "anon";
|
||||||
const userId = currentUser?.user?.id ?? "anon";
|
const userId = currentUser?.user?.id ?? "anon";
|
||||||
|
|||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import type { SpaceTreeNode } from "@/features/page/tree/types";
|
||||||
|
import type { ICurrentUser } from "@/features/user/types/user.types";
|
||||||
|
|
||||||
|
// The persisted tree-data atom hydrates from localStorage ONCE, at family-atom
|
||||||
|
// creation (`getOnInit: true`). To exercise hydration deterministically each
|
||||||
|
// test imports a FRESH module instance (fresh atomFamily) after seeding the
|
||||||
|
// storage stub from vitest.setup.ts. jotai itself is externalized by vitest, so
|
||||||
|
// `createStore` can stay a static import — atoms are plain objects and any
|
||||||
|
// store works with any module instance.
|
||||||
|
import { createStore } from "jotai";
|
||||||
|
|
||||||
|
// Storage key for the default scope: no currentUser -> "anon:anon" (see
|
||||||
|
// scopeKeyAtom in open-tree-nodes-atom.ts) with the `v1` cache-shape version.
|
||||||
|
const ANON_KEY = "treeData:v1:anon:anon";
|
||||||
|
const DEBOUNCE_MS = 500;
|
||||||
|
|
||||||
|
async function freshImport() {
|
||||||
|
vi.resetModules();
|
||||||
|
const treeDataModule = await import("./tree-data-atom");
|
||||||
|
const userModule = await import(
|
||||||
|
"@/features/user/atoms/current-user-atom"
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
treeDataAtom: treeDataModule.treeDataAtom,
|
||||||
|
flushPendingTreeDataWrites: treeDataModule.flushPendingTreeDataWrites,
|
||||||
|
clearPersistedTreeCaches: treeDataModule.clearPersistedTreeCaches,
|
||||||
|
currentUserAtom: userModule.currentUserAtom,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function node(id: string): SpaceTreeNode {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
slugId: `slug-${id}`,
|
||||||
|
name: id,
|
||||||
|
position: "a0",
|
||||||
|
spaceId: "space-1",
|
||||||
|
parentPageId: null as unknown as string,
|
||||||
|
hasChildren: false,
|
||||||
|
children: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every persisted tree key currently in storage — asserting on the whole
|
||||||
|
// prefix (not one known key) catches writes that resurrect under ANY scope.
|
||||||
|
function persistedTreeDataKeys(): string[] {
|
||||||
|
const keys: string[] = [];
|
||||||
|
for (let i = 0; i < localStorage.length; i++) {
|
||||||
|
const key = localStorage.key(i);
|
||||||
|
if (key !== null && key.startsWith("treeData:v1:")) keys.push(key);
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentUser(workspaceId: string, userId: string): ICurrentUser {
|
||||||
|
return {
|
||||||
|
user: { id: userId },
|
||||||
|
workspace: { id: workspaceId },
|
||||||
|
} as unknown as ICurrentUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("treeDataAtom (localStorage-persisted)", () => {
|
||||||
|
it("reads [] from a fresh store with empty storage", async () => {
|
||||||
|
const { treeDataAtom } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
expect(store.get(treeDataAtom)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("persists through the debounced setItem and hydrates a fresh module back", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const setItemSpy = vi.spyOn(localStorage, "setItem");
|
||||||
|
|
||||||
|
const { treeDataAtom } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
store.set(treeDataAtom, [node("a")]);
|
||||||
|
// Second write inside the debounce window — must coalesce into ONE flush
|
||||||
|
// carrying only the latest value.
|
||||||
|
vi.advanceTimersByTime(DEBOUNCE_MS / 2);
|
||||||
|
store.set(treeDataAtom, [node("a"), node("b")]);
|
||||||
|
|
||||||
|
// Nothing flushed yet: the write is trailing-debounced.
|
||||||
|
expect(localStorage.getItem(ANON_KEY)).toBeNull();
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(DEBOUNCE_MS + 100);
|
||||||
|
|
||||||
|
expect(setItemSpy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(JSON.parse(localStorage.getItem(ANON_KEY)!)).toEqual([
|
||||||
|
node("a"),
|
||||||
|
node("b"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// A fresh module (fresh atom family -> getOnInit re-reads storage) and a
|
||||||
|
// fresh store hydrate the persisted tree back — the reload scenario.
|
||||||
|
const second = await freshImport();
|
||||||
|
const store2 = createStore();
|
||||||
|
expect(store2.get(second.treeDataAtom)).toEqual([node("a"), node("b")]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads [] (without throwing) when storage holds corrupted JSON", async () => {
|
||||||
|
localStorage.setItem(ANON_KEY, "{definitely not JSON!!!");
|
||||||
|
|
||||||
|
const { treeDataAtom } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
expect(store.get(treeDataAtom)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads [] when storage holds valid JSON of a non-array shape", async () => {
|
||||||
|
localStorage.setItem(ANON_KEY, JSON.stringify({ id: "not-a-tree" }));
|
||||||
|
|
||||||
|
const { treeDataAtom } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
expect(store.get(treeDataAtom)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports functional-updater writes", async () => {
|
||||||
|
const { treeDataAtom } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
store.set(treeDataAtom, [node("a")]);
|
||||||
|
store.set(treeDataAtom, (prev) => [...prev, node("b")]);
|
||||||
|
|
||||||
|
expect(store.get(treeDataAtom).map((n) => n.id)).toEqual(["a", "b"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("isolates trees between (workspace, user) scopes", async () => {
|
||||||
|
const { treeDataAtom, currentUserAtom } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
store.set(currentUserAtom, currentUser("w1", "u1"));
|
||||||
|
store.set(treeDataAtom, [node("a")]);
|
||||||
|
expect(store.get(treeDataAtom).map((n) => n.id)).toEqual(["a"]);
|
||||||
|
|
||||||
|
// Another account on the same browser origin must NOT see u1's tree.
|
||||||
|
store.set(currentUserAtom, currentUser("w2", "u2"));
|
||||||
|
expect(store.get(treeDataAtom)).toEqual([]);
|
||||||
|
|
||||||
|
store.set(treeDataAtom, [node("b")]);
|
||||||
|
expect(store.get(treeDataAtom).map((n) => n.id)).toEqual(["b"]);
|
||||||
|
|
||||||
|
// Switching back resolves the original scope's tree untouched.
|
||||||
|
store.set(currentUserAtom, currentUser("w1", "u1"));
|
||||||
|
expect(store.get(treeDataAtom).map((n) => n.id)).toEqual(["a"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clearPersistedTreeCaches removes all tree keys and discards pending writes", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
// Stale caches across scopes plus an UNRELATED key that must survive.
|
||||||
|
localStorage.setItem("treeData:v1:a:b", JSON.stringify([node("stale")]));
|
||||||
|
localStorage.setItem("openTreeNodes:a:b", JSON.stringify({ p1: true }));
|
||||||
|
localStorage.setItem("currentUser", JSON.stringify({ user: { id: "b" } }));
|
||||||
|
|
||||||
|
const { treeDataAtom, clearPersistedTreeCaches } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
// Queue a debounced write (not flushed yet) for the anon scope.
|
||||||
|
store.set(treeDataAtom, [node("pending")]);
|
||||||
|
expect(localStorage.getItem(ANON_KEY)).toBeNull();
|
||||||
|
|
||||||
|
clearPersistedTreeCaches();
|
||||||
|
|
||||||
|
// Both prefixed caches are swept; the unrelated key is untouched.
|
||||||
|
expect(localStorage.getItem("treeData:v1:a:b")).toBeNull();
|
||||||
|
expect(localStorage.getItem("openTreeNodes:a:b")).toBeNull();
|
||||||
|
expect(localStorage.getItem("currentUser")).toBe(
|
||||||
|
JSON.stringify({ user: { id: "b" } }),
|
||||||
|
);
|
||||||
|
|
||||||
|
// The queued write was DISCARDED, not merely delayed: the debounce timer
|
||||||
|
// firing later must not resurrect a tree key after logout.
|
||||||
|
vi.advanceTimersByTime(DEBOUNCE_MS + 100);
|
||||||
|
expect(localStorage.getItem(ANON_KEY)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clearPersistedTreeCaches discards queued writes even when flushed DIRECTLY", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
const { treeDataAtom, clearPersistedTreeCaches, flushPendingTreeDataWrites } =
|
||||||
|
await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
// Queue a debounced write, then clear. Calling the flush directly (not via
|
||||||
|
// the debounce timer) isolates the pending-queue discard from the timer
|
||||||
|
// cancel: if the queue survived, this flush would resurrect the key even
|
||||||
|
// though the timer never fired.
|
||||||
|
store.set(treeDataAtom, [node("pending")]);
|
||||||
|
clearPersistedTreeCaches();
|
||||||
|
flushPendingTreeDataWrites();
|
||||||
|
|
||||||
|
expect(localStorage.getItem(ANON_KEY)).toBeNull();
|
||||||
|
expect(persistedTreeDataKeys()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips persisting a tree over the size cap and warns exactly once", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||||
|
const setItemSpy = vi.spyOn(localStorage, "setItem");
|
||||||
|
|
||||||
|
const { treeDataAtom, flushPendingTreeDataWrites } = await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
// One node whose name alone serializes to > MAX_SERIALIZED_LENGTH (~4M).
|
||||||
|
const huge = node("big");
|
||||||
|
huge.name = "x".repeat(4_000_001);
|
||||||
|
|
||||||
|
store.set(treeDataAtom, [huge]);
|
||||||
|
vi.advanceTimersByTime(DEBOUNCE_MS + 100);
|
||||||
|
|
||||||
|
// The oversized serialization is skipped: the key is never written.
|
||||||
|
expect(localStorage.getItem(ANON_KEY)).toBeNull();
|
||||||
|
expect(setItemSpy).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// Editing the still-oversized tree fires another debounced write, but the
|
||||||
|
// "too large" warn is gated by the once-flag — no per-tick console spam.
|
||||||
|
store.set(treeDataAtom, [huge, node("big2")]);
|
||||||
|
vi.advanceTimersByTime(DEBOUNCE_MS + 100);
|
||||||
|
flushPendingTreeDataWrites();
|
||||||
|
|
||||||
|
expect(localStorage.getItem(ANON_KEY)).toBeNull();
|
||||||
|
expect(warnSpy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(warnSpy).toHaveBeenCalledWith(
|
||||||
|
"[tree] cached tree too large to persist; skipping",
|
||||||
|
ANON_KEY,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disables persistence after clearPersistedTreeCaches: NEW writes never reach storage", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
const { treeDataAtom, clearPersistedTreeCaches, flushPendingTreeDataWrites } =
|
||||||
|
await freshImport();
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
clearPersistedTreeCaches();
|
||||||
|
|
||||||
|
// The resurrection scenario: a websocket tree event lands while `await
|
||||||
|
// logout()` is still in flight, AFTER the sweep. The write must not be
|
||||||
|
// queued, must not arm a new debounce timer, and must not survive the
|
||||||
|
// beforeunload flush fired by the logout redirect.
|
||||||
|
store.set(treeDataAtom, [node("late")]);
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(DEBOUNCE_MS + 100);
|
||||||
|
flushPendingTreeDataWrites(); // what the beforeunload handler runs
|
||||||
|
|
||||||
|
expect(persistedTreeDataKeys()).toEqual([]);
|
||||||
|
|
||||||
|
// Only PERSISTENCE is disabled: the in-memory atom keeps working, so the
|
||||||
|
// UI stays intact during the brief pre-redirect window.
|
||||||
|
expect(store.get(treeDataAtom).map((n) => n.id)).toEqual(["late"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,8 +1,206 @@
|
|||||||
import { atom } from "jotai";
|
import { atom } from "jotai";
|
||||||
|
import { atomFamily, atomWithStorage } from "jotai/utils";
|
||||||
import { SpaceTreeNode } from "@/features/page/tree/types";
|
import { SpaceTreeNode } from "@/features/page/tree/types";
|
||||||
import { appendNodeChildren } from "../utils";
|
import { appendNodeChildren } from "../utils";
|
||||||
|
import {
|
||||||
|
OPEN_TREE_NODES_KEY_PREFIX,
|
||||||
|
scopeKeyAtom,
|
||||||
|
} from "./open-tree-nodes-atom";
|
||||||
|
|
||||||
export const treeDataAtom = atom<SpaceTreeNode[]>([]);
|
// The sidebar tree is persisted to localStorage so a page reload can paint the
|
||||||
|
// last-known tree IMMEDIATELY (no blank sidebar while the root query runs) and
|
||||||
|
// then reconcile with the server in the background. localStorage is a BOOT
|
||||||
|
// CACHE only — the in-memory atom stays the source of truth while the app runs.
|
||||||
|
|
||||||
|
// Trailing-debounce machinery for the localStorage writes. The tree is
|
||||||
|
// rewritten on every lazy load / drag / socket event; serializing a large tree
|
||||||
|
// on each update would burn CPU and thrash the storage quota, so writes are
|
||||||
|
// coalesced (~500 ms per burst) and only the latest value per key is flushed.
|
||||||
|
const WRITE_DEBOUNCE_MS = 500;
|
||||||
|
|
||||||
|
// Single source of truth for the tree-cache localStorage key prefix. The `v1`
|
||||||
|
// segment versions the cached node shape (bump it when SpaceTreeNode changes
|
||||||
|
// incompatibly). Shared by the storage key construction below AND the logout
|
||||||
|
// sweep in clearPersistedTreeCaches() so the two can never drift apart.
|
||||||
|
export const TREE_DATA_KEY_PREFIX = "treeData:v1:";
|
||||||
|
|
||||||
|
// Size guard: skip persisting trees whose JSON exceeds ~4M chars. localStorage
|
||||||
|
// quota is typically ~5 MB per origin; a huge tree must not evict everything
|
||||||
|
// else or spam QuotaExceededError on every debounce tick.
|
||||||
|
const MAX_SERIALIZED_LENGTH = 4_000_000;
|
||||||
|
|
||||||
|
const pendingWrites = new Map<string, SpaceTreeNode[]>();
|
||||||
|
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let writeFailureWarned = false;
|
||||||
|
|
||||||
|
// Persistence kill-switch, armed by clearPersistedTreeCaches(). Once set, the
|
||||||
|
// debounced setItem and the flush become no-ops so nothing can be written back
|
||||||
|
// to localStorage AFTER the logout sweep: a websocket tree event landing while
|
||||||
|
// `await logout()` is still in flight would otherwise re-queue a write that
|
||||||
|
// the `beforeunload` flush (fired by the redirect) silently resurrects.
|
||||||
|
// Intentionally never reset: every caller of clearPersistedTreeCaches()
|
||||||
|
// immediately navigates away with a full page load
|
||||||
|
// (window.location.replace/href), so this module instance is torn down anyway.
|
||||||
|
// Only PERSISTENCE stops — the in-memory atoms keep working, so the UI stays
|
||||||
|
// intact during the brief pre-redirect window.
|
||||||
|
let persistenceDisabled = false;
|
||||||
|
|
||||||
|
function writeNow(key: string, value: SpaceTreeNode[]): void {
|
||||||
|
try {
|
||||||
|
const serialized = JSON.stringify(value);
|
||||||
|
if (serialized.length > MAX_SERIALIZED_LENGTH) {
|
||||||
|
// Warn ONCE, like the quota branch below: a >4M-char tree re-serializes on
|
||||||
|
// every ~500ms debounce tick while it's edited, so an un-gated warn would
|
||||||
|
// spam the console on each flush.
|
||||||
|
if (!writeFailureWarned) {
|
||||||
|
writeFailureWarned = true;
|
||||||
|
console.warn("[tree] cached tree too large to persist; skipping", key);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
localStorage.setItem(key, serialized);
|
||||||
|
} catch (err) {
|
||||||
|
// QuotaExceededError, private mode, jsdom shims without working storage…
|
||||||
|
// The cache is best-effort: warn once, keep the in-memory tree working.
|
||||||
|
if (!writeFailureWarned) {
|
||||||
|
writeFailureWarned = true;
|
||||||
|
console.warn("[tree] failed to persist tree cache", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exported so tests can force the debounced write synchronously; production
|
||||||
|
// code must never need it (the beforeunload hook below covers reloads).
|
||||||
|
export function flushPendingTreeDataWrites(): void {
|
||||||
|
if (flushTimer !== null) {
|
||||||
|
clearTimeout(flushTimer);
|
||||||
|
flushTimer = null;
|
||||||
|
}
|
||||||
|
if (persistenceDisabled) {
|
||||||
|
// Belt-and-braces: after logout nothing may reach localStorage, even via
|
||||||
|
// the beforeunload flush racing the redirect. Drop anything queued.
|
||||||
|
pendingWrites.clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const [key, value] of pendingWrites) {
|
||||||
|
writeNow(key, value);
|
||||||
|
}
|
||||||
|
pendingWrites.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logout hygiene: the tree cache stores PAGE TITLES, so leaving it behind
|
||||||
|
// would keep them readable in localStorage on a shared machine after logout.
|
||||||
|
// Sweep by key prefix (not just the current scope) so stale scopes — old
|
||||||
|
// users, the `anon:anon` fallback — are purged too. Pending debounced writes
|
||||||
|
// are DISCARDED first (not flushed): a queued write firing after the sweep
|
||||||
|
// would silently resurrect a removed key.
|
||||||
|
export function clearPersistedTreeCaches(): void {
|
||||||
|
// Disable persistence FIRST so no write can be queued (or flushed) between
|
||||||
|
// the sweep below and the full-page navigation every caller performs next.
|
||||||
|
persistenceDisabled = true;
|
||||||
|
if (flushTimer !== null) {
|
||||||
|
clearTimeout(flushTimer);
|
||||||
|
flushTimer = null;
|
||||||
|
}
|
||||||
|
pendingWrites.clear();
|
||||||
|
try {
|
||||||
|
// Collect matching keys BEFORE removing: deleting while iterating
|
||||||
|
// `localStorage.key(i)` shifts the indices and skips entries.
|
||||||
|
const keysToRemove: string[] = [];
|
||||||
|
for (let i = 0; i < localStorage.length; i++) {
|
||||||
|
const key = localStorage.key(i);
|
||||||
|
if (
|
||||||
|
key !== null &&
|
||||||
|
(key.startsWith(TREE_DATA_KEY_PREFIX) ||
|
||||||
|
key.startsWith(OPEN_TREE_NODES_KEY_PREFIX))
|
||||||
|
) {
|
||||||
|
keysToRemove.push(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const key of keysToRemove) {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Best-effort: disabled storage / jsdom shims must never break logout.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush the pending debounced write on unload so a reload right after a tree
|
||||||
|
// change doesn't lose the newest state (the debounce would otherwise eat it).
|
||||||
|
if (
|
||||||
|
typeof window !== "undefined" &&
|
||||||
|
typeof window.addEventListener === "function"
|
||||||
|
) {
|
||||||
|
window.addEventListener("beforeunload", flushPendingTreeDataWrites);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom sync storage for the tree cache. Deliberately NO `subscribe` key:
|
||||||
|
// cross-tab sync would REPLACE this tab's tree wholesale and clobber in-flight
|
||||||
|
// lazy loads; websockets already keep every open tab live. Each tab keeps its
|
||||||
|
// own in-memory tree — localStorage only seeds the next boot.
|
||||||
|
const treeDataStorage = {
|
||||||
|
getItem: (key: string, initialValue: SpaceTreeNode[]): SpaceTreeNode[] => {
|
||||||
|
// Defensive: jsdom test shims may lack methods, stored JSON may be
|
||||||
|
// corrupted or of a wrong shape. Any failure falls back to the empty tree.
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(key);
|
||||||
|
if (raw === null) return initialValue;
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
return Array.isArray(parsed) ? (parsed as SpaceTreeNode[]) : initialValue;
|
||||||
|
} catch {
|
||||||
|
return initialValue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
setItem: (key: string, newValue: SpaceTreeNode[]): void => {
|
||||||
|
// After logout the cache must stay purged: neither queue the write nor arm
|
||||||
|
// a new flush timer (see persistenceDisabled above). The in-memory atom
|
||||||
|
// value is unaffected — only the localStorage mirror is frozen.
|
||||||
|
if (persistenceDisabled) return;
|
||||||
|
pendingWrites.set(key, newValue);
|
||||||
|
if (flushTimer !== null) clearTimeout(flushTimer);
|
||||||
|
flushTimer = setTimeout(flushPendingTreeDataWrites, WRITE_DEBOUNCE_MS);
|
||||||
|
},
|
||||||
|
removeItem: (key: string): void => {
|
||||||
|
pendingWrites.delete(key);
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
} catch {
|
||||||
|
/* best-effort cache — ignore */
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// One persisted tree per (workspace, user) — same scoping rationale as the
|
||||||
|
// open-map atom (accounts sharing a browser origin must not leak trees).
|
||||||
|
// `getOnInit: true` reads localStorage synchronously at atom init, so the very
|
||||||
|
// first render already has the cached tree — no blank-then-jump sidebar.
|
||||||
|
const treeDataFamily = atomFamily((scopeKey: string) =>
|
||||||
|
atomWithStorage<SpaceTreeNode[]>(
|
||||||
|
`${TREE_DATA_KEY_PREFIX}${scopeKey}`,
|
||||||
|
[],
|
||||||
|
treeDataStorage,
|
||||||
|
{ getOnInit: true },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Public facade — same read value (SpaceTreeNode[]) and same setter shape
|
||||||
|
// (value OR functional updater) as the previous in-memory atom, transparently
|
||||||
|
// routed to the persisted tree of the current workspace/user.
|
||||||
|
export const treeDataAtom = atom(
|
||||||
|
(get) => get(treeDataFamily(get(scopeKeyAtom))),
|
||||||
|
(
|
||||||
|
get,
|
||||||
|
set,
|
||||||
|
update: SpaceTreeNode[] | ((prev: SpaceTreeNode[]) => SpaceTreeNode[]),
|
||||||
|
) => {
|
||||||
|
const target = treeDataFamily(get(scopeKeyAtom));
|
||||||
|
const next =
|
||||||
|
typeof update === "function"
|
||||||
|
? (update as (prev: SpaceTreeNode[]) => SpaceTreeNode[])(get(target))
|
||||||
|
: update;
|
||||||
|
set(target, next);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Atom
|
// Atom
|
||||||
export const appendNodeChildrenAtom = atom(
|
export const appendNodeChildrenAtom = atom(
|
||||||
|
|||||||
@@ -0,0 +1,222 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { createRef } from "react";
|
||||||
|
import { render, act, waitFor, cleanup } from "@testing-library/react";
|
||||||
|
|
||||||
|
// --- Mocks for the heavy / networked module graph ---------------------------
|
||||||
|
// Same isolation strategy as space-tree.expand-all.test.tsx: everything that
|
||||||
|
// would otherwise need a real server / router / DnD stack is mocked. Here we
|
||||||
|
// additionally CAPTURE the DocTree props (onToggle + data) so the test can
|
||||||
|
// drive a lazy-load expand exactly as a row click would, and we control
|
||||||
|
// fetchAllAncestorChildren to assert the fresh fetch happens.
|
||||||
|
|
||||||
|
const fetchAllAncestorChildrenMock = vi.fn();
|
||||||
|
|
||||||
|
// Holder mutated by the DocTree stub each render so the test can read the
|
||||||
|
// latest tree it was handed and invoke its onToggle callback.
|
||||||
|
const docTree: {
|
||||||
|
onToggle?: (id: string, isOpen: boolean) => void | Promise<void>;
|
||||||
|
data: unknown[];
|
||||||
|
} = { data: [] };
|
||||||
|
|
||||||
|
vi.mock("@/features/page/services/page-service.ts", () => ({
|
||||||
|
getSpaceTree: vi.fn(),
|
||||||
|
getPageBreadcrumbs: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/features/page/queries/page-query.ts", () => ({
|
||||||
|
// No root pages and no further pages — the server data-load effect stays
|
||||||
|
// inert (isDataLoaded never flips), so refreshOpenBranches never runs and the
|
||||||
|
// test exercises ONLY the boot-prune + handleToggle lazy-load path against
|
||||||
|
// the hydrated cache we seed into the atom below.
|
||||||
|
useGetRootSidebarPagesQuery: () => ({
|
||||||
|
data: undefined,
|
||||||
|
hasNextPage: false,
|
||||||
|
fetchNextPage: vi.fn(),
|
||||||
|
isFetching: false,
|
||||||
|
}),
|
||||||
|
usePageQuery: () => ({ data: undefined }),
|
||||||
|
fetchAllAncestorChildren: (...args: unknown[]) =>
|
||||||
|
fetchAllAncestorChildrenMock(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/features/page/tree/hooks/use-tree-mutation.ts", () => ({
|
||||||
|
useTreeMutation: () => ({ handleMove: vi.fn() }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@mantine/notifications", () => ({
|
||||||
|
notifications: { show: vi.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("react-i18next", () => ({
|
||||||
|
useTranslation: () => ({ t: (key: string) => key }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("react-router-dom", () => ({
|
||||||
|
useParams: () => ({ pageSlug: undefined }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib", () => ({
|
||||||
|
extractPageSlugId: () => undefined,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/config.ts", () => ({
|
||||||
|
isCompactPageTreeEnabled: () => false,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Capture the props DocTree is rendered with instead of rendering anything.
|
||||||
|
vi.mock("./doc-tree", () => ({
|
||||||
|
DocTree: (props: { onToggle: (id: string, isOpen: boolean) => void; data: unknown[] }) => {
|
||||||
|
docTree.onToggle = props.onToggle;
|
||||||
|
docTree.data = props.data;
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
ROW_HEIGHT_COMPACT: 28,
|
||||||
|
ROW_HEIGHT_STANDARD: 32,
|
||||||
|
}));
|
||||||
|
vi.mock("./space-tree-row", () => ({
|
||||||
|
SpaceTreeRow: () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@mantine/core", () => ({
|
||||||
|
Text: ({ children }: { children?: unknown }) => children ?? null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// In-memory open-map (the real one is localStorage-backed and crashes under the
|
||||||
|
// jsdom shim). Empty at start of each test -> every branch is COLLAPSED, which
|
||||||
|
// is exactly the state we need to prove the boot-prune. `scopeKeyAtom` is
|
||||||
|
// re-exported because the persisted tree-data atom resolves its scope through it.
|
||||||
|
vi.mock("@/features/page/tree/atoms/open-tree-nodes-atom.ts", async () => {
|
||||||
|
const { atom } = await import("jotai");
|
||||||
|
type OpenMap = Record<string, boolean>;
|
||||||
|
const base = atom<OpenMap>({});
|
||||||
|
const openTreeNodesAtom = atom(
|
||||||
|
(get) => get(base),
|
||||||
|
(get, set, update: OpenMap | ((prev: OpenMap) => OpenMap)) => {
|
||||||
|
const next =
|
||||||
|
typeof update === "function"
|
||||||
|
? (update as (prev: OpenMap) => OpenMap)(get(base))
|
||||||
|
: update;
|
||||||
|
set(base, next);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const scopeKeyAtom = atom(() => "test-workspace:test-user");
|
||||||
|
return { openTreeNodesAtom, scopeKeyAtom };
|
||||||
|
});
|
||||||
|
|
||||||
|
import SpaceTree, { SpaceTreeApi } from "./space-tree";
|
||||||
|
import {
|
||||||
|
treeDataAtom,
|
||||||
|
flushPendingTreeDataWrites,
|
||||||
|
} from "@/features/page/tree/atoms/tree-data-atom.ts";
|
||||||
|
import { createStore, Provider } from "jotai";
|
||||||
|
import type { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
||||||
|
|
||||||
|
// The scopeKeyAtom mock resolves to this fixed scope, so the persisted
|
||||||
|
// tree-data atom hydrates from exactly this localStorage key at mount
|
||||||
|
// (getOnInit + atomWithStorage's onMount both read it).
|
||||||
|
const CACHE_KEY = "treeData:v1:test-workspace:test-user";
|
||||||
|
|
||||||
|
function child(
|
||||||
|
id: string,
|
||||||
|
parentPageId: string,
|
||||||
|
hasChildren = false,
|
||||||
|
): SpaceTreeNode {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
slugId: `slug-${id}`,
|
||||||
|
name: id,
|
||||||
|
position: "a0",
|
||||||
|
spaceId: "space-1",
|
||||||
|
parentPageId,
|
||||||
|
hasChildren,
|
||||||
|
children: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// A hydrated boot cache: a COLLAPSED branch (not in the open-map) that still
|
||||||
|
// carries a stale cached child — the exact shape a previous session left behind
|
||||||
|
// after the branch was expanded then collapsed then persisted.
|
||||||
|
function cachedTreeWithCollapsedBranch(): SpaceTreeNode[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: "branch",
|
||||||
|
slugId: "slug-branch",
|
||||||
|
name: "branch",
|
||||||
|
position: "a0",
|
||||||
|
spaceId: "space-1",
|
||||||
|
parentPageId: null as unknown as string,
|
||||||
|
hasChildren: true,
|
||||||
|
children: [child("stale", "branch")],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fetchAllAncestorChildrenMock.mockReset();
|
||||||
|
docTree.onToggle = undefined;
|
||||||
|
docTree.data = [];
|
||||||
|
// Flush any pending debounced write from a previous test before clearing.
|
||||||
|
flushPendingTreeDataWrites();
|
||||||
|
try {
|
||||||
|
localStorage.clear?.();
|
||||||
|
} catch {
|
||||||
|
/* fresh store per test isolates state */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("SpaceTree boot-cache prune (#159 #8 stale collapsed children)", () => {
|
||||||
|
it("drops a collapsed cached branch's children on boot and fetches fresh on first expand", async () => {
|
||||||
|
// Server returns FRESH children on the lazy-load: the stale cached child is
|
||||||
|
// gone, a renamed/new one takes its place.
|
||||||
|
fetchAllAncestorChildrenMock.mockResolvedValue([child("fresh", "branch")]);
|
||||||
|
|
||||||
|
// Simulate the localStorage-hydrated boot cache: seed the persisted key
|
||||||
|
// BEFORE mount so the atom hydrates it (store.set would be clobbered by
|
||||||
|
// atomWithStorage's onMount re-reading storage — this is the real path).
|
||||||
|
localStorage.setItem(
|
||||||
|
CACHE_KEY,
|
||||||
|
JSON.stringify(cachedTreeWithCollapsedBranch()),
|
||||||
|
);
|
||||||
|
|
||||||
|
const store = createStore();
|
||||||
|
const ref = createRef<SpaceTreeApi>();
|
||||||
|
render(
|
||||||
|
<Provider store={store}>
|
||||||
|
<SpaceTree ref={ref} spaceId="space-1" readOnly={false} />
|
||||||
|
</Provider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Boot-prune ran at mount: the COLLAPSED branch's cached children were
|
||||||
|
// dropped to the unloaded shape ([]), so the stale child is no longer there.
|
||||||
|
const branchAfterBoot = docTree.data.find(
|
||||||
|
(n) => (n as SpaceTreeNode).id === "branch",
|
||||||
|
) as SpaceTreeNode;
|
||||||
|
expect(branchAfterBoot.children).toEqual([]);
|
||||||
|
expect(branchAfterBoot.hasChildren).toBe(true);
|
||||||
|
|
||||||
|
// First expand of the collapsed branch after boot must lazy-load fresh
|
||||||
|
// children (before this fix the cached children were kept and the fetch
|
||||||
|
// was skipped, showing stale data).
|
||||||
|
await act(async () => {
|
||||||
|
await docTree.onToggle!("branch", true);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(fetchAllAncestorChildrenMock).toHaveBeenCalledTimes(1);
|
||||||
|
expect(fetchAllAncestorChildrenMock).toHaveBeenCalledWith({
|
||||||
|
pageId: "branch",
|
||||||
|
spaceId: "space-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
// The fresh children replaced the stale cache in the live tree.
|
||||||
|
await waitFor(() => {
|
||||||
|
const branch = store
|
||||||
|
.get(treeDataAtom)
|
||||||
|
.find((n) => n.id === "branch")!;
|
||||||
|
expect(branch.children.map((c) => c.id)).toEqual(["fresh"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -71,7 +71,8 @@ vi.mock("@mantine/core", () => ({
|
|||||||
// getOnInit), which crashes under jsdom's localStorage shim here. Swap in a
|
// getOnInit), which crashes under jsdom's localStorage shim here. Swap in a
|
||||||
// plain in-memory atom with the same read value (OpenMap) and the same setter
|
// plain in-memory atom with the same read value (OpenMap) and the same setter
|
||||||
// shape (value OR functional updater) so the component's open-state logic runs
|
// shape (value OR functional updater) so the component's open-state logic runs
|
||||||
// unchanged while staying inside the test store.
|
// unchanged while staying inside the test store. `scopeKeyAtom` is also
|
||||||
|
// re-exported (the real module exports it for the persisted tree-data atom).
|
||||||
vi.mock("@/features/page/tree/atoms/open-tree-nodes-atom.ts", async () => {
|
vi.mock("@/features/page/tree/atoms/open-tree-nodes-atom.ts", async () => {
|
||||||
const { atom } = await import("jotai");
|
const { atom } = await import("jotai");
|
||||||
type OpenMap = Record<string, boolean>;
|
type OpenMap = Record<string, boolean>;
|
||||||
@@ -86,11 +87,17 @@ vi.mock("@/features/page/tree/atoms/open-tree-nodes-atom.ts", async () => {
|
|||||||
set(base, next);
|
set(base, next);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
return { openTreeNodesAtom };
|
// Fixed scope key: the tree-data atom family resolves through this, so all
|
||||||
|
// tests read/write the same (empty at start of each test) storage key.
|
||||||
|
const scopeKeyAtom = atom(() => "test-workspace:test-user");
|
||||||
|
return { openTreeNodesAtom, scopeKeyAtom };
|
||||||
});
|
});
|
||||||
|
|
||||||
import SpaceTree, { SpaceTreeApi } from "./space-tree";
|
import SpaceTree, { SpaceTreeApi } from "./space-tree";
|
||||||
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom.ts";
|
import {
|
||||||
|
treeDataAtom,
|
||||||
|
flushPendingTreeDataWrites,
|
||||||
|
} from "@/features/page/tree/atoms/tree-data-atom.ts";
|
||||||
import { openTreeNodesAtom } from "@/features/page/tree/atoms/open-tree-nodes-atom.ts";
|
import { openTreeNodesAtom } from "@/features/page/tree/atoms/open-tree-nodes-atom.ts";
|
||||||
import { createStore, Provider } from "jotai";
|
import { createStore, Provider } from "jotai";
|
||||||
import type { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
import type { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
||||||
@@ -134,6 +141,10 @@ function renderTree(store: ReturnType<typeof createStore>) {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
getSpaceTreeMock.mockReset();
|
getSpaceTreeMock.mockReset();
|
||||||
notificationsShowMock.mockReset();
|
notificationsShowMock.mockReset();
|
||||||
|
// The tree-data atom persists via a ~500 ms trailing debounce; flush it NOW
|
||||||
|
// (cancelling the timer) so a previous test's pending write can't land in
|
||||||
|
// storage mid-test after the clear below.
|
||||||
|
flushPendingTreeDataWrites();
|
||||||
// jsdom's localStorage shim here lacks `clear`; guard it. Each test uses a
|
// jsdom's localStorage shim here lacks `clear`; guard it. Each test uses a
|
||||||
// fresh jotai store anyway, so cross-test open-state never leaks.
|
// fresh jotai store anyway, so cross-test open-state never leaks.
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import {
|
|||||||
openBranches,
|
openBranches,
|
||||||
closeIds,
|
closeIds,
|
||||||
loadedOpenBranchIds,
|
loadedOpenBranchIds,
|
||||||
|
pruneCollapsedChildren,
|
||||||
} from "@/features/page/tree/utils/utils.ts";
|
} from "@/features/page/tree/utils/utils.ts";
|
||||||
import { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
import { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
||||||
import { treeModel } from "@/features/page/tree/model/tree-model";
|
import { treeModel } from "@/features/page/tree/model/tree-model";
|
||||||
@@ -199,18 +200,28 @@ const SpaceTree = forwardRef<SpaceTreeApi, SpaceTreeProps>(function SpaceTree(
|
|||||||
const openIdsRef = useRef(openIds);
|
const openIdsRef = useRef(openIds);
|
||||||
openIdsRef.current = openIds;
|
openIdsRef.current = openIds;
|
||||||
|
|
||||||
// Reconnect refresh (#159 #8): on a socket reconnect, re-fetch and reconcile
|
// Boot-cache hygiene (#159 #8): the localStorage-hydrated tree carries the
|
||||||
// the children of every currently-open, already-loaded branch of THIS space,
|
// children of every branch ever expanded, including ones now COLLAPSED. Their
|
||||||
// so a move/rename/delete that happened INSIDE a loaded branch while events
|
// first expand would skip the lazy-load and render stale children (a
|
||||||
// were missed (laptop sleep / wifi gap) is reflected instead of left stale.
|
// rename/move/delete missed while offline). Drop the cached children of every
|
||||||
// The ROOT level is reconciled separately by the root-query refetch +
|
// COLLAPSED branch ONCE at mount so its first expand fetches fresh via
|
||||||
// mergeRootTrees; an UNLOADED branch is skipped (lazy-load fetches it fresh on
|
// handleToggle — exactly as it did before the tree was cached. OPEN branches
|
||||||
// expand). No first-connect guard is needed: space-tree usually mounts AFTER
|
// keep their children and are refreshed by refreshOpenBranches instead, so
|
||||||
// the initial connect, so every `connect` it sees is a reconnect; the rare
|
// this runs before any expand and never double-fetches an open branch.
|
||||||
// initial-connect case has an empty tree, so the refresh is a harmless no-op.
|
const prunedBootCacheRef = useRef(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!socket) return;
|
if (prunedBootCacheRef.current) return;
|
||||||
const onConnect = async () => {
|
prunedBootCacheRef.current = true;
|
||||||
|
setData((prev) => pruneCollapsedChildren(prev, openIdsRef.current));
|
||||||
|
}, [setData]);
|
||||||
|
|
||||||
|
// Re-fetch and reconcile the children of every currently-open, already-loaded
|
||||||
|
// branch of THIS space. Shared by the socket reconnect handler and the
|
||||||
|
// post-load cache refresh below. The ROOT level is reconciled separately by
|
||||||
|
// the root-query refetch + mergeRootTrees; an UNLOADED branch is skipped
|
||||||
|
// (lazy-load fetches it fresh on expand). Reads refs so it always sees the
|
||||||
|
// latest tree/open-state/space without re-creating the callback.
|
||||||
|
const refreshOpenBranches = useCallback(async () => {
|
||||||
const effectSpaceId = spaceIdRef.current;
|
const effectSpaceId = spaceIdRef.current;
|
||||||
const branchIds = loadedOpenBranchIds(
|
const branchIds = loadedOpenBranchIds(
|
||||||
dataRef.current.filter((n) => n?.spaceId === effectSpaceId),
|
dataRef.current.filter((n) => n?.spaceId === effectSpaceId),
|
||||||
@@ -229,15 +240,41 @@ const SpaceTree = forwardRef<SpaceTreeApi, SpaceTreeProps>(function SpaceTree(
|
|||||||
if (spaceIdRef.current !== effectSpaceId) return; // space switched
|
if (spaceIdRef.current !== effectSpaceId) return; // space switched
|
||||||
setData((prev) => treeModel.reconcileChildren(prev, id, fresh));
|
setData((prev) => treeModel.reconcileChildren(prev, id, fresh));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[tree] reconnect branch refresh failed", err);
|
console.error("[tree] open branch refresh failed", err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}, [setData]);
|
||||||
|
|
||||||
|
// Reconnect refresh (#159 #8): on a socket reconnect, refresh open branches
|
||||||
|
// so a move/rename/delete that happened INSIDE a loaded branch while events
|
||||||
|
// were missed (laptop sleep / wifi gap) is reflected instead of left stale.
|
||||||
|
// No first-connect guard is needed: space-tree usually mounts AFTER the
|
||||||
|
// initial connect, so every `connect` it sees is a reconnect; the rare
|
||||||
|
// initial-connect case has an empty tree, so the refresh is a harmless no-op.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!socket) return;
|
||||||
|
const onConnect = () => {
|
||||||
|
refreshOpenBranches();
|
||||||
};
|
};
|
||||||
socket.on("connect", onConnect);
|
socket.on("connect", onConnect);
|
||||||
return () => {
|
return () => {
|
||||||
socket.off("connect", onConnect);
|
socket.off("connect", onConnect);
|
||||||
};
|
};
|
||||||
}, [socket, setData]);
|
}, [socket, refreshOpenBranches]);
|
||||||
|
|
||||||
|
// Post-load cache refresh: the sidebar paints instantly from the
|
||||||
|
// localStorage-cached tree, so children of open branches may be stale. Once
|
||||||
|
// the server root set has been merged for this space (isDataLoaded flips
|
||||||
|
// true), refresh every open, already-loaded branch ONCE per space per mount.
|
||||||
|
// dataRef.current is already up to date here: refs are assigned during
|
||||||
|
// render, and this effect runs after the merge-triggered re-render commit.
|
||||||
|
const refreshedSpacesRef = useRef<Set<string>>(new Set());
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isDataLoaded) return;
|
||||||
|
if (refreshedSpacesRef.current.has(spaceId)) return;
|
||||||
|
refreshedSpacesRef.current.add(spaceId);
|
||||||
|
refreshOpenBranches();
|
||||||
|
}, [isDataLoaded, spaceId, refreshOpenBranches]);
|
||||||
|
|
||||||
const handleToggle = useCallback(
|
const handleToggle = useCallback(
|
||||||
async (id: string, isOpen: boolean) => {
|
async (id: string, isOpen: boolean) => {
|
||||||
@@ -333,12 +370,17 @@ const SpaceTree = forwardRef<SpaceTreeApi, SpaceTreeProps>(function SpaceTree(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={classes.treeContainer}>
|
<div className={classes.treeContainer}>
|
||||||
|
{/* "No pages yet" only after the SERVER confirmed the space is empty —
|
||||||
|
never while just the localStorage cache is empty. */}
|
||||||
{isDataLoaded && filteredData.length === 0 && (
|
{isDataLoaded && filteredData.length === 0 && (
|
||||||
<Text size="xs" c="dimmed" py="xs" px="sm">
|
<Text size="xs" c="dimmed" py="xs" px="sm">
|
||||||
{t("No pages yet")}
|
{t("No pages yet")}
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
{isDataLoaded && filteredData.length > 0 && (
|
{/* Cache-first paint: render as soon as ANY data exists (synchronous
|
||||||
|
localStorage hydration) instead of waiting for the server round-trip;
|
||||||
|
the background merge/refresh reconciles it afterwards. */}
|
||||||
|
{filteredData.length > 0 && (
|
||||||
<DocTree<SpaceTreeNode>
|
<DocTree<SpaceTreeNode>
|
||||||
data={filteredData}
|
data={filteredData}
|
||||||
openIds={openIds}
|
openIds={openIds}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
closeIds,
|
closeIds,
|
||||||
mergeRootTrees,
|
mergeRootTrees,
|
||||||
loadedOpenBranchIds,
|
loadedOpenBranchIds,
|
||||||
|
pruneCollapsedChildren,
|
||||||
sortPositionKeys,
|
sortPositionKeys,
|
||||||
pageToTreeNode,
|
pageToTreeNode,
|
||||||
} from "./utils";
|
} from "./utils";
|
||||||
@@ -438,3 +439,62 @@ describe("loadedOpenBranchIds (#159 #8 reconnect refresh targets)", () => {
|
|||||||
expect(ids.sort()).toEqual(["a", "a1"]);
|
expect(ids.sort()).toEqual(["a", "a1"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("pruneCollapsedChildren", () => {
|
||||||
|
// Signature: pruneCollapsedChildren(tree: SpaceTreeNode[], openIds:
|
||||||
|
// ReadonlySet<string>): SpaceTreeNode[]. Collapsed nodes (id NOT in openIds)
|
||||||
|
// are reset to `children: []` (hasChildren untouched); open nodes keep their
|
||||||
|
// children but are recursed into so a collapsed branch nested under an open
|
||||||
|
// one is still pruned.
|
||||||
|
//
|
||||||
|
// Fixture:
|
||||||
|
// open "p" (in openIds, hasChildren)
|
||||||
|
// └─ collapsed "c" (NOT in openIds) with STALE child "g"
|
||||||
|
// collapsed "t" (NOT in openIds) with child "t1"
|
||||||
|
// Only "p" is open.
|
||||||
|
function fixture() {
|
||||||
|
const grandchild = treeNode("g"); // stale, cached under the collapsed child
|
||||||
|
const collapsedChild = treeNode("c", [grandchild]);
|
||||||
|
const openParent = treeNode("p", [collapsedChild]);
|
||||||
|
const topCollapsed = treeNode("t", [treeNode("t1")]);
|
||||||
|
return { openParent, collapsedChild, topCollapsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
it("keeps an OPEN parent's children and recurses to prune a nested collapsed branch; prunes a top-level collapsed node", () => {
|
||||||
|
const { openParent, topCollapsed } = fixture();
|
||||||
|
const tree = [openParent, topCollapsed];
|
||||||
|
const result = pruneCollapsedChildren(tree, new Set(["p"]));
|
||||||
|
|
||||||
|
// (a) OPEN parent keeps its children (not cleared) and hasChildren stays true.
|
||||||
|
const p = result[0];
|
||||||
|
expect(p.id).toBe("p");
|
||||||
|
expect(p.hasChildren).toBe(true);
|
||||||
|
expect(p.children).toHaveLength(1);
|
||||||
|
|
||||||
|
// (b) The nested COLLAPSED child under the open parent is pruned to
|
||||||
|
// `children: []` by the recursion, with hasChildren preserved. This is the
|
||||||
|
// open-keep + recurse branch that F1's empty-open-set fixture never hits.
|
||||||
|
const c = p.children[0];
|
||||||
|
expect(c.id).toBe("c");
|
||||||
|
expect(c.children).toEqual([]);
|
||||||
|
expect(c.hasChildren).toBe(true);
|
||||||
|
|
||||||
|
// (c) The top-level collapsed node is pruned to `children: []`, hasChildren kept.
|
||||||
|
const t = result[1];
|
||||||
|
expect(t.id).toBe("t");
|
||||||
|
expect(t.children).toEqual([]);
|
||||||
|
expect(t.hasChildren).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not mutate the input tree (returns fresh nodes)", () => {
|
||||||
|
const { openParent, collapsedChild, topCollapsed } = fixture();
|
||||||
|
const tree = [openParent, topCollapsed];
|
||||||
|
pruneCollapsedChildren(tree, new Set(["p"]));
|
||||||
|
|
||||||
|
// Originals are untouched: the collapsed child still carries its stale grandchild.
|
||||||
|
expect(collapsedChild.children).toHaveLength(1);
|
||||||
|
expect(collapsedChild.children[0].id).toBe("g");
|
||||||
|
expect(openParent.children[0]).toBe(collapsedChild);
|
||||||
|
expect(topCollapsed.children).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -293,6 +293,41 @@ export function loadedOpenBranchIds(
|
|||||||
return ids;
|
return ids;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Boot-cache hygiene (#159 #8): the persisted tree keeps the children of EVERY
|
||||||
|
* branch ever expanded — collapsing a branch never prunes them. So on reload a
|
||||||
|
* COLLAPSED branch hydrates with its old cached children, and `handleToggle`
|
||||||
|
* skips the lazy-load on first expand (children already present) → it shows
|
||||||
|
* STALE children (renamed / moved / deleted while the user was offline) with no
|
||||||
|
* reconcile. `refreshOpenBranches` only refreshes OPEN branches, so collapsed
|
||||||
|
* ones slip through.
|
||||||
|
*
|
||||||
|
* Fix: drop the cached children of every node NOT in the persisted open-set,
|
||||||
|
* resetting it to the canonical UNLOADED shape (`children: []`, `hasChildren`
|
||||||
|
* untouched — see pageToTreeNode). Its first expand then lazy-loads fresh, just
|
||||||
|
* as it did before the tree was cached to localStorage. OPEN branches keep
|
||||||
|
* their children (refreshOpenBranches reconciles those, so they must not be
|
||||||
|
* dropped here) and are recursed into so a collapsed branch nested under an
|
||||||
|
* open one is pruned too.
|
||||||
|
*/
|
||||||
|
export function pruneCollapsedChildren(
|
||||||
|
tree: SpaceTreeNode[],
|
||||||
|
openIds: ReadonlySet<string>,
|
||||||
|
): SpaceTreeNode[] {
|
||||||
|
return tree.map((node) => {
|
||||||
|
const hasLoadedChildren = !!node.children && node.children.length > 0;
|
||||||
|
if (!openIds.has(node.id)) {
|
||||||
|
// Collapsed: drop the whole cached subtree so it reads as unloaded.
|
||||||
|
return hasLoadedChildren ? { ...node, children: [] } : node;
|
||||||
|
}
|
||||||
|
// Open: keep it, but recurse into its children (a nested collapsed branch
|
||||||
|
// must still be pruned).
|
||||||
|
return hasLoadedChildren
|
||||||
|
? { ...node, children: pruneCollapsedChildren(node.children, openIds) }
|
||||||
|
: node;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Collect every node id in the tree (roots, branches, leaves). Used by
|
// Collect every node id in the tree (roots, branches, leaves). Used by
|
||||||
// collapseAll to clear the open-state map for all current-space nodes.
|
// collapseAll to clear the open-state map for all current-space nodes.
|
||||||
export function collectAllIds(nodes: SpaceTreeNode[]): string[] {
|
export function collectAllIds(nodes: SpaceTreeNode[]): string[] {
|
||||||
|
|||||||
@@ -0,0 +1,240 @@
|
|||||||
|
import {
|
||||||
|
describe,
|
||||||
|
it,
|
||||||
|
expect,
|
||||||
|
vi,
|
||||||
|
beforeAll,
|
||||||
|
afterEach,
|
||||||
|
} from "vitest";
|
||||||
|
import {
|
||||||
|
render,
|
||||||
|
screen,
|
||||||
|
cleanup,
|
||||||
|
fireEvent,
|
||||||
|
waitFor,
|
||||||
|
} from "@testing-library/react";
|
||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
|
||||||
|
// --- Mocks for the heavy / networked module graph ---------------------------
|
||||||
|
// EditSpaceForm wires the "Enable Git sync" Switch to a TanStack-Query mutation
|
||||||
|
// (useUpdateSpaceMutation). We mock ONLY that hook so the test fully controls
|
||||||
|
// mutateAsync (resolve / reject) and isPending, and stub i18n. The real Mantine
|
||||||
|
// Switch is rendered so the checkbox role / disabled state is meaningful.
|
||||||
|
|
||||||
|
// i18n: identity translator — labels stay as their English keys for queries.
|
||||||
|
vi.mock("react-i18next", () => ({
|
||||||
|
useTranslation: () => ({ t: (key: string) => key }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mutation hook: a controllable mutateAsync plus a togglable isPending.
|
||||||
|
const mutateAsync = vi.fn();
|
||||||
|
let isPending = false;
|
||||||
|
vi.mock("@/features/space/queries/space-query.ts", () => ({
|
||||||
|
useUpdateSpaceMutation: () => ({
|
||||||
|
mutateAsync,
|
||||||
|
get isPending() {
|
||||||
|
return isPending;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// jsdom lacks matchMedia, which MantineProvider's color-scheme hook needs.
|
||||||
|
beforeAll(() => {
|
||||||
|
if (!window.matchMedia) {
|
||||||
|
window.matchMedia = (query: string) =>
|
||||||
|
({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addListener: () => {},
|
||||||
|
removeListener: () => {},
|
||||||
|
addEventListener: () => {},
|
||||||
|
removeEventListener: () => {},
|
||||||
|
dispatchEvent: () => false,
|
||||||
|
}) as unknown as MediaQueryList;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
import { EditSpaceForm } from "./edit-space-form";
|
||||||
|
import type { ISpace } from "@/features/space/types/space.types.ts";
|
||||||
|
|
||||||
|
function makeSpace(overrides: Partial<ISpace> = {}): ISpace {
|
||||||
|
return {
|
||||||
|
id: "space-1",
|
||||||
|
name: "Engineering",
|
||||||
|
description: "",
|
||||||
|
slug: "eng",
|
||||||
|
hostname: "host",
|
||||||
|
creatorId: "u1",
|
||||||
|
createdAt: new Date("2026-01-01"),
|
||||||
|
updatedAt: new Date("2026-01-01"),
|
||||||
|
...overrides,
|
||||||
|
} as ISpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderForm(props: { space: ISpace; readOnly?: boolean }) {
|
||||||
|
return render(
|
||||||
|
<MantineProvider>
|
||||||
|
<EditSpaceForm space={props.space} readOnly={props.readOnly} />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The form now renders TWO switches (git-sync enable + auto-merge-conflicts) in
|
||||||
|
// that DOM order. Mantine renders each as an <input type="checkbox"
|
||||||
|
// role="switch"> but does NOT expose its label as the accessible name, so we
|
||||||
|
// disambiguate by DOM order (index 0 = enable, 1 = auto-merge) and assert the
|
||||||
|
// human-readable label text is present alongside.
|
||||||
|
function getToggle(): HTMLInputElement {
|
||||||
|
screen.getByText("Enable Git sync");
|
||||||
|
return screen.getAllByRole("switch")[0] as HTMLInputElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAutoMergeToggle(): HTMLInputElement {
|
||||||
|
screen.getByText("Auto-merge conflicts on push");
|
||||||
|
return screen.getAllByRole("switch")[1] as HTMLInputElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
mutateAsync.mockReset();
|
||||||
|
isPending = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("EditSpaceForm git-sync toggle", () => {
|
||||||
|
// Test 3: initial checked state derives from settings.gitSync.enabled ?? false.
|
||||||
|
it("derives initial checked state from space.settings.gitSync.enabled (true -> checked)", () => {
|
||||||
|
renderForm({
|
||||||
|
space: makeSpace({ settings: { gitSync: { enabled: true } } }),
|
||||||
|
});
|
||||||
|
expect(getToggle().checked).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defaults to unchecked when gitSync settings are missing", () => {
|
||||||
|
renderForm({ space: makeSpace() });
|
||||||
|
expect(getToggle().checked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test 4: toggling fires the mutation with { spaceId, gitSyncEnabled } and
|
||||||
|
// optimistically flips the switch.
|
||||||
|
it("fires the mutation with the correct payload and optimistically flips on", async () => {
|
||||||
|
mutateAsync.mockResolvedValue(undefined);
|
||||||
|
renderForm({ space: makeSpace() });
|
||||||
|
|
||||||
|
const toggle = getToggle();
|
||||||
|
expect(toggle.checked).toBe(false);
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
|
||||||
|
// Optimistic update: the switch reflects the new state immediately.
|
||||||
|
expect(toggle.checked).toBe(true);
|
||||||
|
|
||||||
|
expect(mutateAsync).toHaveBeenCalledTimes(1);
|
||||||
|
expect(mutateAsync).toHaveBeenCalledWith({
|
||||||
|
spaceId: "space-1",
|
||||||
|
gitSyncEnabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Resolution leaves the toggle on.
|
||||||
|
await waitFor(() => expect(toggle.checked).toBe(true));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test 5: rollback on mutation error — the most valuable test.
|
||||||
|
it("rolls back the toggle to its prior state when the mutation rejects", async () => {
|
||||||
|
mutateAsync.mockRejectedValue(new Error("network"));
|
||||||
|
renderForm({
|
||||||
|
space: makeSpace({ settings: { gitSync: { enabled: false } } }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const toggle = getToggle();
|
||||||
|
expect(toggle.checked).toBe(false);
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
|
||||||
|
// Optimistically flips on before the rejection lands.
|
||||||
|
expect(toggle.checked).toBe(true);
|
||||||
|
expect(mutateAsync).toHaveBeenCalledWith({
|
||||||
|
spaceId: "space-1",
|
||||||
|
gitSyncEnabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// After the rejected promise settles, the component reverts to OFF so the
|
||||||
|
// user is not misled into believing sync is enabled.
|
||||||
|
await waitFor(() => expect(toggle.checked).toBe(false));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test 6: disabled when readOnly and when the mutation is pending.
|
||||||
|
it("disables the toggle when readOnly", () => {
|
||||||
|
renderForm({ space: makeSpace(), readOnly: true });
|
||||||
|
expect(getToggle().disabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disables the toggle while the mutation is pending", () => {
|
||||||
|
isPending = true;
|
||||||
|
renderForm({ space: makeSpace() });
|
||||||
|
expect(getToggle().disabled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("EditSpaceForm auto-merge-conflicts toggle", () => {
|
||||||
|
it("derives initial checked state from space.settings.gitSync.autoMergeConflicts (true -> checked)", () => {
|
||||||
|
renderForm({
|
||||||
|
space: makeSpace({
|
||||||
|
settings: { gitSync: { autoMergeConflicts: true } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(getAutoMergeToggle().checked).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defaults to unchecked when autoMergeConflicts is missing (SAFE default)", () => {
|
||||||
|
renderForm({ space: makeSpace() });
|
||||||
|
expect(getAutoMergeToggle().checked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("fires the mutation with { spaceId, autoMergeConflicts } and optimistically flips on", async () => {
|
||||||
|
mutateAsync.mockResolvedValue(undefined);
|
||||||
|
renderForm({ space: makeSpace() });
|
||||||
|
|
||||||
|
const toggle = getAutoMergeToggle();
|
||||||
|
expect(toggle.checked).toBe(false);
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
|
||||||
|
// Optimistic update.
|
||||||
|
expect(toggle.checked).toBe(true);
|
||||||
|
expect(mutateAsync).toHaveBeenCalledTimes(1);
|
||||||
|
expect(mutateAsync).toHaveBeenCalledWith({
|
||||||
|
spaceId: "space-1",
|
||||||
|
autoMergeConflicts: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => expect(toggle.checked).toBe(true));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rolls back to its prior state when the mutation rejects", async () => {
|
||||||
|
mutateAsync.mockRejectedValue(new Error("network"));
|
||||||
|
renderForm({
|
||||||
|
space: makeSpace({
|
||||||
|
settings: { gitSync: { autoMergeConflicts: false } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const toggle = getAutoMergeToggle();
|
||||||
|
expect(toggle.checked).toBe(false);
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
|
||||||
|
expect(toggle.checked).toBe(true);
|
||||||
|
expect(mutateAsync).toHaveBeenCalledWith({
|
||||||
|
spaceId: "space-1",
|
||||||
|
autoMergeConflicts: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => expect(toggle.checked).toBe(false));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disables the toggle when readOnly", () => {
|
||||||
|
renderForm({ space: makeSpace(), readOnly: true });
|
||||||
|
expect(getAutoMergeToggle().disabled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,14 @@
|
|||||||
import { Group, Box, Button, TextInput, Stack, Textarea } from "@mantine/core";
|
import {
|
||||||
import React from "react";
|
Group,
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
TextInput,
|
||||||
|
Stack,
|
||||||
|
Textarea,
|
||||||
|
Divider,
|
||||||
|
Switch,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import React, { useState } from "react";
|
||||||
import { useForm } from "@mantine/form";
|
import { useForm } from "@mantine/form";
|
||||||
import { zod4Resolver } from "mantine-form-zod-resolver";
|
import { zod4Resolver } from "mantine-form-zod-resolver";
|
||||||
import { z } from "zod/v4";
|
import { z } from "zod/v4";
|
||||||
@@ -29,6 +38,37 @@ export function EditSpaceForm({ space, readOnly }: EditSpaceFormProps) {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const updateSpaceMutation = useUpdateSpaceMutation();
|
const updateSpaceMutation = useUpdateSpaceMutation();
|
||||||
|
|
||||||
|
const [gitSyncEnabled, setGitSyncEnabled] = useState<boolean>(
|
||||||
|
space?.settings?.gitSync?.enabled ?? false,
|
||||||
|
);
|
||||||
|
|
||||||
|
const [autoMergeConflicts, setAutoMergeConflicts] = useState<boolean>(
|
||||||
|
space?.settings?.gitSync?.autoMergeConflicts ?? false,
|
||||||
|
);
|
||||||
|
|
||||||
|
// One parameterized handler for both git-sync space toggles: they differ only by
|
||||||
|
// the local state setter, the mutation payload field, and the error label. The
|
||||||
|
// update is optimistic and reverts the local state on failure (the mutation
|
||||||
|
// surfaces a toast via onError; the raw error is still logged per AGENTS.md).
|
||||||
|
const handleToggle = async (
|
||||||
|
field: "gitSyncEnabled" | "autoMergeConflicts",
|
||||||
|
value: boolean,
|
||||||
|
previous: boolean,
|
||||||
|
setLocal: (next: boolean) => void,
|
||||||
|
errorLabel: string,
|
||||||
|
) => {
|
||||||
|
setLocal(value); // optimistic update
|
||||||
|
try {
|
||||||
|
await updateSpaceMutation.mutateAsync({
|
||||||
|
spaceId: space.id,
|
||||||
|
[field]: value,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
setLocal(previous); // revert on failure
|
||||||
|
console.error(errorLabel, err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const form = useForm<FormValues>({
|
const form = useForm<FormValues>({
|
||||||
validate: zod4Resolver(formSchema),
|
validate: zod4Resolver(formSchema),
|
||||||
initialValues: {
|
initialValues: {
|
||||||
@@ -104,6 +144,43 @@ export function EditSpaceForm({ space, readOnly }: EditSpaceFormProps) {
|
|||||||
</Group>
|
</Group>
|
||||||
)}
|
)}
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<Divider my="lg" />
|
||||||
|
|
||||||
|
<Switch
|
||||||
|
label={t("Enable Git sync")}
|
||||||
|
description={t("Sync this space's pages to a Git repository.")}
|
||||||
|
checked={gitSyncEnabled}
|
||||||
|
disabled={readOnly || updateSpaceMutation.isPending}
|
||||||
|
onChange={(event) =>
|
||||||
|
handleToggle(
|
||||||
|
"gitSyncEnabled",
|
||||||
|
event.currentTarget.checked,
|
||||||
|
gitSyncEnabled,
|
||||||
|
setGitSyncEnabled,
|
||||||
|
"Failed to toggle git-sync for space",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Switch
|
||||||
|
mt="md"
|
||||||
|
label={t("Auto-merge conflicts on push")}
|
||||||
|
description={t(
|
||||||
|
"When off (recommended), a page whose content still has unresolved Git conflict markers is skipped on push until you resolve the conflict in Git. When on, the markers are stripped and both sides' content is pushed.",
|
||||||
|
)}
|
||||||
|
checked={autoMergeConflicts}
|
||||||
|
disabled={readOnly || updateSpaceMutation.isPending}
|
||||||
|
onChange={(event) =>
|
||||||
|
handleToggle(
|
||||||
|
"autoMergeConflicts",
|
||||||
|
event.currentTarget.checked,
|
||||||
|
autoMergeConflicts,
|
||||||
|
setAutoMergeConflicts,
|
||||||
|
"Failed to toggle git-sync auto-merge-conflicts",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,9 +13,15 @@ export interface ISpaceCommentsSettings {
|
|||||||
allowViewerComments?: boolean;
|
allowViewerComments?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ISpaceGitSyncSettings {
|
||||||
|
enabled?: boolean;
|
||||||
|
autoMergeConflicts?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ISpaceSettings {
|
export interface ISpaceSettings {
|
||||||
sharing?: ISpaceSharingSettings;
|
sharing?: ISpaceSharingSettings;
|
||||||
comments?: ISpaceCommentsSettings;
|
comments?: ISpaceCommentsSettings;
|
||||||
|
gitSync?: ISpaceGitSyncSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ISpace {
|
export interface ISpace {
|
||||||
@@ -35,6 +41,8 @@ export interface ISpace {
|
|||||||
// for updates
|
// for updates
|
||||||
disablePublicSharing?: boolean;
|
disablePublicSharing?: boolean;
|
||||||
allowViewerComments?: boolean;
|
allowViewerComments?: boolean;
|
||||||
|
gitSyncEnabled?: boolean;
|
||||||
|
autoMergeConflicts?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IMembership {
|
interface IMembership {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import axios, { AxiosInstance } from "axios";
|
import axios, { AxiosInstance } from "axios";
|
||||||
import APP_ROUTE from "@/lib/app-route.ts";
|
import APP_ROUTE from "@/lib/app-route.ts";
|
||||||
import { isCloud } from "@/lib/config.ts";
|
import { isCloud } from "@/lib/config.ts";
|
||||||
|
import { clearPersistedTreeCaches } from "@/features/page/tree/atoms/tree-data-atom";
|
||||||
|
|
||||||
const api: AxiosInstance = axios.create({
|
const api: AxiosInstance = axios.create({
|
||||||
baseURL: "/api",
|
baseURL: "/api",
|
||||||
@@ -71,6 +72,12 @@ function redirectToLogin() {
|
|||||||
"/invites",
|
"/invites",
|
||||||
];
|
];
|
||||||
if (!exemptPaths.some((path) => window.location.pathname.startsWith(path))) {
|
if (!exemptPaths.some((path) => window.location.pathname.startsWith(path))) {
|
||||||
|
// Forced logout (401 / expired session) must purge the persisted sidebar
|
||||||
|
// tree caches too: they contain page titles, and on a shared machine most
|
||||||
|
// sessions end via cookie expiry — not the logout button — so this is the
|
||||||
|
// only cleanup that runs on that path. It also disables further cache
|
||||||
|
// persistence until the full page load below.
|
||||||
|
clearPersistedTreeCaches();
|
||||||
const redirectTo = window.location.pathname;
|
const redirectTo = window.location.pathname;
|
||||||
if (redirectTo === APP_ROUTE.HOME) {
|
if (redirectTo === APP_ROUTE.HOME) {
|
||||||
window.location.href = APP_ROUTE.AUTH.LOGIN;
|
window.location.href = APP_ROUTE.AUTH.LOGIN;
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import {
|
||||||
|
PALETTE,
|
||||||
|
avatarStyle,
|
||||||
|
avatarBackgroundCss,
|
||||||
|
normalizeName,
|
||||||
|
minPairwiseDistance,
|
||||||
|
relativeLuminance,
|
||||||
|
contrastRatio,
|
||||||
|
oklchToSrgb,
|
||||||
|
isInGamut,
|
||||||
|
} from "./avatar-palette";
|
||||||
|
|
||||||
|
/** Parse "#rrggbb" into sRGB components on the 0..1 scale relativeLuminance expects. */
|
||||||
|
function hexToRgb01(hex: string): [number, number, number] {
|
||||||
|
return [
|
||||||
|
parseInt(hex.slice(1, 3), 16) / 255,
|
||||||
|
parseInt(hex.slice(3, 5), 16) / 255,
|
||||||
|
parseInt(hex.slice(5, 7), 16) / 255,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("avatar-palette validation", () => {
|
||||||
|
it("palette colors stay distinguishable", () => {
|
||||||
|
// 0.06 in OKLab is ~4-5 JNDs — safely distinct at avatar size. If a future
|
||||||
|
// RINGS tweak drops this, "almost identical" colors would reappear.
|
||||||
|
expect(minPairwiseDistance().distance).toBeGreaterThanOrEqual(0.06);
|
||||||
|
expect(PALETTE.length).toBe(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("every palette entry is WCAG-readable and in sRGB gamut", () => {
|
||||||
|
// white text = luminance 1, black text = luminance 0 (per buildPalette).
|
||||||
|
const textLum = { white: 1, black: 0 } as const;
|
||||||
|
for (const entry of PALETTE) {
|
||||||
|
expect(entry.hex).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
|
||||||
|
// (a) The chosen text color really clears the code's 3:1 threshold on the
|
||||||
|
// actual background hex — recomputed independently from the hex, not from
|
||||||
|
// the build-time luminance. A slot that picked the wrong text (or a color
|
||||||
|
// too dim for either text) would fail here.
|
||||||
|
const hexLum = relativeLuminance(hexToRgb01(entry.hex));
|
||||||
|
const chosen = contrastRatio(textLum[entry.text], hexLum);
|
||||||
|
expect(chosen).toBeGreaterThanOrEqual(3);
|
||||||
|
// buildPalette prefers white and only falls back to black when white
|
||||||
|
// fails 3:1. Mirror that decision: black is used *only* when white would
|
||||||
|
// not clear the threshold — so a mis-assigned "black" on a dark color
|
||||||
|
// (where white was fine) fails here.
|
||||||
|
if (entry.text === "black") {
|
||||||
|
expect(contrastRatio(textLum.white, hexLum)).toBeLessThan(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// (b) The entry's OKLCH is inside the sRGB gamut after chroma clamping;
|
||||||
|
// an out-of-gamut slot (e.g. un-clamped chroma) would produce components
|
||||||
|
// outside [0,1] and fail here.
|
||||||
|
expect(isInGamut(oklchToSrgb(entry.L, entry.C, entry.h))).toBe(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("avatarStyle", () => {
|
||||||
|
it("name-to-avatar mapping is frozen (golden values)", () => {
|
||||||
|
// Golden slice: if this breaks, all existing avatars change — make sure
|
||||||
|
// that is intentional (a config change in avatar-palette.ts).
|
||||||
|
const s = avatarStyle("Backend Developer");
|
||||||
|
expect([s.bg, s.bg2, s.angleDeg]).toEqual(["#a55795", "#90355e", 150]);
|
||||||
|
expect(s.text).toBe("white");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is deterministic and normalizes the name", () => {
|
||||||
|
expect(avatarStyle("Researcher")).toEqual(avatarStyle("Researcher"));
|
||||||
|
// Casing, surrounding and repeated whitespace must not change the avatar.
|
||||||
|
expect(avatarStyle(" RESEARCHER ")).toEqual(avatarStyle("researcher"));
|
||||||
|
expect(avatarStyle("Backend Developer")).toEqual(
|
||||||
|
avatarStyle("backend developer"),
|
||||||
|
);
|
||||||
|
expect(normalizeName(" PM ")).toBe("pm");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns a valid base color, angle and matching text", () => {
|
||||||
|
const s = avatarStyle("Нарратор");
|
||||||
|
const idx = PALETTE.findIndex((e) => e.hex === s.bg);
|
||||||
|
expect(idx).toBe(s.paletteIndex);
|
||||||
|
expect(idx).toBeGreaterThanOrEqual(0); // bg is a palette entry
|
||||||
|
// Text color comes from the chosen palette entry.
|
||||||
|
expect(s.text).toBe(PALETTE[idx].text);
|
||||||
|
// Split angle is one of the SPLIT_ANGLE_STEPS (24) directions → multiples of 15.
|
||||||
|
expect(s.angleDeg % 15).toBe(0);
|
||||||
|
expect(s.angleDeg).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(s.angleDeg).toBeLessThan(360);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("distinguishes the agents that used to collide as violet", () => {
|
||||||
|
// "Структурный редактор" and "Фактчекер" looked identically violet before.
|
||||||
|
expect(avatarStyle("Структурный редактор")).not.toEqual(
|
||||||
|
avatarStyle("Фактчекер"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("avatarBackgroundCss", () => {
|
||||||
|
it("renders a two-stop gradient with a soft boundary", () => {
|
||||||
|
const s = avatarStyle("Backend Developer");
|
||||||
|
expect(avatarBackgroundCss(s)).toBe(
|
||||||
|
"linear-gradient(150deg, #a55795 42%, #90355e 58%)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
/**
|
||||||
|
* Deterministic avatar backgrounds for agent roles.
|
||||||
|
*
|
||||||
|
* The palette is generated from scratch at module load in OKLCH (a perceptually
|
||||||
|
* uniform color space), so every value below is tunable: change the ring
|
||||||
|
* configuration or the partner shifts and the whole palette regenerates.
|
||||||
|
*
|
||||||
|
* Pipeline: name -> normalize -> cyrb53 hash -> split into independent fields:
|
||||||
|
* - base color index (one of the validated palette colors)
|
||||||
|
* - partner hue shift: analogous 20..45deg (either side), complementary 180deg,
|
||||||
|
* or triadic +/-120deg — classic color-wheel schemes; partner is also darker
|
||||||
|
* - split angle (SPLIT_ANGLE_STEPS directions, soft boundary)
|
||||||
|
* The same name always yields the same avatar, on any platform, forever.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ------------------------- Tunable configuration -------------------------
|
||||||
|
|
||||||
|
export interface RingConfig {
|
||||||
|
/** OKLCH lightness, 0..1 */
|
||||||
|
L: number;
|
||||||
|
/** OKLCH chroma target; clamped down per-hue to fit the sRGB gamut */
|
||||||
|
C: number;
|
||||||
|
/** Hue of the first color in the ring, degrees */
|
||||||
|
hueStart: number;
|
||||||
|
/** Number of evenly spaced hues in the ring */
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Two lightness rings. 12 light + 8 dark = 20 base colors with a validated
|
||||||
|
* min pairwise deltaE-OK of ~0.066 (clearly distinguishable at avatar size).
|
||||||
|
* Don't add more hues per ring without re-checking minPairwiseDistance():
|
||||||
|
* beyond ~20-24 colors humans stop telling them apart reliably.
|
||||||
|
*/
|
||||||
|
const RINGS: readonly RingConfig[] = [
|
||||||
|
{ L: 0.70, C: 0.14, hueStart: 15, count: 12 }, // light ring
|
||||||
|
{ L: 0.57, C: 0.13, hueStart: 20, count: 8 }, // darker ring
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Partner color: lightness shifted by this much (negative = darker) */
|
||||||
|
const PARTNER_L_SHIFT = -0.10;
|
||||||
|
/** Analogous scheme: hue shift magnitude range, degrees (inclusive, 5-deg steps) */
|
||||||
|
const ANALOG_MIN_SHIFT = 20;
|
||||||
|
const ANALOG_SHIFT_STEP = 5;
|
||||||
|
const ANALOG_SHIFT_STEPS = 6; // 20, 25, 30, 35, 40, 45
|
||||||
|
/** Complementary scheme: fixed hue shift, degrees */
|
||||||
|
const COMPLEMENTARY_SHIFT = 180;
|
||||||
|
/** Triadic scheme: fixed hue shift magnitude, degrees (either side) */
|
||||||
|
const TRIADIC_SHIFT = 120;
|
||||||
|
/** Number of split directions (24 -> 15deg per step) */
|
||||||
|
const SPLIT_ANGLE_STEPS = 24;
|
||||||
|
/** Position of the color boundary, percent of the gradient axis */
|
||||||
|
const SPLIT_PERCENT = 50;
|
||||||
|
/** Width of the soft transition zone around the boundary, percent (0 = hard edge) */
|
||||||
|
const SPLIT_SOFTNESS = 16;
|
||||||
|
|
||||||
|
// ------------------------- OKLCH -> sRGB math -------------------------
|
||||||
|
// Matrices from Bjorn Ottosson's OKLab reference implementation.
|
||||||
|
|
||||||
|
function oklabToLinearSrgb(L: number, a: number, b: number): [number, number, number] {
|
||||||
|
const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
|
||||||
|
const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
|
||||||
|
const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
|
||||||
|
const l = l_ ** 3, m = m_ ** 3, s = s_ ** 3;
|
||||||
|
return [
|
||||||
|
+4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
|
||||||
|
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
|
||||||
|
-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function gammaEncode(c: number): number {
|
||||||
|
return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function oklchToSrgb(L: number, C: number, hDeg: number): [number, number, number] {
|
||||||
|
const h = (hDeg * Math.PI) / 180;
|
||||||
|
const [r, g, b] = oklabToLinearSrgb(L, C * Math.cos(h), C * Math.sin(h));
|
||||||
|
return [gammaEncode(r), gammaEncode(g), gammaEncode(b)];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isInGamut(rgb: readonly number[]): boolean {
|
||||||
|
return rgb.every((c) => c >= -1e-6 && c <= 1 + 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Binary-search the max chroma <= C that fits into the sRGB gamut. */
|
||||||
|
function clampChroma(L: number, C: number, hDeg: number): number {
|
||||||
|
if (isInGamut(oklchToSrgb(L, C, hDeg))) return C;
|
||||||
|
let lo = 0, hi = C;
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
const mid = (lo + hi) / 2;
|
||||||
|
if (isInGamut(oklchToSrgb(L, mid, hDeg))) lo = mid;
|
||||||
|
else hi = mid;
|
||||||
|
}
|
||||||
|
return lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHex(rgb: readonly number[]): string {
|
||||||
|
return (
|
||||||
|
"#" +
|
||||||
|
rgb
|
||||||
|
.map((c) => Math.round(Math.min(1, Math.max(0, c)) * 255).toString(16).padStart(2, "0"))
|
||||||
|
.join("")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WCAG relative luminance of an sRGB color (components 0..1). */
|
||||||
|
export function relativeLuminance(rgb: readonly number[]): number {
|
||||||
|
const lin = rgb.map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
|
||||||
|
return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function contrastRatio(l1: number, l2: number): number {
|
||||||
|
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------- Palette generation -------------------------
|
||||||
|
|
||||||
|
export interface PaletteEntry {
|
||||||
|
/** Base background color */
|
||||||
|
hex: string;
|
||||||
|
/** OKLCH coordinates of the base color (used to derive partner colors) */
|
||||||
|
L: number;
|
||||||
|
C: number;
|
||||||
|
h: number;
|
||||||
|
/** Text/icon color with the best WCAG contrast on the base color */
|
||||||
|
text: "white" | "black";
|
||||||
|
/** OKLab coordinates of the base color (kept for validation) */
|
||||||
|
lab: readonly [number, number, number];
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPalette(): PaletteEntry[] {
|
||||||
|
const entries: PaletteEntry[] = [];
|
||||||
|
for (const ring of RINGS) {
|
||||||
|
const step = 360 / ring.count;
|
||||||
|
for (let i = 0; i < ring.count; i++) {
|
||||||
|
const h = (ring.hueStart + i * step) % 360;
|
||||||
|
const C = clampChroma(ring.L, ring.C, h);
|
||||||
|
const rgb = oklchToSrgb(ring.L, C, h);
|
||||||
|
const lum = relativeLuminance(rgb);
|
||||||
|
entries.push({
|
||||||
|
hex: toHex(rgb),
|
||||||
|
L: ring.L,
|
||||||
|
C,
|
||||||
|
h,
|
||||||
|
// White text needs >= 3:1 contrast; otherwise fall back to black.
|
||||||
|
text: contrastRatio(lum, 1) >= 3 ? "white" : "black",
|
||||||
|
lab: [
|
||||||
|
ring.L,
|
||||||
|
C * Math.cos((h * Math.PI) / 180),
|
||||||
|
C * Math.sin((h * Math.PI) / 180),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Partner color for the split: base hue shifted by shiftDeg, darker by PARTNER_L_SHIFT. */
|
||||||
|
function partnerHex(entry: PaletteEntry, shiftDeg: number): string {
|
||||||
|
const h2 = (entry.h + shiftDeg + 360) % 360;
|
||||||
|
const L2 = entry.L + PARTNER_L_SHIFT;
|
||||||
|
return toHex(oklchToSrgb(L2, clampChroma(L2, entry.C, h2), h2));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Generated once at module load; regenerates on every build from the config above. */
|
||||||
|
export const PALETTE: readonly PaletteEntry[] = buildPalette();
|
||||||
|
|
||||||
|
// ------------------------- Name -> avatar style -------------------------
|
||||||
|
|
||||||
|
/** Normalize so that "PM ", "pm" and "Pm" map to the same avatar. */
|
||||||
|
export function normalizeName(name: string): string {
|
||||||
|
return name.normalize("NFC").trim().toLowerCase().replace(/\s+/g, " ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* cyrb53: deterministic 53-bit string hash with good avalanche.
|
||||||
|
* Pure JS, cross-platform — never use language built-in hashing here.
|
||||||
|
*/
|
||||||
|
function cyrb53(str: string, seed = 0): number {
|
||||||
|
let h1 = 0xdeadbeef ^ seed;
|
||||||
|
let h2 = 0x41c6ce57 ^ seed;
|
||||||
|
for (let i = 0; i < str.length; i++) {
|
||||||
|
const ch = str.charCodeAt(i);
|
||||||
|
h1 = Math.imul(h1 ^ ch, 2654435761);
|
||||||
|
h2 = Math.imul(h2 ^ ch, 1597334677);
|
||||||
|
}
|
||||||
|
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
||||||
|
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
||||||
|
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AvatarStyle {
|
||||||
|
/** Index of the base color in PALETTE */
|
||||||
|
paletteIndex: number;
|
||||||
|
/** Base color hex */
|
||||||
|
bg: string;
|
||||||
|
/** Second color hex (split partner) */
|
||||||
|
bg2: string;
|
||||||
|
/** Signed hue shift of the partner, degrees (e.g. -35, +45, 180, -120) */
|
||||||
|
hueShift: number;
|
||||||
|
/** Direction of the split, degrees */
|
||||||
|
angleDeg: number;
|
||||||
|
/** Text/icon color for the base color */
|
||||||
|
text: "white" | "black";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pure function: the same (normalized) name always returns the same style. */
|
||||||
|
export function avatarStyle(agentName: string): AvatarStyle {
|
||||||
|
const h = cyrb53(normalizeName(agentName));
|
||||||
|
// Slice the hash into independent fields, like digits of a number:
|
||||||
|
const paletteIndex = h % PALETTE.length;
|
||||||
|
let rest = Math.floor(h / PALETTE.length);
|
||||||
|
const angleDeg = (rest % SPLIT_ANGLE_STEPS) * (360 / SPLIT_ANGLE_STEPS);
|
||||||
|
rest = Math.floor(rest / SPLIT_ANGLE_STEPS);
|
||||||
|
// Scheme: 0,1 -> analogous (minus/plus); 2 -> complementary; 3 -> triadic
|
||||||
|
const scheme = rest % 4;
|
||||||
|
rest = Math.floor(rest / 4);
|
||||||
|
let hueShift: number;
|
||||||
|
if (scheme === 2) {
|
||||||
|
hueShift = COMPLEMENTARY_SHIFT;
|
||||||
|
} else if (scheme === 3) {
|
||||||
|
hueShift = rest % 2 ? TRIADIC_SHIFT : -TRIADIC_SHIFT;
|
||||||
|
} else {
|
||||||
|
const magnitude = ANALOG_MIN_SHIFT + (rest % ANALOG_SHIFT_STEPS) * ANALOG_SHIFT_STEP;
|
||||||
|
hueShift = scheme === 0 ? -magnitude : magnitude;
|
||||||
|
}
|
||||||
|
const entry = PALETTE[paletteIndex];
|
||||||
|
return {
|
||||||
|
paletteIndex,
|
||||||
|
bg: entry.hex,
|
||||||
|
bg2: partnerHex(entry, hueShift),
|
||||||
|
hueShift,
|
||||||
|
angleDeg,
|
||||||
|
text: entry.text,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** CSS background value: two colors with a slightly blurred boundary. */
|
||||||
|
export function avatarBackgroundCss(style: AvatarStyle): string {
|
||||||
|
const from = SPLIT_PERCENT - SPLIT_SOFTNESS / 2;
|
||||||
|
const to = SPLIT_PERCENT + SPLIT_SOFTNESS / 2;
|
||||||
|
return `linear-gradient(${style.angleDeg}deg, ${style.bg} ${from}%, ${style.bg2} ${to}%)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------- Validation -------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Min pairwise deltaE-OK (euclidean distance in OKLab) between base colors.
|
||||||
|
* Re-check after tweaking RINGS: keep it >= ~0.06 so no two palette colors
|
||||||
|
* look alike. Intended for a unit test or a dev-time assertion.
|
||||||
|
*/
|
||||||
|
export function minPairwiseDistance(): { distance: number; pair: [string, string] } {
|
||||||
|
let min = Infinity;
|
||||||
|
let pair: [string, string] = ["", ""];
|
||||||
|
for (let i = 0; i < PALETTE.length; i++) {
|
||||||
|
for (let j = i + 1; j < PALETTE.length; j++) {
|
||||||
|
const a = PALETTE[i].lab, b = PALETTE[j].lab;
|
||||||
|
const d = Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
||||||
|
if (d < min) {
|
||||||
|
min = d;
|
||||||
|
pair = [PALETTE[i].hex, PALETTE[j].hex];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { distance: min, pair };
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
"migration:reset": "tsx src/database/migrate.ts down-to NO_MIGRATIONS",
|
"migration:reset": "tsx src/database/migrate.ts down-to NO_MIGRATIONS",
|
||||||
"migration:codegen": "kysely-codegen --dialect=postgres --camel-case --env-file=../../.env --out-file=./src/database/types/db.d.ts",
|
"migration:codegen": "kysely-codegen --dialect=postgres --camel-case --env-file=../../.env --out-file=./src/database/types/db.d.ts",
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
"pretest": "pnpm --filter @docmost/editor-ext build",
|
"pretest": "pnpm --filter @docmost/editor-ext build && pnpm --filter @docmost/git-sync build && pnpm --filter @docmost/mcp build",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
"test:int": "jest --config test/jest-integration.json",
|
"test:int": "jest --config test/jest-integration.json",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
@@ -41,6 +41,7 @@
|
|||||||
"@aws-sdk/s3-request-presigner": "3.1050.0",
|
"@aws-sdk/s3-request-presigner": "3.1050.0",
|
||||||
"@azure/storage-blob": "12.31.0",
|
"@azure/storage-blob": "12.31.0",
|
||||||
"@clickhouse/client": "^1.18.2",
|
"@clickhouse/client": "^1.18.2",
|
||||||
|
"@docmost/git-sync": "workspace:*",
|
||||||
"@docmost/mcp": "workspace:*",
|
"@docmost/mcp": "workspace:*",
|
||||||
"@docmost/pdf-inspector": "1.9.6",
|
"@docmost/pdf-inspector": "1.9.6",
|
||||||
"@fastify/cookie": "^11.0.2",
|
"@fastify/cookie": "^11.0.2",
|
||||||
@@ -189,7 +190,12 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"^.+\\.(t|j)sx?$": "ts-jest"
|
"^.+\\.(t|j)sx?$": [
|
||||||
|
"ts-jest",
|
||||||
|
{
|
||||||
|
"isolatedModules": true
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"transformIgnorePatterns": [
|
"transformIgnorePatterns": [
|
||||||
"/node_modules/(?!(\\.pnpm/)?(nanoid|uuid|image-dimensions|marked|happy-dom|lib0)(@|/))"
|
"/node_modules/(?!(\\.pnpm/)?(nanoid|uuid|image-dimensions|marked|happy-dom|lib0)(@|/))"
|
||||||
@@ -199,11 +205,17 @@
|
|||||||
],
|
],
|
||||||
"coverageDirectory": "../coverage",
|
"coverageDirectory": "../coverage",
|
||||||
"testEnvironment": "node",
|
"testEnvironment": "node",
|
||||||
|
"setupFiles": [
|
||||||
|
"<rootDir>/../test/jest.setup.ts"
|
||||||
|
],
|
||||||
"moduleNameMapper": {
|
"moduleNameMapper": {
|
||||||
"^@docmost/db/(.*)$": "<rootDir>/database/$1",
|
"^@docmost/db/(.*)$": "<rootDir>/database/$1",
|
||||||
"^@docmost/transactional/(.*)$": "<rootDir>/integrations/transactional/$1",
|
"^@docmost/transactional/(.*)$": "<rootDir>/integrations/transactional/$1",
|
||||||
"^@docmost/ee/(.*)$": "<rootDir>/ee/$1",
|
"^@docmost/ee/(.*)$": "<rootDir>/ee/$1",
|
||||||
"^src/(.*)$": "<rootDir>/$1"
|
"^src/(.*)$": "<rootDir>/$1",
|
||||||
|
"^@docmost/git-sync$": "<rootDir>/../../../packages/git-sync/src/index.ts",
|
||||||
|
"^@docmost/git-sync/(.*)$": "<rootDir>/../../../packages/git-sync/src/$1",
|
||||||
|
"^(\\.{1,2}/.*)\\.js$": "$1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { ClsModule } from 'nestjs-cls';
|
|||||||
import { NoopAuditModule } from './integrations/audit/audit.module';
|
import { NoopAuditModule } from './integrations/audit/audit.module';
|
||||||
import { ThrottleModule } from './integrations/throttle/throttle.module';
|
import { ThrottleModule } from './integrations/throttle/throttle.module';
|
||||||
import { McpModule } from './integrations/mcp/mcp.module';
|
import { McpModule } from './integrations/mcp/mcp.module';
|
||||||
|
import { GitSyncModule } from './integrations/git-sync/git-sync.module';
|
||||||
import { SandboxModule } from './integrations/sandbox/sandbox.module';
|
import { SandboxModule } from './integrations/sandbox/sandbox.module';
|
||||||
import { AiModule } from './integrations/ai/ai.module';
|
import { AiModule } from './integrations/ai/ai.module';
|
||||||
import { AiChatModule } from './core/ai-chat/ai-chat.module';
|
import { AiChatModule } from './core/ai-chat/ai-chat.module';
|
||||||
@@ -90,6 +91,7 @@ try {
|
|||||||
TelemetryModule,
|
TelemetryModule,
|
||||||
ThrottleModule,
|
ThrottleModule,
|
||||||
McpModule,
|
McpModule,
|
||||||
|
GitSyncModule,
|
||||||
SandboxModule,
|
SandboxModule,
|
||||||
AiModule,
|
AiModule,
|
||||||
AiChatModule,
|
AiChatModule,
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { CollaborationGateway } from './collaboration.gateway';
|
||||||
|
import { CollaborationHandler } from './collaboration.handler';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Focused test for the COLLAB_DISABLE_REDIS fallback in handleYjsEvent.
|
||||||
|
*
|
||||||
|
* With Redis disabled the gateway builds no RedisSyncExtension, so the old code
|
||||||
|
* (`return this.redisSync?.handleEvent(...)`) returned undefined and every
|
||||||
|
* doc-mutation event silently no-opped. The fallback must instead invoke the
|
||||||
|
* handler locally against the single hocuspocus instance and return its verdict.
|
||||||
|
*
|
||||||
|
* We construct the gateway with stub extensions and an EnvironmentService whose
|
||||||
|
* isCollabDisableRedis() returns true (redisSync stays null, real hocuspocus is
|
||||||
|
* still built), then spy getHandlers so no real direct connection is opened.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const stubExtension = {} as any;
|
||||||
|
|
||||||
|
function makeEnv() {
|
||||||
|
return {
|
||||||
|
getRedisUrl: () => 'redis://localhost:6379',
|
||||||
|
isCollabDisableRedis: () => true,
|
||||||
|
} as any;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CollaborationGateway.handleYjsEvent (no-Redis fallback)', () => {
|
||||||
|
it('invokes the handler locally and returns its verdict instead of undefined', async () => {
|
||||||
|
const collabHandler = new CollaborationHandler();
|
||||||
|
const verdict = { applied: true, currentText: 'new' };
|
||||||
|
const fakeHandler = jest.fn().mockResolvedValue(verdict);
|
||||||
|
// Bypass the real direct-connection code path — assert dispatch only.
|
||||||
|
jest
|
||||||
|
.spyOn(collabHandler, 'getHandlers')
|
||||||
|
.mockReturnValue({ applyCommentSuggestion: fakeHandler } as any);
|
||||||
|
|
||||||
|
const gateway = new CollaborationGateway(
|
||||||
|
stubExtension,
|
||||||
|
stubExtension,
|
||||||
|
stubExtension,
|
||||||
|
makeEnv(),
|
||||||
|
collabHandler,
|
||||||
|
);
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
commentId: 'c1',
|
||||||
|
expectedText: 'old',
|
||||||
|
newText: 'new',
|
||||||
|
user: { id: 'u1' } as any,
|
||||||
|
};
|
||||||
|
const result = await gateway.handleYjsEvent(
|
||||||
|
'applyCommentSuggestion' as any,
|
||||||
|
'doc-1',
|
||||||
|
payload as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fakeHandler).toHaveBeenCalledWith('doc-1', payload);
|
||||||
|
expect(result).toEqual(verdict);
|
||||||
|
expect(result).not.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -147,14 +147,86 @@ export class CollaborationGateway {
|
|||||||
eventName: TName,
|
eventName: TName,
|
||||||
documentName: string,
|
documentName: string,
|
||||||
payload: Parameters<CollabEventHandlers[TName]>[1],
|
payload: Parameters<CollabEventHandlers[TName]>[1],
|
||||||
) {
|
): ReturnType<CollabEventHandlers[TName]> {
|
||||||
return this.redisSync?.handleEvent(eventName, documentName, payload);
|
if (this.redisSync) {
|
||||||
|
// Normal path: the Redis bridge routes the event to the instance that owns
|
||||||
|
// the document (local or another worker) and carries the handler's return
|
||||||
|
// value back to us (customEventComplete + replyId).
|
||||||
|
return this.redisSync.handleEvent(
|
||||||
|
eventName,
|
||||||
|
documentName,
|
||||||
|
payload,
|
||||||
|
) as ReturnType<CollabEventHandlers[TName]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// COLLAB_DISABLE_REDIS: there is no cross-process bridge, so a single local
|
||||||
|
// hocuspocus instance owns every document. Invoke the handler directly
|
||||||
|
// against it instead of returning undefined — otherwise doc-mutation events
|
||||||
|
// (setCommentMark / resolveCommentMark / applyCommentSuggestion) would
|
||||||
|
// silently no-op and, for suggestions, the caller could never learn the
|
||||||
|
// verdict. openDirectConnection loads the doc via the persistence extension
|
||||||
|
// if it is not already in memory.
|
||||||
|
if (this.hocuspocus) {
|
||||||
|
const handlers = this.collabEventsService.getHandlers(this.hocuspocus);
|
||||||
|
const handler = handlers[eventName] as (
|
||||||
|
documentName: string,
|
||||||
|
payload: unknown,
|
||||||
|
) => ReturnType<CollabEventHandlers[TName]>;
|
||||||
|
return handler(documentName, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collaboration was never initialized (no live instance). Fail loudly rather
|
||||||
|
// than silently dropping a mutation; phase 4's caller maps this to a 5xx.
|
||||||
|
throw new Error(
|
||||||
|
`Cannot handle collaboration event "${String(
|
||||||
|
eventName,
|
||||||
|
)}": requires a live collaboration instance`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
openDirectConnection(documentName: string, context?: any) {
|
openDirectConnection(documentName: string, context?: any) {
|
||||||
return this.hocuspocus.openDirectConnection(documentName, context);
|
return this.hocuspocus.openDirectConnection(documentName, context);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write a git-originated body into a page, applying the merge on the instance
|
||||||
|
* that OWNS the live Y.Doc so a connected editor CONVERGES on the change.
|
||||||
|
*
|
||||||
|
* git-sync must NOT use openDirectConnection directly for this: that opens the
|
||||||
|
* document on whichever instance/process runs git-sync (the API/worker). When
|
||||||
|
* an editor is connected to a DIFFERENT collab instance/process, that is a
|
||||||
|
* SEPARATE, detached Y.Doc — the merge lands in the detached doc and the DB,
|
||||||
|
* but the live editor never receives the Yjs update; its next debounced
|
||||||
|
* autosave then overwrites the DB with its stale state and SILENTLY REVERTS
|
||||||
|
* the git change (the data-loss bug). Routing through the custom-event channel
|
||||||
|
* runs the merge on the owning instance's shared Document, whose update is
|
||||||
|
* broadcast to every connection (handleUpdate), so the editor's CRDT converges
|
||||||
|
* on the merged result.
|
||||||
|
*
|
||||||
|
* Without redis there is a single instance, so the write runs locally — which
|
||||||
|
* is already the owning (and only) instance the editor is connected to.
|
||||||
|
*/
|
||||||
|
async writePageBody(
|
||||||
|
documentName: string,
|
||||||
|
payload: {
|
||||||
|
prosemirrorJson: unknown;
|
||||||
|
baseProsemirrorJson?: unknown;
|
||||||
|
userId: string;
|
||||||
|
},
|
||||||
|
): Promise<void> {
|
||||||
|
if (this.redisSync) {
|
||||||
|
await this.handleYjsEvent(
|
||||||
|
'gitSyncWriteBody',
|
||||||
|
documentName,
|
||||||
|
payload as any,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await this.collabEventsService
|
||||||
|
.getHandlers(this.hocuspocus)
|
||||||
|
.gitSyncWriteBody(documentName, payload as any);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
*Can be used before calling openDirectConnection directly
|
*Can be used before calling openDirectConnection directly
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,262 @@
|
|||||||
|
// Exercises the REAL `gitSyncWriteBody` collab handler (the owner-routed body
|
||||||
|
// write the data-loss fix introduces). The handler imports the editor graph via
|
||||||
|
// collaboration.util / yjs.util (tiptapExtensions -> editor-ext -> react-dom,
|
||||||
|
// unloadable under jest's node env, same coupling noted in
|
||||||
|
// gitmost-datasource.service.spec.ts), so we stub those + the transformer. The
|
||||||
|
// stubbed toYdoc builds paragraph blocks straight from the ProseMirror JSON so
|
||||||
|
// we can assert convergence on real text.
|
||||||
|
jest.mock('./collaboration.util', () => ({
|
||||||
|
tiptapExtensions: [],
|
||||||
|
getPageId: (name: string) => name.replace(/^page\./, ''),
|
||||||
|
prosemirrorNodeToYElement: jest.fn(),
|
||||||
|
}));
|
||||||
|
jest.mock('./yjs.util', () => ({
|
||||||
|
setYjsMark: jest.fn(),
|
||||||
|
updateYjsMarkAttribute: jest.fn(),
|
||||||
|
}));
|
||||||
|
jest.mock('@hocuspocus/transformer', () => {
|
||||||
|
const Yjs = require('yjs');
|
||||||
|
return {
|
||||||
|
TiptapTransformer: {
|
||||||
|
toYdoc: (json: any) => {
|
||||||
|
if (json?.__throw) throw new Error('boom: malformed doc');
|
||||||
|
const d = new Yjs.Doc();
|
||||||
|
const frag = d.getXmlFragment('default');
|
||||||
|
const blocks = (json?.content ?? []).map((node: any) => {
|
||||||
|
const el = new Yjs.XmlElement(node.type || 'paragraph');
|
||||||
|
const text = (node.content ?? [])
|
||||||
|
.map((t: any) => t.text ?? '')
|
||||||
|
.join('');
|
||||||
|
const t = new Yjs.XmlText();
|
||||||
|
if (text) t.insert(0, text);
|
||||||
|
el.insert(0, [t]);
|
||||||
|
return el;
|
||||||
|
});
|
||||||
|
if (blocks.length) frag.insert(0, blocks);
|
||||||
|
return d;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
import * as Y from 'yjs';
|
||||||
|
import { CollaborationHandler } from './collaboration.handler';
|
||||||
|
|
||||||
|
const pmDoc = (...paras: string[]) => ({
|
||||||
|
type: 'doc',
|
||||||
|
content: paras.map((text) => ({
|
||||||
|
type: 'paragraph',
|
||||||
|
content: text ? [{ type: 'text', text }] : [],
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
|
||||||
|
const texts = (frag: Y.XmlFragment): string[] =>
|
||||||
|
frag.toArray().map((el) =>
|
||||||
|
(el as Y.XmlElement)
|
||||||
|
.toArray()
|
||||||
|
.map((c) => (c as Y.XmlText).toString())
|
||||||
|
.join(''),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Build a fake Hocuspocus whose openDirectConnection yields a DirectConnection
|
||||||
|
// over a REAL shared Document, with a connected "editor" doc that receives the
|
||||||
|
// shared doc's updates (modelling Document.handleUpdate's broadcast on the
|
||||||
|
// OWNING instance). Initial content carries live block ids; the editor starts
|
||||||
|
// fully synced with the shared doc.
|
||||||
|
function fakeHocuspocus(initial: { text: string; id: string }[]) {
|
||||||
|
const shared = new Y.Doc();
|
||||||
|
const frag = shared.getXmlFragment('default');
|
||||||
|
shared.transact(() => {
|
||||||
|
frag.insert(
|
||||||
|
0,
|
||||||
|
initial.map((s) => {
|
||||||
|
const el = new Y.XmlElement('paragraph');
|
||||||
|
el.setAttribute('id', s.id);
|
||||||
|
const t = new Y.XmlText();
|
||||||
|
if (s.text) t.insert(0, s.text);
|
||||||
|
el.insert(0, [t]);
|
||||||
|
return el;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const editor = new Y.Doc();
|
||||||
|
Y.applyUpdate(editor, Y.encodeStateAsUpdate(shared));
|
||||||
|
// Broadcast relay: server-originated updates flow to the connected editor.
|
||||||
|
shared.on('update', (u: Uint8Array, origin: any) => {
|
||||||
|
if (origin !== 'editor') Y.applyUpdate(editor, u, 'server');
|
||||||
|
});
|
||||||
|
|
||||||
|
const openDirectConnection = jest.fn(async () => ({
|
||||||
|
// DirectConnection.transact runs the fn directly against the Document (no
|
||||||
|
// wrapping Y transaction), exactly like @hocuspocus/server.
|
||||||
|
transact: async (fn: (doc: Y.Doc) => void) => fn(shared),
|
||||||
|
disconnect: jest.fn(async () => undefined),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { hocuspocus: { openDirectConnection } as any, shared, editor };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CollaborationHandler.gitSyncWriteBody (owner-routed body write)', () => {
|
||||||
|
it('converges a connected editor on the git change (no silent revert)', async () => {
|
||||||
|
const { hocuspocus, shared, editor } = fakeHocuspocus([
|
||||||
|
{ text: 'alpha', id: 'p1' },
|
||||||
|
{ text: 'beta', id: 'p2' },
|
||||||
|
]);
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
const handlers = handler.getHandlers(hocuspocus);
|
||||||
|
|
||||||
|
// git changed block 1 beta -> beta2; base is the pre-change content.
|
||||||
|
await handlers.gitSyncWriteBody('page.x', {
|
||||||
|
prosemirrorJson: pmDoc('alpha', 'beta2'),
|
||||||
|
baseProsemirrorJson: pmDoc('alpha', 'beta'),
|
||||||
|
userId: 'svc-user',
|
||||||
|
});
|
||||||
|
|
||||||
|
// The shared (owning-instance) doc holds the merge...
|
||||||
|
expect(texts(shared.getXmlFragment('default'))).toEqual(['alpha', 'beta2']);
|
||||||
|
// ...and the connected editor CONVERGED via the broadcast (the bug would
|
||||||
|
// leave it on 'beta' and revert the page on its next autosave).
|
||||||
|
expect(texts(editor.getXmlFragment('default'))).toEqual(['alpha', 'beta2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves a concurrent edit to a DIFFERENT block (3-way, finding #2)', async () => {
|
||||||
|
const { hocuspocus, shared, editor } = fakeHocuspocus([
|
||||||
|
{ text: 'alpha', id: 'p1' },
|
||||||
|
{ text: 'beta', id: 'p2' },
|
||||||
|
]);
|
||||||
|
// The editor is actively editing block 0 while the push arrives.
|
||||||
|
const eFrag = editor.getXmlFragment('default');
|
||||||
|
editor.transact(
|
||||||
|
() => (eFrag.get(0) as Y.XmlElement).get(0) instanceof Y.XmlText &&
|
||||||
|
((eFrag.get(0) as Y.XmlElement).get(0) as Y.XmlText).insert(5, ' EDIT'),
|
||||||
|
'editor',
|
||||||
|
);
|
||||||
|
Y.applyUpdate(shared, Y.encodeStateAsUpdate(editor), 'editor');
|
||||||
|
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
await handler.getHandlers(hocuspocus).gitSyncWriteBody('page.x', {
|
||||||
|
prosemirrorJson: pmDoc('alpha', 'beta2'),
|
||||||
|
baseProsemirrorJson: pmDoc('alpha', 'beta'),
|
||||||
|
userId: 'svc-user',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Human's block-0 edit AND git's block-1 change both survive on the editor.
|
||||||
|
expect(texts(editor.getXmlFragment('default'))).toEqual([
|
||||||
|
'alpha EDIT',
|
||||||
|
'beta2',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FLUSHES the pending debounced store BEFORE merging so an in-flight edit survives (finding #2)', async () => {
|
||||||
|
// QA #119 finding #2: the 3-way merge must run against the latest live-doc
|
||||||
|
// state. A concurrent UI edit that is still in-flight (the store is debounced)
|
||||||
|
// must be drained into the live doc BEFORE git merges, or git clean-applies and
|
||||||
|
// the edit is silently dropped — even on a DIFFERENT block. Model the drain via
|
||||||
|
// the pending-store flush: when it runs, the in-flight block-0 edit lands.
|
||||||
|
const shared = new Y.Doc();
|
||||||
|
const frag = shared.getXmlFragment('default');
|
||||||
|
shared.transact(() => {
|
||||||
|
frag.insert(
|
||||||
|
0,
|
||||||
|
[
|
||||||
|
{ text: 'alpha', id: 'p1' },
|
||||||
|
{ text: 'beta', id: 'p2' },
|
||||||
|
].map((s) => {
|
||||||
|
const el = new Y.XmlElement('paragraph');
|
||||||
|
el.setAttribute('id', s.id);
|
||||||
|
const t = new Y.XmlText();
|
||||||
|
t.insert(0, s.text);
|
||||||
|
el.insert(0, [t]);
|
||||||
|
return el;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const order: string[] = [];
|
||||||
|
const debouncer = {
|
||||||
|
isDebounced: jest.fn(() => true),
|
||||||
|
executeNow: jest.fn(async () => {
|
||||||
|
order.push('flush');
|
||||||
|
// The in-flight client edit to block 0 only lands once the pending store
|
||||||
|
// is flushed (i.e. the event loop is drained) — BEFORE the merge.
|
||||||
|
shared.transact(() =>
|
||||||
|
((frag.get(0) as Y.XmlElement).get(0) as Y.XmlText).insert(5, ' EDIT'),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const openDirectConnection = jest.fn(async () => ({
|
||||||
|
transact: async (fn: (doc: Y.Doc) => void) => {
|
||||||
|
order.push('merge');
|
||||||
|
fn(shared);
|
||||||
|
},
|
||||||
|
disconnect: jest.fn(async () => undefined),
|
||||||
|
}));
|
||||||
|
const hocuspocus = { openDirectConnection, debouncer } as any;
|
||||||
|
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
await handler.getHandlers(hocuspocus).gitSyncWriteBody('page.x', {
|
||||||
|
prosemirrorJson: pmDoc('alpha', 'beta2'), // git changes block 1
|
||||||
|
baseProsemirrorJson: pmDoc('alpha', 'beta'),
|
||||||
|
userId: 'svc-user',
|
||||||
|
});
|
||||||
|
|
||||||
|
// The flush ran, and it ran BEFORE the merge transaction.
|
||||||
|
expect(debouncer.executeNow).toHaveBeenCalledTimes(1);
|
||||||
|
expect(order).toEqual(['flush', 'merge']);
|
||||||
|
// Both the in-flight block-0 edit and git's block-1 change survive — the
|
||||||
|
// pre-flush bug would have produced ['alpha', 'beta2'] (UI edit dropped).
|
||||||
|
expect(texts(shared.getXmlFragment('default'))).toEqual([
|
||||||
|
'alpha EDIT',
|
||||||
|
'beta2',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not flush when no store is pending (isDebounced false)', async () => {
|
||||||
|
const { hocuspocus, shared } = fakeHocuspocus([{ text: 'a', id: 'p1' }]);
|
||||||
|
const executeNow = jest.fn();
|
||||||
|
(hocuspocus as any).debouncer = {
|
||||||
|
isDebounced: jest.fn(() => false),
|
||||||
|
executeNow,
|
||||||
|
};
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
await handler.getHandlers(hocuspocus).gitSyncWriteBody('page.x', {
|
||||||
|
prosemirrorJson: pmDoc('a', 'b'),
|
||||||
|
userId: 'svc-user',
|
||||||
|
});
|
||||||
|
expect(executeNow).not.toHaveBeenCalled();
|
||||||
|
expect(texts(shared.getXmlFragment('default'))).toEqual(['a', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('crash-safe: a transform failure never opens the connection or mutates the live doc', async () => {
|
||||||
|
const { hocuspocus, shared } = fakeHocuspocus([{ text: 'alpha', id: 'p1' }]);
|
||||||
|
const before = texts(shared.getXmlFragment('default'));
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
handler.getHandlers(hocuspocus).gitSyncWriteBody('page.x', {
|
||||||
|
prosemirrorJson: { __throw: true } as any,
|
||||||
|
userId: 'svc-user',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('boom');
|
||||||
|
|
||||||
|
// The incoming doc is built BEFORE opening the connection, so the throw
|
||||||
|
// happens first: the live doc is untouched and no connection was opened.
|
||||||
|
expect(hocuspocus.openDirectConnection).not.toHaveBeenCalled();
|
||||||
|
expect(texts(shared.getXmlFragment('default'))).toEqual(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to a 2-way merge when no base is supplied', async () => {
|
||||||
|
const { hocuspocus, shared, editor } = fakeHocuspocus([
|
||||||
|
{ text: 'alpha', id: 'p1' },
|
||||||
|
]);
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
|
||||||
|
await handler.getHandlers(hocuspocus).gitSyncWriteBody('page.x', {
|
||||||
|
prosemirrorJson: pmDoc('alpha', 'gamma'),
|
||||||
|
userId: 'svc-user',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(texts(shared.getXmlFragment('default'))).toEqual(['alpha', 'gamma']);
|
||||||
|
expect(texts(editor.getXmlFragment('default'))).toEqual(['alpha', 'gamma']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import * as Y from 'yjs';
|
||||||
|
import { CollaborationHandler } from './collaboration.handler';
|
||||||
|
import * as yjsUtil from './yjs.util';
|
||||||
|
import { User } from '@docmost/db/types/entity.types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the `applyCommentSuggestion` collab handler (phase 3 of #315).
|
||||||
|
*
|
||||||
|
* The handler runs `replaceYjsMarkedText` inside the owning instance's Y
|
||||||
|
* transaction and returns the verdict to the caller. We exercise it against a
|
||||||
|
* REAL in-memory Y.Doc carrying a marked comment run, driven through a FAKE
|
||||||
|
* hocuspocus whose openDirectConnection().transact(fn) simply runs fn(doc) —
|
||||||
|
* mirroring how the real hocuspocus DirectConnection invokes the callback with
|
||||||
|
* the shared document (it does not forward the callback's return value, which is
|
||||||
|
* exactly why withYdocConnection captures it via a closure).
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Build a Y.Doc with a single paragraph whose text carries a `comment` mark for
|
||||||
|
// the given commentId — the shape `replaceYjsMarkedText` walks in production.
|
||||||
|
function buildDocWithComment(text: string, commentId: string) {
|
||||||
|
const doc = new Y.Doc();
|
||||||
|
const fragment = doc.getXmlFragment('default');
|
||||||
|
const paragraph = new Y.XmlElement('paragraph');
|
||||||
|
const xmlText = new Y.XmlText();
|
||||||
|
xmlText.insert(0, text);
|
||||||
|
xmlText.format(0, text.length, { comment: { commentId, resolved: false } });
|
||||||
|
paragraph.insert(0, [xmlText]);
|
||||||
|
fragment.insert(0, [paragraph]);
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fake hocuspocus exposing only what withYdocConnection needs: a direct
|
||||||
|
// connection whose transact() runs the callback against `doc`.
|
||||||
|
function fakeHocuspocus(doc: Y.Doc) {
|
||||||
|
const connection = {
|
||||||
|
transact: jest.fn(async (fn: (d: Y.Doc) => void) => {
|
||||||
|
fn(doc);
|
||||||
|
}),
|
||||||
|
disconnect: jest.fn(async () => {}),
|
||||||
|
};
|
||||||
|
const hocuspocus = {
|
||||||
|
openDirectConnection: jest.fn(async () => connection),
|
||||||
|
} as any;
|
||||||
|
return { hocuspocus, connection };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = { id: 'u1' } as unknown as User;
|
||||||
|
|
||||||
|
describe('CollaborationHandler.applyCommentSuggestion', () => {
|
||||||
|
it('applies the replacement and returns the verdict when the marked text matches', async () => {
|
||||||
|
const doc = buildDocWithComment('Hello world', 'c1');
|
||||||
|
const { hocuspocus, connection } = fakeHocuspocus(doc);
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
const handlers = handler.getHandlers(hocuspocus);
|
||||||
|
|
||||||
|
const result = await handlers.applyCommentSuggestion('doc-1', {
|
||||||
|
commentId: 'c1',
|
||||||
|
expectedText: 'Hello world',
|
||||||
|
newText: 'Goodbye world',
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({ applied: true, currentText: 'Goodbye world' });
|
||||||
|
// The mutation ran inside the transaction and hit the real doc.
|
||||||
|
expect(connection.transact).toHaveBeenCalledTimes(1);
|
||||||
|
expect(connection.disconnect).toHaveBeenCalledTimes(1);
|
||||||
|
expect(doc.getXmlFragment('default').toString()).toContain(
|
||||||
|
'Goodbye world',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects (applied=false) and returns the current text when it changed', async () => {
|
||||||
|
const doc = buildDocWithComment('Hello world', 'c1');
|
||||||
|
const { hocuspocus } = fakeHocuspocus(doc);
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
const handlers = handler.getHandlers(hocuspocus);
|
||||||
|
|
||||||
|
const result = await handlers.applyCommentSuggestion('doc-1', {
|
||||||
|
commentId: 'c1',
|
||||||
|
expectedText: 'Stale expected text',
|
||||||
|
newText: 'Goodbye world',
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({ applied: false, currentText: 'Hello world' });
|
||||||
|
// Nothing was replaced.
|
||||||
|
expect(doc.getXmlFragment('default').toString()).toContain(
|
||||||
|
'Hello world',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forwards the exact args to replaceYjsMarkedText and returns its result', async () => {
|
||||||
|
const doc = buildDocWithComment('abc', 'c9');
|
||||||
|
const { hocuspocus } = fakeHocuspocus(doc);
|
||||||
|
const spy = jest
|
||||||
|
.spyOn(yjsUtil, 'replaceYjsMarkedText')
|
||||||
|
.mockReturnValue({ applied: true, currentText: 'xyz' });
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
const handlers = handler.getHandlers(hocuspocus);
|
||||||
|
|
||||||
|
const result = await handlers.applyCommentSuggestion('doc-1', {
|
||||||
|
commentId: 'c9',
|
||||||
|
expectedText: 'abc',
|
||||||
|
newText: 'xyz',
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledWith(
|
||||||
|
doc.getXmlFragment('default'),
|
||||||
|
'c9',
|
||||||
|
'abc',
|
||||||
|
'xyz',
|
||||||
|
);
|
||||||
|
expect(result).toEqual({ applied: true, currentText: 'xyz' });
|
||||||
|
spy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('withYdocConnection returns the callback result (transact does not forward it)', async () => {
|
||||||
|
const doc = new Y.Doc();
|
||||||
|
const { hocuspocus } = fakeHocuspocus(doc);
|
||||||
|
const handler = new CollaborationHandler();
|
||||||
|
|
||||||
|
const value = await handler.withYdocConnection(
|
||||||
|
hocuspocus,
|
||||||
|
'doc-1',
|
||||||
|
{},
|
||||||
|
() => 42,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(value).toBe(42);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,9 +5,18 @@ import {
|
|||||||
prosemirrorNodeToYElement,
|
prosemirrorNodeToYElement,
|
||||||
tiptapExtensions,
|
tiptapExtensions,
|
||||||
} from './collaboration.util';
|
} from './collaboration.util';
|
||||||
import { setYjsMark, updateYjsMarkAttribute, YjsSelection } from './yjs.util';
|
import {
|
||||||
|
replaceYjsMarkedText,
|
||||||
|
setYjsMark,
|
||||||
|
updateYjsMarkAttribute,
|
||||||
|
YjsSelection,
|
||||||
|
} from './yjs.util';
|
||||||
import * as Y from 'yjs';
|
import * as Y from 'yjs';
|
||||||
import { User } from '@docmost/db/types/entity.types';
|
import { User } from '@docmost/db/types/entity.types';
|
||||||
|
import {
|
||||||
|
mergeXmlFragments,
|
||||||
|
mergeXmlFragments3WayWithStats,
|
||||||
|
} from './merge/yjs-body-merge';
|
||||||
|
|
||||||
export type CollabEventHandlers = ReturnType<
|
export type CollabEventHandlers = ReturnType<
|
||||||
CollaborationHandler['getHandlers']
|
CollaborationHandler['getHandlers']
|
||||||
@@ -73,6 +82,35 @@ export class CollaborationHandler {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
applyCommentSuggestion: async (
|
||||||
|
documentName: string,
|
||||||
|
payload: {
|
||||||
|
commentId: string;
|
||||||
|
expectedText: string;
|
||||||
|
newText: string;
|
||||||
|
user: User;
|
||||||
|
},
|
||||||
|
): Promise<{ applied: boolean; currentText: string | null }> => {
|
||||||
|
const { commentId, expectedText, newText, user } = payload;
|
||||||
|
// Run the check-and-replace inside the owning instance's Y transaction so
|
||||||
|
// the delete+insert are atomic. The verdict from replaceYjsMarkedText is
|
||||||
|
// returned to the API-server caller (cross-process via the Redis bridge,
|
||||||
|
// or locally when Redis is disabled — see collaboration.gateway.ts).
|
||||||
|
return this.withYdocConnection(
|
||||||
|
hocuspocus,
|
||||||
|
documentName,
|
||||||
|
{ user },
|
||||||
|
(doc) => {
|
||||||
|
const fragment = doc.getXmlFragment('default');
|
||||||
|
return replaceYjsMarkedText(
|
||||||
|
fragment,
|
||||||
|
commentId,
|
||||||
|
expectedText,
|
||||||
|
newText,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
updatePageContent: async (
|
updatePageContent: async (
|
||||||
documentName: string,
|
documentName: string,
|
||||||
payload: {
|
payload: {
|
||||||
@@ -112,21 +150,152 @@ export class CollaborationHandler {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
/**
|
||||||
|
* Git-sync body write, applied as a block-level MERGE into the LIVE doc on
|
||||||
|
* the instance that OWNS it (routed here via the custom-event channel —
|
||||||
|
* see CollaborationGateway.writePageBody). Running on the owning instance
|
||||||
|
* is what makes a connected editor CONVERGE: the merge mutates the shared
|
||||||
|
* Document, whose update is broadcast to every connection, so the editor's
|
||||||
|
* CRDT applies the git change instead of silently reverting it on its next
|
||||||
|
* autosave (the data-loss bug this fixes).
|
||||||
|
*
|
||||||
|
* With a `baseProsemirrorJson` (the last-synced common ancestor) it does a
|
||||||
|
* THREE-WAY merge — a block only the human changed is kept, a block only
|
||||||
|
* git changed is taken (conflicts -> git). Without a base it falls back to
|
||||||
|
* the 2-way merge.
|
||||||
|
*/
|
||||||
|
gitSyncWriteBody: async (
|
||||||
|
documentName: string,
|
||||||
|
payload: {
|
||||||
|
prosemirrorJson: any;
|
||||||
|
baseProsemirrorJson?: any;
|
||||||
|
userId: string;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const { prosemirrorJson, baseProsemirrorJson, userId } = payload;
|
||||||
|
|
||||||
|
// Build the incoming (and base) Yjs docs BEFORE opening the connection /
|
||||||
|
// touching the live doc. If a transform throws (a malformed/unsupported
|
||||||
|
// doc) we must NOT have mutated the live body — otherwise a conversion
|
||||||
|
// failure could leave the page empty (crash-safe conversion).
|
||||||
|
const targetDoc = TiptapTransformer.toYdoc(
|
||||||
|
prosemirrorJson,
|
||||||
|
'default',
|
||||||
|
tiptapExtensions,
|
||||||
|
);
|
||||||
|
const baseDoc =
|
||||||
|
baseProsemirrorJson != null
|
||||||
|
? TiptapTransformer.toYdoc(
|
||||||
|
baseProsemirrorJson,
|
||||||
|
'default',
|
||||||
|
tiptapExtensions,
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
// CONCURRENT-EDIT FLUSH (QA #119, finding #2). The 3-way merge below runs
|
||||||
|
// against the LIVE Y.Doc, so a concurrent UI edit is only preserved if it
|
||||||
|
// is already part of that doc. A user's edit is debounced before it lands
|
||||||
|
// (the editor batches; the collab store is debounced up to 10s), so the
|
||||||
|
// merge could otherwise run against a PRE-EDIT doc: git would then
|
||||||
|
// clean-apply (no same-block conflict detected) and the in-flight UI edit
|
||||||
|
// — even on a DIFFERENT block — would be silently dropped.
|
||||||
|
//
|
||||||
|
// Flushing the pending debounced store here (a) drains the event loop so a
|
||||||
|
// just-arrived client Yjs update is applied to the live doc BEFORE we
|
||||||
|
// merge, and (b) persists the live doc so the merge baseline is current
|
||||||
|
// even on the doc-reload-from-DB path. After the flush the merge sees the
|
||||||
|
// latest state, so an edit on a different block is MERGED (not overwritten)
|
||||||
|
// and a genuine same-block edit is detected as a conflict -> the
|
||||||
|
// boundary-snapshot in PersistenceExtension pins it to page history
|
||||||
|
// (recoverable) instead of vanishing silently.
|
||||||
|
await this.flushPendingStore(hocuspocus, documentName);
|
||||||
|
|
||||||
|
// actor:'git-sync' + the service user flow into PersistenceExtension
|
||||||
|
// (lastUpdatedSource='git-sync', lastUpdatedById=userId).
|
||||||
|
await this.withYdocConnection(
|
||||||
|
hocuspocus,
|
||||||
|
documentName,
|
||||||
|
{ actor: 'git-sync', user: { id: userId } },
|
||||||
|
(doc) => {
|
||||||
|
const liveFrag = doc.getXmlFragment('default');
|
||||||
|
const targetFrag = targetDoc.getXmlFragment('default');
|
||||||
|
if (baseDoc) {
|
||||||
|
const { conflicts } = mergeXmlFragments3WayWithStats(
|
||||||
|
liveFrag,
|
||||||
|
targetFrag,
|
||||||
|
baseDoc.getXmlFragment('default'),
|
||||||
|
);
|
||||||
|
// SAME-BLOCK conflict contract (SPEC §9): a block both the human
|
||||||
|
// and git changed resolves to GIT (deterministic). Make that
|
||||||
|
// OBSERVABLE rather than silent — log it. The losing human content
|
||||||
|
// is NOT destroyed: the persistence extension's boundary snapshot
|
||||||
|
// pins the pre-merge page state to history on this user->git-sync
|
||||||
|
// transition, so it stays recoverable.
|
||||||
|
if (conflicts > 0) {
|
||||||
|
this.logger.warn(
|
||||||
|
`git-sync merge for ${documentName}: ${conflicts} same-block ` +
|
||||||
|
`conflict(s) resolved to the git version; the prior page ` +
|
||||||
|
`state is preserved in page history (recoverable).`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
mergeXmlFragments(liveFrag, targetFrag);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async withYdocConnection(
|
/**
|
||||||
|
* Flush any pending DEBOUNCED store for `documentName` so the live Y.Doc and the
|
||||||
|
* DB are current BEFORE a git-sync merge reads them (QA #119, finding #2 —
|
||||||
|
* concurrent UI edit silently lost). Mirrors the PersistenceExtension.onDisconnect
|
||||||
|
* flush: only acts when a store is actually pending (`isDebounced`), runs the
|
||||||
|
* SAME scheduled payload (`executeNow`, preserving the edit's context/actor), and
|
||||||
|
* never throws — a flush failure must not abort the git-sync write. Awaiting it
|
||||||
|
* also drains the event loop, so a client Yjs update sitting in the socket buffer
|
||||||
|
* is applied to the live doc before the merge transaction runs.
|
||||||
|
*/
|
||||||
|
private async flushPendingStore(
|
||||||
|
hocuspocus: Hocuspocus,
|
||||||
|
documentName: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const debounceId = `onStoreDocument-${documentName}`;
|
||||||
|
try {
|
||||||
|
const debouncer = (hocuspocus as any)?.debouncer;
|
||||||
|
if (!debouncer?.isDebounced?.(debounceId)) return;
|
||||||
|
await debouncer.executeNow(debounceId);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(
|
||||||
|
`git-sync pre-merge flush failed for ${documentName}: ` +
|
||||||
|
(err instanceof Error ? err.message : String(err)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async withYdocConnection<T>(
|
||||||
hocuspocus: Hocuspocus,
|
hocuspocus: Hocuspocus,
|
||||||
documentName: string,
|
documentName: string,
|
||||||
context: any = {},
|
context: any = {},
|
||||||
fn: (doc: Document) => void,
|
// `fn` MUST be synchronous: hocuspocus `connection.transact(fn)` runs fn
|
||||||
): Promise<void> {
|
// synchronously and does NOT await it, so any mutations after an `await`
|
||||||
|
// inside fn would execute OUTSIDE the Yjs transaction and lose atomicity.
|
||||||
|
fn: (doc: Document) => T,
|
||||||
|
): Promise<T> {
|
||||||
const connection = await hocuspocus.openDirectConnection(
|
const connection = await hocuspocus.openDirectConnection(
|
||||||
documentName,
|
documentName,
|
||||||
context,
|
context,
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
await connection.transact(fn);
|
// hocuspocus `connection.transact(fn)` invokes fn(document) but does NOT
|
||||||
|
// forward fn's return value, so we capture it in a closure and return it
|
||||||
|
// after the transaction (and its storeDocument hooks) resolve.
|
||||||
|
let result: T;
|
||||||
|
await connection.transact((doc) => {
|
||||||
|
result = fn(doc);
|
||||||
|
});
|
||||||
|
return result!;
|
||||||
} finally {
|
} finally {
|
||||||
await connection.disconnect();
|
await connection.disconnect();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { PersistenceExtension } from './persistence.extension';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression for the QA #119 "loss-on-fast-close" data loss: editing a page then
|
||||||
|
* closing the tab within the collab debounce window (~3-18s) lost the edit
|
||||||
|
* because, with `unloadImmediately: false`, Hocuspocus does NOT flush the
|
||||||
|
* debounced onStoreDocument on a last-client disconnect. PersistenceExtension
|
||||||
|
* now flushes the pending store on the LAST disconnect (and only then).
|
||||||
|
*/
|
||||||
|
describe('PersistenceExtension.onDisconnect flush (loss-on-fast-close)', () => {
|
||||||
|
function makeExt(): PersistenceExtension {
|
||||||
|
// onDisconnect touches none of the injected deps; pass casts.
|
||||||
|
return new PersistenceExtension(
|
||||||
|
null as any,
|
||||||
|
null as any,
|
||||||
|
null as any,
|
||||||
|
null as any,
|
||||||
|
null as any,
|
||||||
|
null as any,
|
||||||
|
null as any,
|
||||||
|
null as any,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeData(opts: {
|
||||||
|
clientsCount: number;
|
||||||
|
isDebounced: boolean;
|
||||||
|
isLoading?: boolean;
|
||||||
|
}) {
|
||||||
|
const executeNow = jest.fn(async () => undefined);
|
||||||
|
const isDebounced = jest.fn(() => opts.isDebounced);
|
||||||
|
return {
|
||||||
|
executeNow,
|
||||||
|
isDebounced,
|
||||||
|
payload: {
|
||||||
|
clientsCount: opts.clientsCount,
|
||||||
|
context: {},
|
||||||
|
document: { isLoading: opts.isLoading ?? false } as any,
|
||||||
|
documentName: 'page.abc',
|
||||||
|
instance: { debouncer: { isDebounced, executeNow } } as any,
|
||||||
|
requestHeaders: {},
|
||||||
|
requestParameters: new URLSearchParams(),
|
||||||
|
socketId: 's',
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
it('flushes the pending store when the LAST client disconnects', async () => {
|
||||||
|
const ext = makeExt();
|
||||||
|
const { executeNow, payload } = makeData({
|
||||||
|
clientsCount: 0,
|
||||||
|
isDebounced: true,
|
||||||
|
});
|
||||||
|
await ext.onDisconnect(payload);
|
||||||
|
expect(executeNow).toHaveBeenCalledTimes(1);
|
||||||
|
expect(executeNow).toHaveBeenCalledWith('onStoreDocument-page.abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does NOT flush while other editors remain connected', async () => {
|
||||||
|
const ext = makeExt();
|
||||||
|
const { executeNow, payload } = makeData({
|
||||||
|
clientsCount: 2,
|
||||||
|
isDebounced: true,
|
||||||
|
});
|
||||||
|
await ext.onDisconnect(payload);
|
||||||
|
expect(executeNow).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does NOT write when nothing is pending (already persisted)', async () => {
|
||||||
|
const ext = makeExt();
|
||||||
|
const { executeNow, payload } = makeData({
|
||||||
|
clientsCount: 0,
|
||||||
|
isDebounced: false,
|
||||||
|
});
|
||||||
|
await ext.onDisconnect(payload);
|
||||||
|
expect(executeNow).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does NOT flush a doc that is still loading (load error guard)', async () => {
|
||||||
|
const ext = makeExt();
|
||||||
|
const { executeNow, payload } = makeData({
|
||||||
|
clientsCount: 0,
|
||||||
|
isDebounced: true,
|
||||||
|
isLoading: true,
|
||||||
|
});
|
||||||
|
await ext.onDisconnect(payload);
|
||||||
|
expect(executeNow).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
// Stub collaboration.util so importing the extension does not drag in the
|
||||||
|
// editor-ext -> @tiptap/react -> react-dom graph (unloadable under jest's node
|
||||||
|
// env, same coupling the gitmost-datasource / mcp specs document). The
|
||||||
|
// extension only calls getPageId, jsonToText and isEmptyParagraphDoc from it on
|
||||||
|
// the store path; tiptapExtensions is unused by onStoreDocument.
|
||||||
|
jest.mock('../collaboration.util', () => ({
|
||||||
|
tiptapExtensions: [],
|
||||||
|
getPageId: (name: string) => name.replace(/^page\./, ''),
|
||||||
|
jsonToText: () => 'text',
|
||||||
|
isEmptyParagraphDoc: () => false,
|
||||||
|
// The post-write mention extraction walks the doc via jsonToNode().descendants;
|
||||||
|
// return a node-like stub with no descendants so no mentions are produced
|
||||||
|
// (mention handling is out of scope here — we only assert provenance).
|
||||||
|
jsonToNode: () => ({ descendants: () => undefined }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Control the Yjs<->JSON bridge: fromYdoc returns the "incoming" doc the writer
|
||||||
|
// is storing. We keep it distinct from the page's persisted content so the
|
||||||
|
// no-op guard (isDeepStrictEqual) never short-circuits the write.
|
||||||
|
const INCOMING_JSON = { type: 'doc', content: [{ type: 'paragraph' }, { t: 1 }] };
|
||||||
|
jest.mock('@hocuspocus/transformer', () => ({
|
||||||
|
TiptapTransformer: {
|
||||||
|
fromYdoc: jest.fn(() => INCOMING_JSON),
|
||||||
|
toYdoc: jest.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Run the executeTx callback inline with a passthrough trx.
|
||||||
|
jest.mock('@docmost/db/utils', () => ({
|
||||||
|
executeTx: jest.fn(async (_db: any, cb: any) => cb({} as any)),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import * as Y from 'yjs';
|
||||||
|
import { PersistenceExtension } from './persistence.extension';
|
||||||
|
import {
|
||||||
|
onChangePayload,
|
||||||
|
onStoreDocumentPayload,
|
||||||
|
} from '@hocuspocus/server';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provenance-precedence coverage for PersistenceExtension.onStoreDocument
|
||||||
|
* (test-strategy Module 4 / item #2): the contract `agent > git-sync > user`,
|
||||||
|
* plus the negative that a git-sync store does NOT pin a boundary history
|
||||||
|
* snapshot. We drive the precedence through the real public method (onChange to
|
||||||
|
* arm the sticky agent marker, then onStoreDocument), mocking the repos / db /
|
||||||
|
* Yjs bridge so no real database or collab server is needed. The store's
|
||||||
|
* persisted `lastUpdatedSource` and the saveHistory call are the observable
|
||||||
|
* outputs.
|
||||||
|
*/
|
||||||
|
describe('PersistenceExtension.onStoreDocument — provenance precedence (#2)', () => {
|
||||||
|
const DOCUMENT_NAME = 'page.page-1';
|
||||||
|
const PAGE_ID = 'page-1';
|
||||||
|
|
||||||
|
// `page.content` differs from INCOMING_JSON so the write is never skipped.
|
||||||
|
const persistedPage = (overrides?: { lastUpdatedSource?: string }) => ({
|
||||||
|
id: PAGE_ID,
|
||||||
|
slugId: 'slug-1',
|
||||||
|
spaceId: 'space-1',
|
||||||
|
workspaceId: 'ws-1',
|
||||||
|
creatorId: 'creator-1',
|
||||||
|
contributorIds: ['creator-1'],
|
||||||
|
content: { type: 'doc', content: [{ type: 'paragraph', content: [] }] },
|
||||||
|
lastUpdatedSource: overrides?.lastUpdatedSource ?? 'user',
|
||||||
|
createdAt: new Date(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const build = (pageOverrides?: { lastUpdatedSource?: string }) => {
|
||||||
|
const pageRepo = {
|
||||||
|
findById: jest.fn().mockResolvedValue(persistedPage(pageOverrides)),
|
||||||
|
updatePage: jest.fn().mockResolvedValue({ numUpdatedRows: 1n }),
|
||||||
|
};
|
||||||
|
const pageHistoryRepo = {
|
||||||
|
// No prior snapshot -> humanBaselineMissing is true, so the ONLY thing
|
||||||
|
// gating the boundary snapshot in these tests is the source precedence.
|
||||||
|
findPageLastHistory: jest.fn().mockResolvedValue(null),
|
||||||
|
saveHistory: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const aiQueue = { add: jest.fn().mockResolvedValue(undefined) };
|
||||||
|
const historyQueue = { add: jest.fn().mockResolvedValue(undefined) };
|
||||||
|
const notificationQueue = { add: jest.fn().mockResolvedValue(undefined) };
|
||||||
|
const collabHistory = {
|
||||||
|
addContributors: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const transclusionService = {
|
||||||
|
syncPageTransclusions: jest.fn().mockResolvedValue(undefined),
|
||||||
|
syncPageReferences: jest.fn().mockResolvedValue(undefined),
|
||||||
|
syncPageTemplateReferences: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
|
||||||
|
const ext = new PersistenceExtension(
|
||||||
|
pageRepo as any,
|
||||||
|
pageHistoryRepo as any,
|
||||||
|
{} as any, // db
|
||||||
|
aiQueue as any,
|
||||||
|
historyQueue as any,
|
||||||
|
notificationQueue as any,
|
||||||
|
collabHistory as any,
|
||||||
|
transclusionService as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
return { ext, pageRepo, pageHistoryRepo, historyQueue };
|
||||||
|
};
|
||||||
|
|
||||||
|
// A real Y.Doc is required for Y.encodeStateAsUpdate(document); broadcastStateless
|
||||||
|
// is a no-op spy. The fromYdoc bridge is mocked, so the doc's contents are
|
||||||
|
// irrelevant to the JSON path.
|
||||||
|
const makeStorePayload = (context: any): onStoreDocumentPayload =>
|
||||||
|
({
|
||||||
|
documentName: DOCUMENT_NAME,
|
||||||
|
document: Object.assign(new Y.Doc(), {
|
||||||
|
broadcastStateless: jest.fn(),
|
||||||
|
}),
|
||||||
|
context,
|
||||||
|
}) as any;
|
||||||
|
|
||||||
|
const makeChangePayload = (actor: string): onChangePayload =>
|
||||||
|
({
|
||||||
|
documentName: DOCUMENT_NAME,
|
||||||
|
context: { user: { id: 'user-1' }, actor },
|
||||||
|
}) as any;
|
||||||
|
|
||||||
|
const sourceOf = (pageRepo: { updatePage: jest.Mock }) =>
|
||||||
|
pageRepo.updatePage.mock.calls[0][0].lastUpdatedSource;
|
||||||
|
|
||||||
|
it("tags 'user' for a plain write (no agent touch, no git-sync actor)", async () => {
|
||||||
|
const { ext, pageRepo } = build();
|
||||||
|
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'user-1' }, actor: 'user' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sourceOf(pageRepo)).toBe('user');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tags 'git-sync' when the writer's actor is 'git-sync' and no agent touched the window", async () => {
|
||||||
|
const { ext, pageRepo } = build();
|
||||||
|
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'svc-user' }, actor: 'git-sync' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sourceOf(pageRepo)).toBe('git-sync');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps 'git-sync' for an explicit git-sync store even with a sticky agent marker (#14 loop-guard)", async () => {
|
||||||
|
const { ext, pageRepo } = build();
|
||||||
|
|
||||||
|
// An agent edit landed earlier in the coalescing window (sticky marker),
|
||||||
|
// then a git-sync writer performs the store. Red-team finding #14: an
|
||||||
|
// EXPLICIT current-write actor is authoritative for THIS write, so the
|
||||||
|
// store must stay 'git-sync' — otherwise the PageChangeListener loop-guard
|
||||||
|
// (keyed on lastUpdatedSource === 'git-sync') fails to recognize git-sync's
|
||||||
|
// own write and re-exports it. Explicit 'agent' still wins (see below); the
|
||||||
|
// sticky marker only promotes a plain human writer to 'agent'.
|
||||||
|
await ext.onChange(makeChangePayload('agent'));
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'svc-user' }, actor: 'git-sync' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sourceOf(pageRepo)).toBe('git-sync');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tags 'agent' when the storing writer itself is the agent (no prior onChange)", async () => {
|
||||||
|
const { ext, pageRepo } = build();
|
||||||
|
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'agent-user' }, actor: 'agent' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sourceOf(pageRepo)).toBe('agent');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- boundary snapshot for a git-sync store over a HUMAN baseline -----------
|
||||||
|
// SPEC §9 observable-loss guard (bug #2): a git-sync body write is a block-level
|
||||||
|
// 3-way merge whose same-block rule is "git wins". To keep a concurrent human
|
||||||
|
// edit RECOVERABLE rather than silently overwritten, a git-sync store over a
|
||||||
|
// prior NON-git-sync baseline pins that prior state to page history first —
|
||||||
|
// exactly like the agent path. So saveHistory MUST be called here.
|
||||||
|
it('DOES pin a boundary snapshot for a git-sync store over a prior human state', async () => {
|
||||||
|
const { ext, pageHistoryRepo } = build({ lastUpdatedSource: 'user' });
|
||||||
|
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'svc-user' }, actor: 'git-sync' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(pageHistoryRepo.saveHistory).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- negative: a git-sync store over a git-sync baseline does NOT re-pin -----
|
||||||
|
// The boundary is pinned once on the transition INTO git-sync; a subsequent
|
||||||
|
// git-sync store over an already-git-sync baseline must not churn history.
|
||||||
|
it('does NOT re-pin a boundary snapshot for a git-sync store over a git-sync baseline', async () => {
|
||||||
|
const { ext, pageHistoryRepo } = build({ lastUpdatedSource: 'git-sync' });
|
||||||
|
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'svc-user' }, actor: 'git-sync' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(pageHistoryRepo.saveHistory).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('DOES pin a boundary snapshot for an agent store over a prior human state (control)', async () => {
|
||||||
|
// Confirms the negative above is meaningful: under the SAME mocks, an agent
|
||||||
|
// store over a 'user' baseline DOES trigger the boundary snapshot.
|
||||||
|
const { ext, pageHistoryRepo } = build({ lastUpdatedSource: 'user' });
|
||||||
|
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'agent-user' }, actor: 'agent' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(pageHistoryRepo.saveHistory).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does NOT pin a boundary snapshot for a plain user store', async () => {
|
||||||
|
const { ext, pageHistoryRepo } = build({ lastUpdatedSource: 'user' });
|
||||||
|
|
||||||
|
await ext.onStoreDocument(
|
||||||
|
makeStorePayload({ user: { id: 'user-1' }, actor: 'user' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(pageHistoryRepo.saveHistory).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
afterUnloadDocumentPayload,
|
afterUnloadDocumentPayload,
|
||||||
Extension,
|
Extension,
|
||||||
onChangePayload,
|
onChangePayload,
|
||||||
|
onDisconnectPayload,
|
||||||
onLoadDocumentPayload,
|
onLoadDocumentPayload,
|
||||||
onStatelessPayload,
|
onStatelessPayload,
|
||||||
onStoreDocumentPayload,
|
onStoreDocumentPayload,
|
||||||
@@ -82,7 +83,17 @@ export function resolveSource(
|
|||||||
stickyTouched: boolean,
|
stickyTouched: boolean,
|
||||||
contextActor?: string,
|
contextActor?: string,
|
||||||
): ProvenanceSource {
|
): ProvenanceSource {
|
||||||
return stickyTouched || contextActor === 'agent' ? 'agent' : 'user';
|
// An EXPLICIT current-write actor is authoritative for THIS write and wins
|
||||||
|
// over the sticky-agent fallback. Order: explicit 'agent' > explicit
|
||||||
|
// 'git-sync' > sticky agent marker > plain human 'user'. The git-sync case
|
||||||
|
// must NOT be masked by the sticky marker, or the PageChangeListener
|
||||||
|
// loop-guard (which keys on lastUpdatedSource === 'git-sync') would re-export
|
||||||
|
// git-sync's own writes (#14). Explicit agent still wins so a window that
|
||||||
|
// mixed an agent edit stays tagged 'agent'.
|
||||||
|
if (contextActor === 'agent') return 'agent';
|
||||||
|
if (contextActor === 'git-sync') return 'git-sync';
|
||||||
|
if (stickyTouched) return 'agent';
|
||||||
|
return 'user';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -191,6 +202,40 @@ export class PersistenceExtension implements Extension {
|
|||||||
return new Y.Doc();
|
return new Y.Doc();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LOSS-ON-FAST-CLOSE FIX (QA #119). When the LAST editor disconnects, FLUSH any
|
||||||
|
* pending (debounced) store to the DB IMMEDIATELY instead of waiting out the
|
||||||
|
* up-to-10s `debounce` window.
|
||||||
|
*
|
||||||
|
* The collab server runs with `unloadImmediately: false` (collaboration.gateway),
|
||||||
|
* so on a last-client disconnect Hocuspocus does NOT flush the debounced
|
||||||
|
* onStoreDocument — it relies on the timer firing later. A quick edit-then-close
|
||||||
|
* (closing the tab within the debounce window, ~3-18s) therefore left the edit
|
||||||
|
* only in the soon-to-be-unloaded in-memory Y.Doc; meanwhile git-sync mirrored
|
||||||
|
* the STALE/empty DB body to the vault (the reported "59-byte frontmatter-only"
|
||||||
|
* data loss). Running the already-scheduled store now closes that window.
|
||||||
|
*
|
||||||
|
* Gated tightly so it never adds a redundant write: only on the LAST disconnect
|
||||||
|
* (`clientsCount === 0`), only for a fully-loaded doc, and only when a store is
|
||||||
|
* actually pending (`isDebounced`). `executeNow` runs the SAME payload Hocuspocus
|
||||||
|
* scheduled (preserving the edit's context/actor) and clears the timer.
|
||||||
|
*/
|
||||||
|
async onDisconnect(data: onDisconnectPayload) {
|
||||||
|
const { instance, document, documentName, clientsCount } = data;
|
||||||
|
if (clientsCount > 0) return;
|
||||||
|
if (!document || document.isLoading) return;
|
||||||
|
const debounceId = `onStoreDocument-${documentName}`;
|
||||||
|
if (!instance?.debouncer?.isDebounced(debounceId)) return;
|
||||||
|
try {
|
||||||
|
await instance.debouncer.executeNow(debounceId);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error(
|
||||||
|
`onDisconnect flush failed for ${documentName}: ` +
|
||||||
|
(err instanceof Error ? err.message : String(err)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async onStoreDocument(data: onStoreDocumentPayload) {
|
async onStoreDocument(data: onStoreDocumentPayload) {
|
||||||
const { documentName, document, context } = data;
|
const { documentName, document, context } = data;
|
||||||
|
|
||||||
@@ -213,6 +258,11 @@ export class PersistenceExtension implements Extension {
|
|||||||
// Sticky agent marker: 'agent' if any agent edit landed in this window, OR
|
// Sticky agent marker: 'agent' if any agent edit landed in this window, OR
|
||||||
// if the current writer is the agent (covers a store with no prior onChange
|
// if the current writer is the agent (covers a store with no prior onChange
|
||||||
// agent event in the same window). §15 H2.
|
// agent event in the same window). §15 H2.
|
||||||
|
// Provenance precedence: agent > git-sync > user (see resolveSource). A
|
||||||
|
// 'git-sync' store is NOT given an immediate history snapshot — it is
|
||||||
|
// debounced like a human edit (a git-sync write is a block-level merge into
|
||||||
|
// the live doc, so it reads like an incremental human edit, not a bulk
|
||||||
|
// import that would warrant its own immediate snapshot).
|
||||||
const lastUpdatedSource = resolveSource(
|
const lastUpdatedSource = resolveSource(
|
||||||
this.consumeAgentTouched(documentName),
|
this.consumeAgentTouched(documentName),
|
||||||
context?.actor,
|
context?.actor,
|
||||||
@@ -279,17 +329,25 @@ export class PersistenceExtension implements Extension {
|
|||||||
// flag via that same hoisted consume (a "cleared then retyped"
|
// flag via that same hoisted consume (a "cleared then retyped"
|
||||||
// sequence can't leave a usable one behind).
|
// sequence can't leave a usable one behind).
|
||||||
const incomingEmpty = isEmptyParagraphDoc(tiptapJson as any);
|
const incomingEmpty = isEmptyParagraphDoc(tiptapJson as any);
|
||||||
|
// A git-sync write is authoritative and its content IS the vault file:
|
||||||
|
// an empty incoming doc there means the user DELIBERATELY cleared the
|
||||||
|
// page's markdown in git (there is no "transient glitch empty" for a
|
||||||
|
// file-sourced write). Honor it, otherwise the empty-guard rejects the
|
||||||
|
// clear, the vault ref has already advanced past the empty commit, and
|
||||||
|
// vault<->Docmost diverge permanently (review warning). This mirrors the
|
||||||
|
// #251 intentional-clear allowance for a different authoritative source.
|
||||||
|
const gitSyncClear = lastUpdatedSource === 'git-sync';
|
||||||
if (
|
if (
|
||||||
incomingEmpty &&
|
incomingEmpty &&
|
||||||
page.content &&
|
page.content &&
|
||||||
!isEmptyParagraphDoc(page.content as any)
|
!isEmptyParagraphDoc(page.content as any)
|
||||||
) {
|
) {
|
||||||
if (allowIntentionalClear) {
|
if (allowIntentionalClear || gitSyncClear) {
|
||||||
this.logger.debug(
|
this.logger.debug(
|
||||||
`Intentional clear for ${pageId}: persisting empty doc over ` +
|
`Intentional clear for ${pageId}: persisting empty doc over ` +
|
||||||
`non-empty content (user-signalled)`,
|
`non-empty content (${gitSyncClear ? 'git-sync' : 'user-signalled'})`,
|
||||||
);
|
);
|
||||||
// fall through — the empty write is allowed exactly once.
|
// fall through — the empty write is allowed.
|
||||||
} else {
|
} else {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Skipping store for ${pageId}: empty live doc would overwrite ` +
|
`Skipping store for ${pageId}: empty live doc would overwrite ` +
|
||||||
@@ -314,21 +372,30 @@ export class PersistenceExtension implements Extension {
|
|||||||
//this.logger.debug('Contributors error:' + err?.['message']);
|
//this.logger.debug('Contributors error:' + err?.['message']);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Approach A — boundary snapshot before the agent's first edit.
|
// Approach A — boundary snapshot before a MACHINE write overwrites a
|
||||||
// When this store is the agent's and the page's currently persisted
|
// human (or other-source) baseline. When this store is from a machine
|
||||||
// state was authored by a human, pin that human state as its own
|
// source — the AGENT or GIT-SYNC — and the page's currently persisted
|
||||||
// history version BEFORE the agent overwrites it. `page` still holds
|
// state was authored by a DIFFERENT source, pin that prior state as its
|
||||||
// the OLD content/provenance here, so saveHistory(page) captures the
|
// own history version BEFORE the machine write overwrites it. `page`
|
||||||
// pre-agent state tagged 'user'. The agent's new content is
|
// still holds the OLD content/provenance here, so saveHistory(page)
|
||||||
// snapshotted later by the debounced PAGE_HISTORY job ('agent'). Skip
|
// captures the pre-write state. The machine's new content is snapshotted
|
||||||
// if the prior state is already agent-authored (boundary already
|
// later by the debounced PAGE_HISTORY job.
|
||||||
// pinned on the user->agent transition), if the page is effectively
|
//
|
||||||
// empty, or if the latest existing snapshot already equals this human
|
// For GIT-SYNC this is the OBSERVABLE-LOSS guard (SPEC §9 conflict
|
||||||
// state (avoid duplicates).
|
// contract): a git-sync body write is a block-level 3-way merge whose
|
||||||
if (
|
// same-block rule is "git wins". Without this pin, a concurrent human
|
||||||
lastUpdatedSource === 'agent' &&
|
// edit to a block git also changed would be overwritten with NO trace.
|
||||||
page.lastUpdatedSource !== 'agent'
|
// Pinning the pre-merge state here means the human's content is always
|
||||||
) {
|
// RECOVERABLE via page history rather than silently lost — git still
|
||||||
|
// wins the live doc deterministically, but nothing is destroyed.
|
||||||
|
//
|
||||||
|
// Skip if the prior state was already authored by THIS machine source
|
||||||
|
// (boundary already pinned on the transition into it), if the page is
|
||||||
|
// effectively empty, or if the latest existing snapshot already equals
|
||||||
|
// the prior state (avoid duplicates).
|
||||||
|
const isMachineWrite =
|
||||||
|
lastUpdatedSource === 'agent' || lastUpdatedSource === 'git-sync';
|
||||||
|
if (isMachineWrite && page.lastUpdatedSource !== lastUpdatedSource) {
|
||||||
// pageHistory.pageId is uuid-typed; use page.id (never the doc-name
|
// pageHistory.pageId is uuid-typed; use page.id (never the doc-name
|
||||||
// slugId) so a `page.<slugId>` doc cannot throw 22P02 here (#260).
|
// slugId) so a `page.<slugId>` doc cannot throw 22P02 here (#260).
|
||||||
const lastHistory = await this.pageHistoryRepo.findPageLastHistory(
|
const lastHistory = await this.pageHistoryRepo.findPageLastHistory(
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
// Regression coverage for the custom-event request/reply protocol in the
|
||||||
|
// RedisSyncExtension. git-sync routes its body write through a custom event
|
||||||
|
// (`gitSyncWriteBody`) which, when the target doc is owned by a DIFFERENT collab
|
||||||
|
// instance, runs REMOTELY inside `handleRedisMessage` on the owning instance. The
|
||||||
|
// remote handler can THROW (markdown->ProseMirror transform on a malformed body).
|
||||||
|
//
|
||||||
|
// Before the fix the throw was uncaught: (1) no `customEventComplete` reply was
|
||||||
|
// published, so the origin's awaiting promise only rejected after `customEventTTL`
|
||||||
|
// (~30s) as a generic 'TIMEOUT', and (2) an unhandledRejection escaped the async
|
||||||
|
// `messageBuffer` listener on the owning instance. These tests assert the throw is
|
||||||
|
// turned into an error-carrying reply that rejects the origin PROMPTLY with the
|
||||||
|
// real message, with the no-throw and local paths unchanged.
|
||||||
|
|
||||||
|
import { RedisSyncExtension } from './redis-sync.extension';
|
||||||
|
|
||||||
|
type Listener = (channel: Buffer, message: Buffer) => unknown;
|
||||||
|
|
||||||
|
// Minimal in-memory pub/sub + lock store shared across FakeRedis duplicates,
|
||||||
|
// modelling the two-instance topology (origin + owner) over one Redis.
|
||||||
|
class FakeRedisBus {
|
||||||
|
instances: FakeRedis[] = [];
|
||||||
|
locks = new Map<string, string>();
|
||||||
|
published: { channel: string; message: Buffer }[] = [];
|
||||||
|
|
||||||
|
register(inst: FakeRedis) {
|
||||||
|
this.instances.push(inst);
|
||||||
|
}
|
||||||
|
|
||||||
|
publish(channel: string, message: Buffer) {
|
||||||
|
this.published.push({ channel, message });
|
||||||
|
for (const inst of this.instances) {
|
||||||
|
if (!inst.subscribed.has(channel)) continue;
|
||||||
|
for (const listener of inst.messageListeners) {
|
||||||
|
// ioredis delivers async; `void` mirrors the production listener
|
||||||
|
// registration (`sub.on('messageBuffer', ...)`), whose rejection would
|
||||||
|
// surface as an unhandledRejection if the handler did not catch.
|
||||||
|
void listener(Buffer.from(channel), message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeRedis {
|
||||||
|
subscribed = new Set<string>();
|
||||||
|
messageListeners: Listener[] = [];
|
||||||
|
|
||||||
|
constructor(private bus: FakeRedisBus) {
|
||||||
|
bus.register(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
duplicate() {
|
||||||
|
return new FakeRedis(this.bus);
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribe(...channels: string[]) {
|
||||||
|
for (const c of channels) this.subscribed.add(c);
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
on(event: string, cb: any) {
|
||||||
|
if (event === 'messageBuffer') this.messageListeners.push(cb as Listener);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
publish(channel: string, message: Buffer) {
|
||||||
|
this.bus.publish(channel, message);
|
||||||
|
return Promise.resolve(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Models `SET key val PX ttl NX GET`: only writes when absent (NX); returns the
|
||||||
|
// previous value (GET) so the origin observes the owner already holding the lock.
|
||||||
|
set(key: string, val: string, ...args: any[]) {
|
||||||
|
const hasNX = args.includes('NX');
|
||||||
|
const hasGET = args.includes('GET');
|
||||||
|
const old = this.bus.locks.get(key) ?? null;
|
||||||
|
if (!hasNX || old === null) this.bus.locks.set(key, val);
|
||||||
|
return Promise.resolve(hasGET ? old : 'OK');
|
||||||
|
}
|
||||||
|
|
||||||
|
del(key: string) {
|
||||||
|
this.bus.locks.delete(key);
|
||||||
|
return Promise.resolve(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pack = (m: any) => Buffer.from(JSON.stringify(m));
|
||||||
|
const unpack = (b: Buffer) => JSON.parse(b.toString());
|
||||||
|
|
||||||
|
function makeExtension(
|
||||||
|
bus: FakeRedisBus,
|
||||||
|
serverId: string,
|
||||||
|
customEvents: Record<string, (doc: string, payload: any) => Promise<any>>,
|
||||||
|
) {
|
||||||
|
const ext = new RedisSyncExtension({
|
||||||
|
redis: new FakeRedis(bus) as any,
|
||||||
|
pack: pack as any,
|
||||||
|
unpack: unpack as any,
|
||||||
|
serverId,
|
||||||
|
customEvents: customEvents as any,
|
||||||
|
customEventTTL: 30_000,
|
||||||
|
});
|
||||||
|
// Doc is NOT loaded on this instance -> handleEvent takes the remote/proxy path.
|
||||||
|
(ext as any).instance = { documents: new Map() };
|
||||||
|
return ext;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('RedisSyncExtension custom-event error propagation', () => {
|
||||||
|
let unhandled: unknown[];
|
||||||
|
let onUnhandled: (e: unknown) => void;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
// Fake timers so the 30s TTL fallback timer never fires (and never dangles).
|
||||||
|
jest.useFakeTimers();
|
||||||
|
unhandled = [];
|
||||||
|
onUnhandled = (e) => unhandled.push(e);
|
||||||
|
process.on('unhandledRejection', onUnhandled);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.off('unhandledRejection', onUnhandled);
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
const flush = async () => {
|
||||||
|
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
it('owner publishes an error-carrying reply (no unhandledRejection) when the remote handler throws', async () => {
|
||||||
|
const bus = new FakeRedisBus();
|
||||||
|
const owner = makeExtension(bus, 'owner', {
|
||||||
|
boom: async () => {
|
||||||
|
throw new Error('kaboom');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Drive the remote branch directly, as if the origin's customEventStart arrived.
|
||||||
|
await (owner as any).handleRedisMessage(
|
||||||
|
Buffer.from('collabMsg:owner'),
|
||||||
|
pack({
|
||||||
|
type: 'customEventStart',
|
||||||
|
documentName: 'page.x',
|
||||||
|
eventName: 'boom',
|
||||||
|
payload: {},
|
||||||
|
replyTo: 'collabMsg:origin',
|
||||||
|
replyId: 7,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await flush();
|
||||||
|
|
||||||
|
const replies = bus.published
|
||||||
|
.filter((p) => p.channel === 'collabMsg:origin')
|
||||||
|
.map((p) => unpack(p.message));
|
||||||
|
expect(replies).toHaveLength(1);
|
||||||
|
expect(replies[0]).toMatchObject({
|
||||||
|
type: 'customEventComplete',
|
||||||
|
replyId: 7,
|
||||||
|
error: 'kaboom',
|
||||||
|
});
|
||||||
|
expect(unhandled).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('origin rejects PROMPTLY with the real error (not a TTL TIMEOUT) when the remote handler throws', async () => {
|
||||||
|
const bus = new FakeRedisBus();
|
||||||
|
// Owner already holds the document lock.
|
||||||
|
bus.locks.set('collabLock:page.x', 'owner');
|
||||||
|
makeExtension(bus, 'owner', {
|
||||||
|
boom: async () => {
|
||||||
|
throw new Error('kaboom');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const origin = makeExtension(bus, 'origin', {
|
||||||
|
boom: async () => undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
const promise = (origin as any).handleEvent('boom', 'page.x', { foo: 1 });
|
||||||
|
// Attach a catch immediately so a rejection is never momentarily unhandled.
|
||||||
|
const settled = promise.then(
|
||||||
|
() => ({ ok: true as const }),
|
||||||
|
(e: unknown) => ({ ok: false as const, error: e }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await flush();
|
||||||
|
// Resolves WITHOUT advancing any timer -> the 30s TIMEOUT fallback did not fire.
|
||||||
|
const result = await settled;
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
expect((result as any).error).toBeInstanceOf(Error);
|
||||||
|
expect(((result as any).error as Error).message).toBe('kaboom');
|
||||||
|
expect(unhandled).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('origin resolves with the payload when the remote handler succeeds (unchanged behavior)', async () => {
|
||||||
|
const bus = new FakeRedisBus();
|
||||||
|
bus.locks.set('collabLock:page.x', 'owner');
|
||||||
|
makeExtension(bus, 'owner', {
|
||||||
|
ok: async (_doc: string, payload: any) => ({ echoed: payload }),
|
||||||
|
});
|
||||||
|
const origin = makeExtension(bus, 'origin', {
|
||||||
|
ok: async () => undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
const promise = (origin as any).handleEvent('ok', 'page.x', { foo: 1 });
|
||||||
|
await flush();
|
||||||
|
await expect(promise).resolves.toEqual({ echoed: { foo: 1 } });
|
||||||
|
expect(unhandled).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -51,9 +51,15 @@ export class RedisSyncExtension<TCE extends CustomEvents> implements Extension {
|
|||||||
private instance!: Hocuspocus;
|
private instance!: Hocuspocus;
|
||||||
private readonly customEvents: TCE;
|
private readonly customEvents: TCE;
|
||||||
private replyIdCounter: number = 0;
|
private replyIdCounter: number = 0;
|
||||||
|
private pendingReplies: Record<
|
||||||
|
number,
|
||||||
|
{
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
private pendingReplies: Record<number, PromiseWithResolvers<any>['resolve']> =
|
resolve: PromiseWithResolvers<any>['resolve'];
|
||||||
{};
|
// @ts-ignore
|
||||||
|
reject: PromiseWithResolvers<any>['reject'];
|
||||||
|
}
|
||||||
|
> = {};
|
||||||
|
|
||||||
constructor(configuration: Configuration<TCE>) {
|
constructor(configuration: Configuration<TCE>) {
|
||||||
const {
|
const {
|
||||||
@@ -176,25 +182,45 @@ export class RedisSyncExtension<TCE extends CustomEvents> implements Extension {
|
|||||||
}
|
}
|
||||||
if (type === 'customEventStart') {
|
if (type === 'customEventStart') {
|
||||||
const { documentName, eventName, payload, replyTo, replyId } = msg;
|
const { documentName, eventName, payload, replyTo, replyId } = msg;
|
||||||
|
let reply: RSAMessageCustomEventComplete;
|
||||||
|
try {
|
||||||
const res = await this.handleEventLocally(
|
const res = await this.handleEventLocally(
|
||||||
eventName as Extract<keyof TCE, string>,
|
eventName as Extract<keyof TCE, string>,
|
||||||
documentName,
|
documentName,
|
||||||
payload,
|
payload,
|
||||||
);
|
);
|
||||||
const reply: RSAMessageCustomEventComplete = {
|
reply = {
|
||||||
type: 'customEventComplete',
|
type: 'customEventComplete',
|
||||||
replyId,
|
replyId,
|
||||||
payload: res,
|
payload: res,
|
||||||
};
|
};
|
||||||
|
} catch (err) {
|
||||||
|
// The remote handler threw (e.g. the markdown->ProseMirror transform in
|
||||||
|
// gitSyncWriteBody can throw on a malformed body). Reply with the error on
|
||||||
|
// the SAME correlation channel so the origin rejects promptly with the real
|
||||||
|
// message instead of waiting out customEventTTL as a generic 'TIMEOUT'.
|
||||||
|
// Catching here also keeps the throw from escaping this async messageBuffer
|
||||||
|
// listener as an unhandledRejection on the owning instance.
|
||||||
|
reply = {
|
||||||
|
type: 'customEventComplete',
|
||||||
|
replyId,
|
||||||
|
payload: undefined,
|
||||||
|
error: err instanceof Error ? err.message : String(err),
|
||||||
|
};
|
||||||
|
}
|
||||||
this.pub.publish(`${replyTo}`, this.pack(reply));
|
this.pub.publish(`${replyTo}`, this.pack(reply));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (type === 'customEventComplete') {
|
if (type === 'customEventComplete') {
|
||||||
const { replyId, payload } = msg;
|
const { replyId, payload, error } = msg;
|
||||||
const resolveFn = this.pendingReplies[replyId];
|
const pending = this.pendingReplies[replyId];
|
||||||
if (!resolveFn) return;
|
if (!pending) return;
|
||||||
delete this.pendingReplies[replyId];
|
delete this.pendingReplies[replyId];
|
||||||
resolveFn(payload);
|
if (error !== undefined) {
|
||||||
|
pending.reject(new Error(error));
|
||||||
|
} else {
|
||||||
|
pending.resolve(payload);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { socketId } = msg;
|
const { socketId } = msg;
|
||||||
@@ -273,11 +299,22 @@ export class RedisSyncExtension<TCE extends CustomEvents> implements Extension {
|
|||||||
};
|
};
|
||||||
const msg = this.pack(proxyMessage);
|
const msg = this.pack(proxyMessage);
|
||||||
this.pub.publish(`${this.msgChannel}:${proxyTo}`, msg);
|
this.pub.publish(`${this.msgChannel}:${proxyTo}`, msg);
|
||||||
// @ts-ignore
|
// Manual deferred (no Promise.withResolvers) so this runs on Node < 22 too.
|
||||||
const { promise, resolve, reject } = Promise.withResolvers();
|
let resolve!: (v: unknown) => void;
|
||||||
this.pendingReplies[replyId] = resolve;
|
let reject!: (e: unknown) => void;
|
||||||
|
const promise = new Promise((res, rej) => {
|
||||||
|
resolve = res;
|
||||||
|
reject = rej;
|
||||||
|
});
|
||||||
|
this.pendingReplies[replyId] = { resolve, reject };
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
// Fallback for a genuinely lost reply. A handler that threw now rejects
|
||||||
|
// promptly via the error-carrying customEventComplete above; this TIMEOUT
|
||||||
|
// only fires when no reply ever comes back.
|
||||||
|
if (this.pendingReplies[replyId]) {
|
||||||
|
delete this.pendingReplies[replyId];
|
||||||
reject('TIMEOUT');
|
reject('TIMEOUT');
|
||||||
|
}
|
||||||
}, this.customEventTTL);
|
}, this.customEventTTL);
|
||||||
return promise as Promise<ReturnType<TCE[TName]>>;
|
return promise as Promise<ReturnType<TCE[TName]>>;
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user