Commit Graph
11635 Commits
Author SHA1 Message Date
DarkSky 6f9f1cace5 refactor(workspace): dissolve native-playground into domain directories 2026-11-27 06:55:47 +09:00
DarkSky 9cd813275b refactor(server): isolate v0.27.5 compatibility code and track its exit
Move the userspace SessionRedis lock bridge and the lazy root doc lifecycle
migration into server-sync/src/legacy_compat. Mark every remaining
v0.27.5 compatibility point with a compat tag.

Add docs/post-cutover-ablation-backlog.md with the exit check and removal
scope of each tag. L0 Tier A gate 7 now checks that tags and entries match
one to one.
2026-11-27 05:48:02 +09:00
DarkSky 302e3d853d refactor(server): align transcript upload limits and trim hot paths
Return 403 ACTION_FORBIDDEN while Copilot is off.

Parse multipart GraphQL requests with the v0.27.5 upload limits. A
non-file field holds at most 1000000 bytes, a file at most 100 MiB, and a
request at most 32 files and map entries. Each limit returns 413 Payload
Too Large.

Limit JSON GraphQL bodies to 16 MiB.

Keep transcript slices in their upload files and leave the 50 MiB slice
check to the transcript runtime, after its duplicate-task check. Drop the
total upload cap. Read at most 100 MiB in setBlob.

Close dedicated session connections on every exit path. Take the domain
workspace lock with one blocking advisory lock.

Cache the search projection probe per storage. Compute
StorageBackendSpec::backend_identity without a client.

Use one millisecond renew script in server-worker. Split the node-semver
parser out of version_guard, and bound the invalid range log.

Remove the manifest test hook from the assetpack read path.
2026-11-27 05:47:27 +09:00
DarkSky 5b79dd4a69 refactor(server-db): isolate the v0.27.5 Prisma baseline in phase_a_compat
Move the _prisma_migrations replay, the top-level transaction stripping,
and the schema_baseline_0275 gate into phase_a_compat::prisma_baseline.
schema.rs keeps the native component migrations and calls the baseline
through one entry point.

Close the dedicated schema session connection on every exit path.

Add bounded reads (get_limited) and signed downloads (presign_get) to
BlobStorageBackend. The fs and assetpack backends check the size before
they read and cannot sign downloads. S3 signs with SigV4, and R2 behind a
signing worker signs with the upload URL prefix.

Read error bodies up to 64 KiB, keep the raw R2 sign key, and read the
download URL lifetime from presign.expiresInSeconds.
2026-11-27 04:33:12 +09:00
DarkSky f46af9a696 feat(server): add DynamicBlobStorage hot reload for copilot.storage 2026-11-27 02:47:56 +09:00
DarkSky b5b4fcb7e0 feat(backend): add Copilot embedding SPI and GraphQL resolvers 2026-11-26 19:02:48 +09:00
DarkSky 1ec9019fcb feat(server): add copilot transcript SPI and GraphQL contract 2026-11-26 17:59:24 +09:00
DarkSky 49a37caf3d feat(server-blob): upgrade assetpack crates and add precomp2 config toggle
Upgrade assetpack-core to 0.4.2 (default-features = false, file-transform),
assetpack-transform-precomp2 to 0.4.4 (precomp2 0.3.4), brotli to 9, and
zstd to 0.14, and drop the direct lzma-rust2 dependency.

Refactor AssetpackBlobStorage onto sqlx SqlitePool, FileTransformConfig::fast,
FileReader, and TransformDecoderRegistry with zero-clone chunk reads, separate
read/write/transform semaphores, manifest-only promote_object, and Unix-second
object/cache timestamps. Add config.precomp2 (default true), reject precomp2 on
fs configs in both validation and startup parsing, document v0.27.5 coexistence
in docs/rollout-coexistence.md, and cover real 0.1.0 interop, PCF2 segment
bombs, and 16000x16000 PNG regressions.
2026-11-26 14:22:39 +09:00
DarkSky 6b74655aee feat(server): add BYOK SPI and GraphQL contract surface 2026-11-26 09:00:57 +09:00
DarkSky 719a791c0c feat(server): add copilot graphql surface and rest routes
Expand CopilotRuntimeSpi with neutral session, history, quota, route
option, attachment, and SSE streaming methods. Add the matching Copilot
GraphQL types, UserType.copilot and UserType.quotaUsage resolvers,
ServerFeature::Copilot gating, canonical error mappings, and the seven
/api/copilot/* REST routes in server-http.
2026-11-26 07:37:49 +09:00
DarkSky 3bbac69479 fix(search): extract inline doc references like the v0.27.5 reader
The search extractor did not read inline `reference` attributes in rich
text, so a doc that links to another doc only through an inline mention
did not show as a backlink. It also dropped `prop:params` of linked and
synced doc embeds, and it did not index database columns, table cells
or LaTeX.

- Read the `reference` attribute of the visible runs in `prop:text` of
  paragraph, list and code blocks. Parse each `reference` format once,
  so a long run of text under one reference costs linear time.

- Keep `ref` unique by its full string and push the `pageId` of each kept
  `ref` to `ref_doc_id`, so the two lists stay in step. Check database
  cells one at a time, as the reader does.

- Serialize `ref` as `JSON.stringify({ docId, ...params })`. Spread
  strings and arrays by index, put index keys first, and format numbers
  as ECMAScript does.

- Keep only the `docId` when the params are larger than 256 KiB, nest
  too deeply, have too many entries, or pass the 16 MiB budget of the
  block. Check duplicates by the hash of the full reference, so such a
  reference does not merge with a different reference to the same doc.

- Merge `prop:params` into the `ref` of `affine:embed-linked-doc` and
  `affine:embed-synced-doc`, and keep an empty `pageId`.

- Index the database title, column names and select options from `Y.Map`
  columns. Read cell references from `Y.Text` or from boxed text with a
  truthy marker. Add `databaseName` to database blocks and row paragraphs.

- Read the text of each flavour as the old server does. Read rich text
  only from `Y.Text`. Index the table cells in key order and the LaTeX
  source.

- A note, frame or edgeless text with no text of its own joins the
  text of its direct children, up to 1 MiB. Each child gives its text to
  one container only.

- Index no text for doc embeds and bookmarks. Skip blocks with only
  white space, and keep bookmark blocks.

- Raise `SCHEMA_FINGERPRINT` to 2, so that startup builds a new generation
  and reprojects docs that did not change. Retire drained generations of
  any schema version.

- Move the `TestDoc` builder to `tests/support`. Test each flavour, the
  params spread, malformed input, the time for many runs and references,
  backlinks through `search` and `aggregate`, and the schema upgrade.
2026-11-26 06:34:59 +09:00
DarkSky 99791c3bc0 chore(backend): upgrade y-octo to 0.4.2 and harden sync boundaries
- Upgrade `y-octo` to `0.4.2` (`y-octo-core 0.1.1`) in `packages/backend`
  and add `y-octo-core` to `server-sync` and `server-domain` for write-boundary
  v1 scanning.
- Reject new zero-length struct updates in `server-sync::storage::validate_doc_update`
  and `server-domain::workspaces::create_workspace_with_init` via
  `y_octo_core::decoder_v1::decode_update_v1` while keeping persisted
  historical zero-length reads intact.
- Align workspace lifecycle root-doc decoding to `WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS`
  (`max_structs = 16_000_000`), propagate `ReadError::ResourceLimit` before
  committing `storage_reconciliation_checkpoints`, and preserve the
  `[affine-doc:resource_limit]` marker in `server-domain::doc_sharing`.
- Keep `ReadError::IncompleteSnapshot` fallback to `Doc::try_from_binary_v1`
  in `server-sync` and `server-domain` while enforcing `ReadLimits`.
- Add regression tests for cross-frame zero-length poisoning, workspace init
  zero-length rejection, legacy zero-length recovery, multi-client clock gaps,
  alias `ResourceLimit` markers, and lifecycle `ResourceLimit` rollback plus retry.
2026-11-26 05:42:25 +09:00
DarkSky 70173e6565 feat(backend): add billing GraphQL resolvers, SPI, and disposition handler 2026-11-25 21:40:22 +09:00
DarkSky 8c9f4512d5 feat(backend): add public HTTP surfaces and maintenance workers
Implement static asset hosting (Selfhost and Front canary Web Mobile shell), SSR document renderer with ACL-backed preview exposure, HTML head/avatar OG metadata, and iterative bounded Markdown rendering skipping affine:surface and edgeless notes, worker proxy (image-proxy and 2 MiB link-preview) with bounded cache and shared Redis Hash Lua/memory throttling with SHA-256 tracker hashing, telemetry collection with shared version/throttle guards, per-method invalid origin messages, and bounded param flattening, GraphQL CR comment depth pre-scan hardening, and periodic background maintenance workers with slash-separated advisory locks and pending-updates backlog gauge.
2026-11-25 18:55:14 +09:00
DarkSky 69bacafdad feat(http): wire multipart blob routes, storage hot-reload, and boot_storage 2026-11-25 18:55:14 +09:00
DarkSky 51b24de310 feat(storage): add multipart, assetpack, reconciliation, and search wire tests 2026-11-25 17:27:48 +09:00
DarkSky 51c7cd31a5 feat(server): add workspace MCP credentials, GraphQL resolvers, and stateless JSON-RPC transport 2026-11-25 14:10:29 +09:00
DarkSky 55adbc6080 feat(server): add calendar sync service, GraphQL resolvers, and webhook REST routes 2026-11-25 14:10:29 +09:00
DarkSky 3304aaa4cf feat(server): add calendar provider adapters, crypto, iCal parser, and OAuth state store 2026-11-25 14:09:03 +09:00
DarkSky c043f6c7ac feat(server): add security challenges, signing key rotation, and UserType.token
Implement single-transaction security challenges (email verification, password change/set, email change with percent-decoding and realtime user-updated fan-out), admin session signing key rotation/deletion with strict verify_until boundary and parent token TTL policy, UserType.token, Query.error, and GraphQL strict throttling.
2026-11-25 10:01:21 +09:00
DarkSky 2f41f8977c feat(server): add login OAuth/OIDC, PostgreSQL captcha, and strict throttling
Implement OAuth/OIDC preflight, atomic runtime_states claim (3h TTL), bounded TTL discovery/JWKS caching, ring/p256 JWT verification across RS/PS/ES algorithms, Apple args secret normalization, PostgreSQL-backed Hashcash and Turnstile captcha, and request-level strict throttling.
2026-11-25 09:56:04 +09:00
DarkSky ed2852614d feat(server): add admin console workspace, dashboard, shared-link, and mail-delivery queries
- Add AdminService in server-domain for workspace listing, counts, details, member/shared-link lookups, workspace updates, dashboard metrics, shared-link pagination, and mail-delivery aggregates.
- Expose adminWorkspaces, adminWorkspacesCount, adminWorkspace, adminUpdateWorkspace, adminDashboard, adminAllSharedLinks, and adminMailDeliveries in server-http GraphQL.
- Update packages/backend/AGENTS.md with AdminService and admin console query documentation and extend integration tests.
2026-11-25 09:24:01 +09:00
DarkSky f218b68e4b feat(server): add admin user management, config validation, doc analytics, and realtime topic tests
- Implement admin user CRUD, feature updates, batch import, enable, and recreate-for-ban transaction semantics in UserService.
- Derive ServerConfigType oauthProviders and OAuth/Captcha feature flags dynamically from app_configs and resolve availableUpgrade on demand via safe_fetch.
- Add appConfigMetadata and dry-run validateAppConfig with secret redaction and env-only key rejection.
- Add workspaceRolePermissions and DocType analytics/lastAccessedMembers with Doc.Read and Doc.Analytics permission checks.
- Wire WorkspaceService to EventBusPublisher for single notification.count.changed emission on invite, accept, and approve flows and add integration tests.
2026-11-25 09:21:34 +09:00
DarkSky 9603b4b762 feat(server): add SQL manifest, safe_fetch, route matrix, and client version guard
Add the server foundation contracts for SQL execution order, outbound SSRF
protection, deployment and role route isolation, and client version control:

- Add the ordered SQL manifest (`packages/backend/server-db/sql-manifest.json`)
  and check manifest coverage and SHA-256 digests in `check-l0-tier-a.mjs`.

- Add `server_domain::safe_fetch` with pinned DNS resolution, per-origin
  private network allowlist, redirect header filtering, cross-origin body
  replay blocking, and legacy error envelope mapping.

- Add `RouteMountMatrix` across `(DeploymentMode, dev_mode, ServerRole)` with
  modular REST and GraphQL route wiring and `ServerExtension` isolation.

- Enforce `client.versionControl` with cached `AppConfigService` snapshots,
  anonymous fast-path short-circuiting, npm semver range parsing, named guard
  coverage on public auth endpoints, and read-only cookie session resolution
  with TTR refresh.
2026-11-25 04:12:12 +09:00
DarkSky 42a52df55c fix(server-domain): box partial cleanup on DeleteUserError 2026-11-24 23:58:11 +09:00
DarkSky af0d124d5d feat(server): add lockless compaction CAS, search projection v6, and server-search
Refactor document compaction and search projection to remove cross-workspace lock contention and hold zero locks during CRDT merges.

Document compaction and user deletion changes:
- Replace single-transaction compaction with lock-free reads, owned-permit blocking CRDT merges, and short strict-CAS write transactions.
- Retry compaction on snapshot or update CAS mismatches and PostgreSQL 40P01 deadlocks.
- Replace full-table pending update grouping with a rotating primary-key loose index scan and per-batch quota cache.
- Delete owned personal workspaces in individual short transactions with post-lock Team verification and partial cleanup returns.

Connection, rate-limit, and test harness changes:
- Set default statement and idle transaction timeouts on dedicated PostgreSQL session connections.
- Run deferred invite rate-limit effects only after rejected invite transactions roll back cleanly.
- Pass prebound SMTP sinks in parity-harness replay tests to eliminate ephemeral port races.

Search projection v6 and pure-Rust runtime changes:
- Add search_projection_v6.sql with per-workspace advisory locks, post-lock mode re-checks, and a 30s pre-expiry dual-lock bridge.
- Skip steady-state workspace_states updates during ordinary document snapshot writes to remove hot-row contention.
- Validate forward-compatible contiguous prefixes in native_schema_migrations during rolling upgrades.
- Add pure-Rust server-search (disabled by default) with committed marker-XID fences, deferred GC progress retention, repeatable-read ACL snapshots, and GraphQL resolvers.
2026-11-24 23:36:03 +09:00
DarkSky fe911cf25e fix(license): propagate schedule confirmation error in sync_workspace_seats
Return a DomainError when installed_licenses.validated_at fails to update after remote seat synchronization.
2026-11-24 18:41:18 +09:00
DarkSky 1d6fd58258 feat(backend): add doc sharing, histories, comments, notifications, open-app, and license
Add Rust domain services, GraphQL resolvers, REST routes, and realtime RPC
handlers for public docs, grants, histories, comments, notifications, user
settings, Open-App sign-in, and self-hosted licenses.

- Add DocSharingService, public-docs routes, y-octo root-doc filtering, and
  realtime share-state and grants RPCs.

- Add DocHistoryService, snapshot recovery, update compaction, and expired
  record cleanup.

- Add CommentService, NotificationService, user settings, Open-App codes,
  SelfhostLicenseService, and BillingSpi.

- Run 9 deterministic Cloud E2E specs in CI, remove waitForTimeout calls,
  and add collaboration parity checks.
2026-11-24 17:25:29 +09:00
DarkSky ae1bd232db feat(server): add public API parity and cloud E2E cutover for affine-server
Add public-repo API parity to `affine-server` and run the core cloud
Playwright suite against the Rust all-in-one server.

- Add HS256 Bearer access tokens, native session exchange, refresh,
  revoke, and list REST endpoints, login preflight, profile updates,
  WebP avatar transcoding and safe removal, and a distributed-locked
  expired-session cleanup worker with background lease renewal.

- Unify workspace and per-document ACL evaluation (`acl.rs`), split
  REST and GraphQL modules, and add workspace member management,
  ownership transfer with readonly and quota invalidation guards, atomic
  invite links, `createWorkspace(init)` transactional root snapshots,
  `DocType`, `DocPermissions`, `createBlobUpload`, `calendarProviders`,
  and SocketIO realtime workspace access and config rooms.

- Extract reachable blob keys with `y-octo` bounded BFS under
  `REPEATABLE READ` snapshots with pre-merge budgets and bounded caching,
  check per-doc ACL and reserved doc isolation on source-scoped blob
  routes, paginate `readable-blob-manifest/v1` with SQL cursor pushdown,
  and reject legacy blob reads with `403 UNSUPPORTED_CLIENT_VERSION`.

- Keep fresh DB bootstrap on the default v1 sync protocol until
  activated, and accept both absent (v1) and active (v2) lifecycle
  checkpoints on existing databases.

- Add `AFFINE_E2E_RUST_SERVER=1` Playwright support and a
  `cloud-e2e-rust-server` CI job, extend the live parity scenario to
  23 steps, and lower `waitForTimeout` usage from 336 to 312 (ratchet
  from 324 to 316).
2026-11-24 07:59:26 +09:00
DarkSky dece75f25a feat(server): add billing subject, rate limit SPI, and userspace mutex
Add `BillingSubject` to `AccessGrant` in `server-types` and re-export it from `server-spi`.
Remove the direct `entitlements` SQL query from `UserType::quota` in `server-http`.
Resolve personal storage quota from `AccessGrant.billing_subject` alone.

Add `RequestSource`, async `RateLimitPolicy`, and `CommunityRateLimitPolicy` to `server-spi` and `ServerExtension`.
Remove duplicate `AuthMailQuotaPolicy` from `server-domain`, add pure-Rust `contains_url_or_domain`, and add batch `invite_members_with_source`.
Wire `RateLimitPolicy` with on-demand `RequestSource` into `AuthService`, `WorkspaceService`, `server-http`, and `affine-server`.
Add `InvalidationHintV1::QuotaEntitlement` and `serve_with_extension_and_init` for startup hooks before serving requests.

Upgrade `RedisMutex` in `server-worker` with cached connections, lock-free connect, cancel-safe Lua lock retry, pre-commit fencing, and cancel-safe release.
Wire `server-sync` userspace writes (`MutexLock:userspace:<user_id>:<doc_id>`) to `RedisMutex` on `SessionRedis` with millisecond timestamps, upfront DB permits, lease renewal, and pre-commit fence rollback.
Handle empty-table insert conflicts via `ON CONFLICT DO NOTHING` with a `FOR UPDATE` merge fallback.

Update `packages/backend/AGENTS.md` and ignore pre-signed native license JSON in `.prettierignore` and `.oxlintrc.json`.
Extend `scripts/ci/check-l0-tier-a.mjs` to block non-test `entitlements` SQL queries in `server-http` and check documented Rust types.
Replace 22 active `waitForTimeout` calls in 12 local E2E specs with state assertions and lower `scripts/ci/l0-ratchet.json` from 358 to 336.
2026-11-23 20:24:28 +09:00
DarkSky 35e81338e9 chore(server): refresh oracle contract digests for 0.27.5 sync baseline
Re-extract frozen v0.27.5 server contracts after rebasing onto canary.
Update socketio-events.json and manifest.json digests to match the current sync gateway source.
2026-11-23 17:41:00 +09:00
DarkSky c245d8e1f7 feat(server): add domain, mail, blob, sync services and writing rules
Add server-domain, server-mail, server-blob, and server-sync under packages/backend with y-octo 0.4.0.
Wire auth, blob, mail worker, and Socket.IO routes into server-http and affine-server.
Extend the parity harness and CSF frame audit checks.
Fix mail error redaction, expired terminal error codes, database clock reads in blob checks, and permission docs.
Add the STE writing skill and update AGENTS.md rules.
2026-11-23 16:04:20 +09:00
DarkSky b375374c7f refactor(server): move server crates under packages/backend and upgrade y-octo to 0.4.0
Move the server Rust workspace directly under packages/backend.
Exclude native and server from that workspace.
Move frame-audit to tools/frame-audit as a standalone crate.
Isolate packages/backend/native under the root workspace.
Upgrade y-octo to 0.4.0 in native-playground and remove the old removal workarounds.
Update CI workflows, static gates, and docs for the new paths.
2026-11-23 15:12:26 +09:00
DarkSky ec1093007c fix(ci): ignore bundled license in formatter, harden shared container startup, and select M1 crates in run.json
- .prettierignore: exclude pre-signed crates/server-types/assets/*.license.json from oxfmt/prettier.
- crates/test-db-harness/src/docker.rs & crates/AGENTS.md: raise SHARED_START_TIMEOUT from 10s to 60s
  to match PG READY_TIMEOUT on cold CI runners, serialize same-process ensure_shared calls with an
  in-process Mutex, and update last_error in SharedAction::Wait instead of surfacing stale Conflict.
- .github/workflows/native-playground.yml: include all six M1 server crates in run.json --select.
2026-11-23 13:58:04 +09:00
DarkSky 82e166f49b test(parity): frozen v0.27.5 self-parity run, web build lane, fewer waitForTimeout
Parity harness:
- `compare` re-runs the comparison on a recorded report offline through
  the same protocol/database/effects path as live runs, and like `run`
  rejects scenarios without steps.
- `require` lists per-side checks (equals, length, contains); an unmet one
  is a difference at /require/<side><pointer>, so two sides failing the
  same way are never green.
- Timestamps also accept RFC 2822 HTTP dates (cookie Expires), with both
  sides in the same format.
- Socket.IO `record_events` limits which pushed events are reported;
  `wait_event` still sees all of them.
- scripts/run-v0275-self-parity.mjs boots two @affine/server instances of
  the checkout given by --server-root (the frozen baseline,
  darksky/before-stable-fix c2929acf2d) on
  leased PG16 clones, two Redis containers, two SMTP capture ports and
  separate HOMEs, in a run directory of its own; runs the data migrations,
  validate-cutover and workspace lifecycle activation; replays
  scenarios/v0275-self-parity.json (/info, GraphQL setup/auth/workspace/
  quota, Socket.IO join/push/load, a real test mail) and requires 0
  differences across protocol, all user tables, SMTP and Redis plus every
  requirement (doc accepted and stored, schema_baseline_0275 checkpoint,
  one mail, invalidation and event bus messages), then a tampered
  right-side DB row and GraphQL field reported at exactly their paths.
  Only a passing run writes --record, atomically, with the server SHA;
  cleanup failures fail the run; a temporary static manifest is removed.
- tests/v0275_self_parity.rs replays a committed recording of the frozen
  baseline, injects one change per dimension and checks that both sides
  losing the same results fail their requirements.

CI:
- np-web-build.yml builds @affine/web, @affine/mobile and @affine/admin on
  ubuntu-24.04 without Electron/Playwright/Sentry downloads, each bundle
  within eight minutes, and checks the bundle entry exists;
  native-playground.yml calls it only when frontend sources change.

Test debt:
- Delete the unused blocksuite std inline test helper and the unused
  selectVisibilitySelector; drop sleeps already covered by auto-waiting
  assertions and click(); poll getIndexCoordinate per animation frame.
  waitForTimeout ceiling 378 -> 370.
2026-11-23 13:58:04 +09:00
DarkSky 0aec3f7364 feat(server): add server-spi, server-http, server-worker, and affine-server multi-role skeleton
Stacked cleanly onto W1-A final (ee1463d7) with zero modifications to
crates/server-types or crates/server-db:
- crates/server-spi: canonical QuotaGate (fail-closed on 0-seat readonly and
  checked_add seat overflow guard), SessionPolicyHook, CopilotPolicySpi,
  ServerExtension traits, CommunityExtension, and real PostgreSQL transactional
  proof test (txid_current() equality + atomic rollback).
- crates/server-http: axum 0.8 + async-graphql 7 skeleton with role-isolated routes
  (/healthz, /readyz with 2s PG/Redis timeouts, /info, /graphql exposing
  v0.27.5 Query.workspace(id) -> WorkspaceType with real DB usage queries inside
  WorkloadTier::InteractiveRead TieredTx), plus legacy_compat::{quota, errors}
  verified against tests/oracle-contracts/v0.27.5/schema.gql.
- crates/server-worker: SessionRedis-compatible RedisMutex (SET NX EX + atomic Lua
  renew/unlock), v2: private keyspace helper, CancellationToken, and WorkerSupervisor
  graceful lease drain with real Redis integration tests.
- crates/affine-server: single-binary multi-role CLI (--role, --port 0, default
  ensure_schema_ready() startup gate with --skip-schema-check), reusable library
  entrypoints (build_server, serve_with_extension, build_app_and_serve),
  Arc<AppState> + ArcSwap<RuntimeConfig>, SIGTERM/SIGINT drain, and real PG+Redis
  E2E tests (< 200ms cold boot, graceful lock release, and stepping-stone gate).
- crates/Cargo.toml, crates/Cargo.lock, crates/AGENTS.md: add the 4 crates to the
  8-member workspace while preserving W1-A's server-types and server-db entries.
2026-11-23 13:58:04 +09:00
DarkSky c57f98ba6e feat(crates): add server-types and server-db foundations 2026-11-23 13:58:04 +09:00
DarkSky 31df4f3917 fix(test-db-harness): converge concurrent shared container starts and require owners for removal
- ensure_shared: a caller that wins the start returns its container as
  soon as its port is published; a caller that loses the race for the
  name waits with short backoff until the winner's container runs. The
  10 s window starts after the caller's own first lookup or start, so
  pulling the image is not counted, and a last lookup runs before giving
  up. A stopped leftover of ours is removed without force and started
  again; a paused or unknown-state shared container is kept and
  reported, since it may hold other runs' databases.
- remove_owned takes a required, non-empty owner run and removes only
  containers labeled affine.test.shared=false, so the shared container
  and containers without the shared label are always refused. The
  owner-less Container::remove is gone; drop passes this run's id.
- Tests: eight callers cold-starting one fresh shared container converge
  on one container and port; a paused shared container is reported and
  kept; every container state maps to its action; empty owners and
  containers missing the shared label are refused.
2026-11-23 13:58:04 +09:00
DarkSky 4a08e49642 feat(ci): add crates/ test harness workspace, shared frame audit and fast CI lanes
- crates/: standalone server-side Rust workspace (resolver 3, edition
  2024, own lock and toolchain 1.98.1)
  - frame-audit: the one serde-only FrameSnapshot schema and audit
    engine; native-playground's ui depends on it by path and re-exports
    it. The six structural rules keep their ids; evidence rules (first-
    line baseline, footer reverse wrap, divider placement, static cursor,
    overlay z-order via renderer hit-test probes, text truncation) report
    missing evidence instead of skipping, and concentric radii reject
    negative and step-limited radii. Old snapshots still load.
  - test-db-harness / affine-test-env: a marker-checked PostgreSQL test
    cluster (explicit URL or a reused machine-wide pgvector container),
    read-only migration-digest templates with Prisma bookkeeping,
    template clones under owner-token leases, and an orphan reaper. Clone,
    heartbeat, release and reap serialize per database on an advisory
    lock and re-check under it; every maintenance connection re-checks
    the cluster marker. Private Redis or a prefix-isolated URL. Images
    pinned to multi-arch digests; only private harness containers of the
    expected run, by full id, can be removed. run.json reports.
- scripts/ci/check-l0-tier-a.mjs: dependency-free gates for crates/
  layering and hygiene, a waitForTimeout/.skip ratchet with per-file
  ceilings, workflow references, pinned test images and .gitignore.
- native-playground.yml: resolve the change base to a commit SHA, call
  np-web-fast.yml (lint, typecheck, Node-only Vitest projects without
  Electron, browser or Rust-binary dependencies) when web sources
  change, and always run L0, the frozen server contract checks, crates/
  and the parity harness (fmt, clippy, tests against real services).
- Web lint and format: the frozen contract artifacts and
  blocksuite/native-playground (checked by its own lane) are ignored via
  .prettierignore, from which .oxlintrc.json is generated; the server
  contract and parity harness scripts are formatted and lint-clean.
- tools/parity-harness/rustfmt.toml keeps the default style there.
- Remove the copilot cron workflows and the skipped migration spec;
  ignore test-results/ and .artifacts/.
2026-11-23 13:58:04 +09:00
DarkSky 616597ec28 test: freeze server oracle contracts and add parity harness 2026-11-23 13:58:04 +09:00
DarkSky 033803f1a4 refactor(native-playground): modularize large modules and tighten render hot paths
Split oversized modules across crates/doc and crates/playground into cohesive submodules under 800 non-test lines, enable workspace-wide Rust structure checks in scripts/check-invariants.sh, add solid-quad fast path in WGSL and Metal shaders, remove redundant page viewport background overdraw, and cache theme token lookups.
2026-11-23 13:58:04 +09:00
DarkSky ebc5eb6fb2 feat(native-playground): add interactive edgeless authoring and polish 2026-11-23 13:58:04 +09:00
DarkSky 5565057fb6 feat(playground): read and render typed whiteboard surfaces 2026-11-23 13:58:04 +09:00
DarkSky ba55dd7058 feat(native-playground): add GPU 2D transforms, procedural dot-grid, and Edgeless Note/Frame/Text canvas
Add GPU paint transform and local content-mask stacks across Metal, wgpu, and WebGL2 shaders, quarter-octave glyph zoom bucketing, and procedural single-draw-call dot-grid backgrounds in crates/ui (plus TextSystem::line_gap).

Implement the Edgeless spatial canvas (camera, dot-grid, Surface-parented Frame and EdgelessText, Note scale/collapse/style parity, cached per-note BlockFlow with zero pan/zoom relayouts, and zoom bar), register edgeless_1k_pan_zoom_blocks_relayout in perf/compare-n3.mjs, and add cross-backend headless regression tests and Chromium WebGL2 smoke assertions.
2026-11-23 13:58:04 +09:00
DarkSky 5b82831fd8 feat(native-playground): add slash menu, formatting toolbar, drag handle, and interactive block controls
Page mode gains its floating controls on top of the page editor: a slash menu typed in the document, a formatting toolbar over the text selection, a gutter drag handle with a drop indicator, and clickable to-do boxes, toggle and heading chevrons and a code copy button. The editor stays the single owner of the selection, the caret and text edits; every overlay edit goes through its `PageDocSession`, is one undo step, and reaches a live room like any other editor commit.

- crates/playground `overlays.rs` (new): `Overlays` takes an `OverlayScene` (page snapshot, world-space layout, window geometry) with an `OverlayEvent` or a key and answers with `OverlayEffects` (document edits, clipboard text, a timer to start). The `PlaygroundView` glue at the end of the file feeds it input and carries the effects out; `dispatch_overlay` is the entry for pointer listeners, hosts and tests. The overlays read the editor's selection as a `SelectionFormat` (its box, the marks every selected unit carries, the shared alignment) and paint no caret or selection of their own.
- Pointer and keys: a press on the page dismisses the slash menu, the link field and a block drag and then goes to the editor; moves and the release are handled at the window root, so a drag continues outside the page, and a pointer on an open popover does not change the hovered block under it. `editor_key_down` offers every key to the overlays first: an open link field takes every key but the ones that type text, the slash menu takes `Up`, `Down`, `Tab`, `Shift+Tab`, `Enter` and `Escape`, and the rest is the editor's.
- Slash menu: typing `/` at a caret in paragraph or list text, outside inline code, opens the menu on that character, remembered as a relative position, so text a peer inserts before it moves the menu along. The text between the `/` and the caret is both document text and the filter; the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer). Running an item is one `structural_edit` after BlockSuite's `updateBlockType` and `appendDivider`: it removes the typed command, then a paragraph type, a list type or code converts the block with the text it has left (in place within a flavour, as a fresh block across flavours), and a divider goes right below the block, followed by an empty paragraph when the block was the last of its parent. One undo restores the typed command. `Tab` and `Shift+Tab` step through the items, and `Enter` without a match closes the menu without splitting the block. `OpenSlashMenu` keeps a menu with a query row of its own for hosts. Items follow BlockSuite's order in two groups with all six headings listed; each icon sits in a bordered 28 px box; the menu is 8 px round with 4 px padding and 4 px rows, without a border, scrolls under a cap with a thumb and keeps a `No results` row.
- Formatting toolbar: bold, italic, underline, strikethrough, inline code, a link field with `Apply` / `Remove`, and left / center / right alignment above a finished, non-empty selection of paragraph and list text, in one block or across blocks; a selection touching the title or code gets none. It waits while the button of a plain press is held and opens at once on a double or triple click. Marks use the editor's `format_mark`; a link and an alignment run in one `structural_edit`, the alignment on every selected paragraph and list block, empty ones included, and a block that sets no alignment reads as its nearest aligned ancestor's.
- Link field: `LinkBar` is a one-line text input with its own text, selection and input-method composition. While it is open it is the view's text input: every `EntityInputHandler` call goes to it, the document's text, selection and composition stay untouched until `Apply`, and the platform is told whenever it opens, closes or changes. Caret keys, deletion, select-all, copy and cut edit the field, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field.
- Drag handle: shown for the hovered or dragged block, 24 px left of it and at least 4 px from the window edge, one step further out beside a heading's collapse chevron. It draws BlockSuite's grabber, a 4 × 12 px bar that turns into two columns of dots on a pill under the pointer or in a drag. A drag picks the nearest slot among the block's siblings, looked up in one pass over the layout, and drops through `reparent_block`, so numbered runs are renumbered.
- Block controls: 24 px targets toggle `prop:checked` and `prop:collapsed` as isolated undo steps; the chevron turns over 150 ms. A hovered code block offers a copy button that reads `Copied` for 1.5 s on the scheduler clock, and a sideways scroll moves the lines of an unwrapped code block instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections, and pointer hit-testing follow that scroll and stay inside the code area.
- Positioner and motion: the pure, screen-space `place_popover` places a popover `Above` (centered) or `BelowStart` its anchor, flips it at the top bar and the window bottom, and clamps it inside the edge margins on the pixel grid. Popovers fade with an ease-out cubic `EaseOut` evaluated at scheduler time; a fully transparent popover is not mounted, and one fading out carries no listeners.
- crates/playground `editor_session.rs`: the first selection box records `page.selection`; typing `/` reports its position to the overlays, and a remote update moves the typed slash menu with its character; the input handler answers for the link field while that is open; a dropped selection publishes an empty `<pageId>:native` awareness entry, so peers stop drawing the caret and keep the name and color.
- crates/playground `block_flow.rs`: `page_elements` takes a `PagePaint` (a chevron in flight, a code block's scroll); `ScrolledCode` maps carets and selection boxes onto the scrolled lines of a code block; `BlockBody` exposes its chevron and `code_scroll` range, and `PageViewport` maps world rectangles into the viewport element.
- crates/playground `theme.rs`: `PlaygroundTheme::shadows` parses the `--affine-*-shadow` tokens, and `IconPaint::paint_rotated` turns an icon around its center.
- crates/doc: `PageDocSession::correct_numbered_order_from` is public, for a numbered item inserted by a command; `bs_doc_driver` learns the `reorder`, `align` and `link` structural edits.
- `bs-harness`: `render --state <name>` renders one overlay state of the showcase, `audit-states` audits every state in both themes at 1280 px and 320 px, `fps-check` also replays the slash menu and the formatting toolbar opening and closing at 60, 120, 24 and 7 fps, and `record-demo <dir>` writes the audited frames of a 60 fps walk through typing, composition, the slash menu, the toolbar, the block controls and undo.
- `scripts/web-smoke.mjs` opens the link field over a selection in Chromium and checks composition, the paste key and the `paste` event against the hidden textarea, and that the paragraph is untouched afterwards.
- `perf/accepted.json` acknowledges the larger Web bundle and headless binary.
- Tests: popover placement and flipping, easing end states, slash filtering and grouping, typed commands on empty and non-empty blocks with one-step undo, a typed `/` followed through a peer's concurrent edits, slash menu keys, mouse selection into toolbar marks, links and alignment across blocks, the link field as a text input with composition, block controls, code scrolling with local and remote carets, drag reordering, popover hover shielding, narrow windows, overlay edits and a cleared selection reaching the peers of a live room, and the JS room-sync suite observing a native reorder, alignment and link.
2026-11-23 13:58:04 +09:00
DarkSky 222d6d6de0 Add collaborative rich-text editing to the native page 2026-11-23 13:58:04 +09:00
DarkSky bdad4ecff5 feat(native-playground): add BlockFlow page renderer, light/dark themes, and live room sync
Renders any page document in Page mode from the same y-octo CRDT state the JavaScript editor edits, in both themes, on macOS, Linux headless and the Web.

- crates/doc: typed read snapshot (`read.rs`, `PageDocSession::read_page_snapshot`) returning an ordered `PageSnapshot` tree for every supported block flavour with the normalized JSON of each `prop:*`, numbered-list run indices, `prop:textAlign`, the note display modes by their wire values (`both` / `doc` / `edgeless`), detached blocks and lossless `Unknown` blocks; `add_raw_block` for flavours without a typed spec; the room hub now forwards the equal-clock live-to-`null` awareness removal once the last owning connection releases a client; `RoomAwareness::reannounce_local_payload` lands a reconnecting client above the tombstone the relay wrote for it.
- crates/playground `theme.rs`: `PlaygroundTheme::{Light, Dark}` resolved from the generated `tokens.rs` / `icons.rs` (included, never copied), `IBM Plex Mono` registered next to `Inter`, and a top bar theme toggle.
- crates/playground `block_flow.rs`: world-space `BlockFlow` layout mapped to the screen by `PageViewport`, with per-block reuse across passes. Title, paragraphs and headings, quotes, nested bulleted / numbered / to-do / toggle lists, dividers, code, images, bookmarks and unknown-block cards follow BlockSuite's page metrics (collapsing margins, first-line list prefixes, heading letter spacing, 944px container narrowing below 640px). Text alignment is inherited by nested children, a collapsed heading hides its own children and the siblings under it, and remote carets, selections, name tags and presence badges are drawn from `selectionV2` entries of the shown page only.
- crates/playground `rich_text.rs`: `RichParagraph` is the one rich-text engine. `BlockFlow` lays out and paints paragraph and list text with it (`LaidOutRichParagraph::paint_at`) and reads remote carets and selections from its geometry. It now resolves `color` and `background` marks through the theme, follows CSS `bolder`, paints the generated `LinkedPageIcon` for references, wraps a reference as one inline object so the words before it stay on their line, aligns lines left, center or right together with their carets and decorations, and takes its code box metrics from constants a test keeps equal to `tokens/style-oracle.json` instead of embedding the oracle.
- crates/playground `room_client.rs`: sans-I/O `RoomProtocol` for the relay's binary room protocol with `tokio-tungstenite` (`--room` / `--relay`) and browser `WebSocket` (`?room=&ws=`) transports, blob fetch (a bare HTTP/1.1 `GET` over TCP natively, `fetch` on the Web) and reconnect with backoff. Native transports reject `wss://` / `https://` relays up front, and a pending connect times out and never holds up blob fetches or shutdown.
- Images decode PNG, JPEG, WebP, GIF and BMP once; bytes that are no image stay unavailable. A blob the page references before its upload finished is fetched again on the scheduler clock with a backoff capped at 4 s for as long as the page references it, showing `Loading image`, then `Image unavailable`, then the image.
- Deterministic `seed_showcase_doc` workspace when no room is given; `bs-harness render` gains `--theme light|dark` and `--mode page|edgeless`.
- `scripts/web-smoke.mjs` gains `--query` and `--min-title-ink` so a page that arrives over a live room is captured after it rendered.
- `perf/accepted.json` acknowledges the larger Web bundle and headless binary; the comparator's gate self-test no longer depends on the repository's acceptance file.
- Tests: token and block metrics against `tokens/style-oracle.json` in both themes on constants and rendered frames, showcase and edge-content audits across viewports down to 320px, scroll mapping, incremental relayout, text alignment with an inherited child and a remote caret, selection key matching, and live in-process relay tests covering edits, blobs, awareness, a blob uploaded after its image block, and presence after a reconnect.
- @blocksuite/playground: `reusePartialSeedDoc` keeps `doc.load(initFn)` initializers working when a promoted seed winner fills a partially seeded doc (a bare `load()` leaves the initializer for the `load(initFn)` that follows), and `initRoomDocWithSeed` rejects a winner whose seed leaves no `affine:page` root.
2026-11-23 13:58:04 +09:00
DarkSky 25a35c83b8 feat(native-playground): lay out and paint rich paragraphs 2026-11-23 13:58:03 +09:00
DarkSky 4e26a040ee feat(native-playground): add y-octo doc engine, binary room sync, and unified workspace
Unifies the 3-crate native-playground workspace (ui, doc, playground) with:
- crates/doc (#![forbid(unsafe_code)], y-octo 0.3.0, 53-bit JS-safe client IDs, full block & surface element schemas with 0-writeback defaults, blocks-scoped undo/redo with SelectionSnapshot, deterministic RoomAwareness with BlockSuite TextSelectionState, Sans-I/O binary room framing, Axum room hub / bs-relay with WS-only seed-claim FIFO waiter promotion & equal-clock awareness refcount hardening & permissive blob CORS, and bs_doc_driver).
- @blocksuite/sync DocPeer finishPull listener ordering (preserving 0-writeback while capturing mid-handshake edits) and pendingIncomingUpdates subdoc buffer.
- @blocksuite/playground RoomWebSocketClient (+2 awareness clock re-announce on reconnect, disconnect removal before detaching listener, socket-only detached offline fallback, in-place Proxy reuse for partial-seed recovery without destroying shared subdocs, winner flush & non-winner affine:page root wait, ?ws= relay origin forwarding to MockServerBlobSource) + live Rust-JS E2E convergence suite.
- Real doc_1k_edits_ms and room_sync_1k_ops_ms benchmarks in bs-harness bench.
- Updated check-invariants.sh (doc GUI isolation + forbid(unsafe_code)), AGENTS.md active invariants, and native-playground CI workflow (wasm32 doc check, macOS doc tests, and parallel js-room-coop job).
2026-11-23 13:58:03 +09:00
DarkSky 74bcafa70f feat(native-playground): add N-3 perf guardrail, theme/style oracle, and CI self-tests 2026-11-23 13:58:03 +09:00