diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..4aa10a4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +* text=auto eol=lf + +*.gif binary +*.ico binary +*.jpg binary +*.png binary +*.webp binary diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..958943e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,24 @@ +name: Bug report +description: Report reproducible broker behavior without private inference content. +title: 'bug: ' +labels: [bug] +body: + - type: input + id: version + attributes: + label: TabLoom version + validations: + required: true + - type: textarea + id: behavior + attributes: + label: Observed behavior + description: Use synthetic inputs and safe event metadata only. + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Minimal reproduction + validations: + required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..cc29a88 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,23 @@ +## Objective + +Describe the user or operator outcome. + +## Contract impact + +- Requirement IDs: +- Protocol or configuration change: +- Privacy or security change: + +## Evidence + +- [ ] Format, lint, and type checks +- [ ] Unit tests and coverage +- [ ] Library and demo builds +- [ ] Package checks and clean-consumer smoke +- [ ] Browser coordination tests +- [ ] Dependency audit +- [ ] Visual verification when the demo changes + +## Residual risk + +Document any unverified provider, browser, or failure mode. diff --git a/.github/workflows/browser.yml b/.github/workflows/browser.yml new file mode 100644 index 0000000..244194d --- /dev/null +++ b/.github/workflows/browser.yml @@ -0,0 +1,42 @@ +name: Browser conformance + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: browser-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + browser: + name: Browser (${{ matrix.browser }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + browser: [chromium, firefox, webkit] + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + run_install: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm exec playwright install --with-deps ${{ matrix.browser }} + - run: pnpm exec playwright test --project=${{ matrix.browser }} + - if: failure() + uses: actions/upload-artifact@v4 + with: + name: browser-evidence-${{ matrix.browser }} + path: | + playwright-report + test-results + if-no-files-found: ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b47b355 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,57 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + quality: + name: Quality (${{ matrix.os }}, Node ${{ matrix.node }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + node: 24 + - os: macos-latest + node: 24 + - os: windows-latest + node: 24 + - os: ubuntu-latest + node: 26 + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + run_install: false + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm check + - run: pnpm package:smoke + + dependency-audit: + name: Production dependency audit + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + run_install: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm run audit diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..3e65990 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,23 @@ +name: CodeQL + +on: + push: + branches: [main] + pull_request: + schedule: + - cron: '23 3 * * 1' + +permissions: + contents: read + security-events: write + +jobs: + analyze: + name: Analyze JavaScript and TypeScript + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: github/codeql-action/init@v3 + with: + languages: javascript-typescript + - uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..c7f24ac --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,45 @@ +name: Release + +on: + push: + tags: + - 'v*' + +permissions: + contents: write + +jobs: + prerelease: + name: Verify and publish prerelease assets + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: pnpm/action-setup@v4 + with: + run_install: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm check + - run: pnpm package:smoke + - run: pnpm run audit + - run: pnpm exec playwright install --with-deps chromium firefox webkit + - run: pnpm test:browser + - name: Build archive and checksum + shell: bash + run: | + mkdir release + pnpm pack --pack-destination release --silent + version="${GITHUB_REF_NAME#v}" + archive="$(find release -maxdepth 1 -type f -name '*.tgz' -print -quit)" + mv "$archive" "release/tabloom-${version}.tgz" + cd release + sha256sum "tabloom-${version}.tgz" > "tabloom-${version}.tgz.sha256" + - name: Create GitHub prerelease + env: + GH_TOKEN: ${{ github.token }} + run: gh release create "$GITHUB_REF_NAME" release/* --verify-tag --prerelease --generate-notes diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..27c8895 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +node_modules/ +dist/ +dist-demo/ +coverage/ +playwright-report/ +test-results/ +.artifacts/ +*.tgz +.DS_Store +*.log diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..a774a78 --- /dev/null +++ b/.npmrc @@ -0,0 +1,3 @@ +engine-strict=true +prefer-frozen-lockfile=true +strict-peer-dependencies=true diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..c5a267c --- /dev/null +++ b/.prettierignore @@ -0,0 +1,6 @@ +dist +dist-demo +coverage +playwright-report +test-results +pnpm-lock.yaml diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..9e4c08a --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,5 @@ +{ + "semi": true, + "singleQuote": true, + "trailingComma": "all" +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ba9fd29 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,8 @@ +# Repository working agreement + +- Use `Antonio Antenore ` for every local commit. +- Keep `main` releasable and deliver reviewed work through a short-lived branch. +- Prefer typed configuration, explicit ports, and provider-neutral domain code. +- Do not claim live GPU or model evidence when a deterministic adapter produced the result. +- Keep prompt payloads out of telemetry, diagnostics, screenshots, and fixtures. +- Run the full quality gate before publication and verify the published state from a fresh clone. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f819193 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +All notable changes are documented here. + +## [0.1.0-alpha.1] - 2026-07-17 + +### Added + +- Fenced same-origin owner election using Web Locks and persistent epochs. +- Versioned BroadcastChannel protocol with runtime envelope validation. +- Provider-neutral streaming sessions with cancellation, timeout, bounded admission, and typed failures. +- Automatic pending-request redispatch after takeover with stale-attempt rejection and one accepted client terminal. +- Deterministic adapter for repeatable coordination evidence. +- Visual three-page broker lab with topology, controls, safe event lineage, and responsive layouts. +- Unit, coverage, package, and Playwright gates across Chromium, Firefox, and WebKit. +- CI, dependency audit, CodeQL, prerelease archive, and checksum automation. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..298881f --- /dev/null +++ b/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 Antonio Antenore + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1c273c9 --- /dev/null +++ b/README.md @@ -0,0 +1,139 @@ +# TabLoom + +[![CI](https://github.com/aantenore/tabloom/actions/workflows/ci.yml/badge.svg)](https://github.com/aantenore/tabloom/actions/workflows/ci.yml) +[![Browser conformance](https://github.com/aantenore/tabloom/actions/workflows/browser.yml/badge.svg)](https://github.com/aantenore/tabloom/actions/workflows/browser.yml) +[![CodeQL](https://github.com/aantenore/tabloom/actions/workflows/codeql.yml/badge.svg)](https://github.com/aantenore/tabloom/actions/workflows/codeql.yml) + +TabLoom is a same-origin browser inference broker. It coordinates sibling pages so one live page owns the inference runtime while peers stream requests through it. + +It supplies the coordination layer, not a model runtime: exclusive ownership, monotonic fencing epochs, protocol validation, bounded admission, streaming sessions, cancellation, timeouts, takeover, and privacy-safe telemetry. + +> **Alpha:** the release-gated adapter is deterministic simulation. WebLLM and Transformers.js are documented integration seams, not verified GPU or model evidence. + +## Why + +Loading the same local model in every open page can multiply scarce device memory. Browser runtimes already solve inference and generic election packages already solve ownership; TabLoom focuses on the missing inference-specific lifecycle across owner changes. + +## Architecture + +```mermaid +flowchart LR + P1["Peer page A"] <--> C["BroadcastChannel protocol"] + P2["Peer page B"] <--> C + C <--> O["Elected owner page"] + L["Exclusive Web Lock"] --> O + E["Persistent monotonic epoch"] --> O + O --> A["Replaceable inference adapter"] +``` + +- Web Locks elect exactly one owner inside a storage bucket. +- Same-origin storage advances the fencing epoch while the lock is held. +- BroadcastChannel carries runtime-validated, versioned envelopes. +- Ports keep election, transport, clock, IDs, telemetry, and inference replaceable. +- Clients reject stale epochs and accept at most one terminal result per session. + +## Install the prerelease archive + +The first alpha is distributed as a GitHub release archive rather than an npm registry publication. + +```bash +curl -LO https://github.com/aantenore/tabloom/releases/download/v0.1.0-alpha.1/tabloom-0.1.0-alpha.1.tgz +pnpm add ./tabloom-0.1.0-alpha.1.tgz +``` + +Verify the adjacent `.sha256` asset before installing in a controlled delivery pipeline. + +## Quick start + +```ts +import { + DeterministicInferenceAdapter, + createBrowserBroker, +} from '@aantenore/tabloom'; + +const broker = createBrowserBroker({ + adapter: new DeterministicInferenceAdapter(), + config: { + namespace: 'my-app-local-inference', + queueCapacity: 8, + requestTimeoutMs: 30_000, + }, +}); + +const unsubscribe = broker.subscribe((snapshot, event) => { + console.log(snapshot.role, snapshot.epoch, event?.type); + if (event?.type === 'retry') { + // Clear any partial presentation: streaming restarts on the new epoch. + } +}); + +await broker.start(); + +const session = broker.request({ text: 'Explain fenced ownership.' }); +try { + for await (const chunk of session) { + console.log(chunk.text); + } + console.log(await session.result); +} finally { + unsubscribe(); + await broker.stop(); +} +``` + +The deterministic adapter makes lifecycle behavior reproducible. Replace it with an application adapter for a real runtime; see [adapter integrations](docs/integrations.md). + +## Session semantics + +| Concern | Alpha contract | +| ------------------------ | -------------------------------------------------------------------------------------------------- | +| Ownership | One Web Lock holder owns the adapter; peers do not initialize it | +| Fencing | Every owner attempt carries a monotonically increasing epoch | +| Streaming | Chunks are ordered and deduplicated inside the current attempt | +| Takeover | Pending work can restart on a newer owner; observe `retry` and replace partial presentation | +| Terminal state | A client session accepts one completion or typed failure | +| Provider execution | At-least-once across takeover; adapters with external side effects need their own idempotency key | +| Admission | Queue capacity is fixed by validated configuration; excess work fails with `BACKPRESSURE` | +| Privacy-safe diagnostics | Built-in telemetry types expose lifecycle metadata, never request payloads or generated chunk data | + +## Browser requirements + +Serve from HTTPS, or loopback for development. The alpha requires Web Locks, BroadcastChannel, local storage, and cryptographic UUID support in the same storage partition. + +The multi-page suite is locally verified with Playwright 1.61.1 against Chromium 149.0.7827.55, Firefox 151.0, and WebKit 26.5. Each engine exercises one-owner convergence, peer streaming, cancellation, backpressure, and owner takeover. + +## Development + +Requires Node.js 24 or newer and pnpm 11.13.0. + +```bash +corepack pnpm install --frozen-lockfile +corepack pnpm dev +``` + +Open `http://127.0.0.1:4173`, then use **Open sibling tab** to build a visible cluster. + +Run the complete local quality gate: + +```bash +corepack pnpm check +corepack pnpm package:smoke +corepack pnpm test:browser +corepack pnpm run audit +``` + +## Evidence and boundaries + +- [Delivery contract](docs/delivery-contract.md) +- [Architecture decision](docs/adr/0001-browser-broker.md) +- [Threat model](docs/threat-model.md) +- [Compatibility matrix](docs/compatibility.md) +- [Market and build-vs-buy review](docs/market-scan.md) +- [Operations runbook](docs/runbook.md) +- [Visual QA ledger](docs/visual-qa.md) + +Cross-origin coordination, durable recovery after all pages close, mutually untrusted same-origin scripts, and exactly-once provider side effects are intentionally out of scope. + +## License + +Apache-2.0. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..5b241dd --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Security policy + +## Supported versions + +Only the latest published prerelease is supported during alpha development. + +## Reporting + +Use GitHub private vulnerability reporting for security-sensitive findings. Do not place prompts, model inputs, credentials, or other private data in a public issue. + +## Security boundary + +TabLoom coordinates contexts within one browser storage partition and origin. It is not an authorization boundary between untrusted scripts already executing on that origin. + +## Current audit posture + +The production dependency audit reports no known vulnerability at the release threshold. The development graph currently carries one low-severity [esbuild advisory](https://github.com/advisories/GHSA-g7r4-m6w7-qqqr) affecting a Windows development server exposed to untrusted clients. The demo server is fixed to loopback, CI does not expose it publicly, and the dependency will be updated when the Vite toolchain supports the patched esbuild line. diff --git a/demo/App.tsx b/demo/App.tsx new file mode 100644 index 0000000..715ac47 --- /dev/null +++ b/demo/App.tsx @@ -0,0 +1,270 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { + DeterministicInferenceAdapter, + TabLoomError, + createBrowserBroker, + type BrokerEvent, + type BrokerSnapshot, + type DeterministicChunk, + type DeterministicRequest, + type DeterministicResult, + type InferenceSession, +} from '@tabloom'; +import { CollectingTelemetry } from '../src/adapters/runtime.js'; +import { Controls } from './components/Controls.js'; +import { Timeline } from './components/Timeline.js'; +import { Topology } from './components/Topology.js'; +import { LoomMark, ShieldIcon } from './icons.js'; + +type DemoSession = InferenceSession; + +interface DemoConfig { + readonly capacity: number; + readonly delayMs: number; + readonly namespace: string; +} + +export function App() { + const config = useMemo(() => readDemoConfig(), []); + const telemetry = useMemo(() => new CollectingTelemetry(), []); + const adapter = useMemo( + () => + new DeterministicInferenceAdapter({ + defaultChunkDelayMs: config.delayMs, + defaultChunkSize: 6, + }), + [config.delayMs], + ); + const broker = useMemo( + () => + createBrowserBroker< + DeterministicRequest, + DeterministicChunk, + DeterministicResult + >({ + adapter, + config: { + heartbeatIntervalMs: 150, + leaderTimeoutMs: 600, + namespace: config.namespace, + queueCapacity: config.capacity, + requestTimeoutMs: 12_000, + }, + telemetry, + }), + [adapter, config.capacity, config.namespace, telemetry], + ); + const [snapshot, setSnapshot] = useState(broker.snapshot); + const snapshotRef = useRef(snapshot); + const [events, setEvents] = useState([]); + const [prompt, setPrompt] = useState( + 'Coordinate one local model runtime across these browser tabs.', + ); + const [output, setOutput] = useState(''); + const [error, setError] = useState(); + const [requestStatus, setRequestStatus] = useState('idle'); + const [isActive, setIsActive] = useState(false); + const [chunkCount, setChunkCount] = useState(0); + const [terminalCount, setTerminalCount] = useState(0); + const [capacityDraft, setCapacityDraft] = useState(config.capacity); + const activeSession = useRef(undefined); + + useEffect(() => { + snapshotRef.current = snapshot; + }, [snapshot]); + + useEffect(() => { + const unsubscribe = broker.subscribe((nextSnapshot, event) => { + snapshotRef.current = nextSnapshot; + setSnapshot(nextSnapshot); + if (event !== undefined) { + setEvents((current) => [event, ...current].slice(0, 80)); + if ( + event.type === 'retry' && + event.requestId === activeSession.current?.id + ) { + setOutput(''); + setChunkCount(0); + setRequestStatus('retrying on new owner'); + } + } + }); + void broker.start().catch((cause: unknown) => { + setError(safeMessage(cause)); + setRequestStatus('capability error'); + }); + return () => { + unsubscribe(); + void broker.stop(); + }; + }, [broker]); + + const send = useCallback(() => { + if (activeSession.current !== undefined || prompt.trim().length === 0) { + return; + } + setOutput(''); + setError(undefined); + setChunkCount(0); + setRequestStatus('waiting for owner'); + const session = broker.request({ + chunkDelayMs: config.delayMs, + chunkSize: 6, + text: prompt.trim(), + }); + activeSession.current = session; + setIsActive(true); + const resultPromise = session.result; + void resultPromise.catch(() => undefined); + void (async () => { + try { + setRequestStatus('streaming'); + for await (const chunk of session) { + setOutput((current) => current + chunk.text); + setChunkCount((current) => current + 1); + } + await resultPromise; + setRequestStatus('completed'); + } catch (cause) { + const code = + cause instanceof TabLoomError ? cause.code : 'ADAPTER_FAILED'; + setRequestStatus(statusForError(code)); + setError(safeMessage(cause)); + } finally { + activeSession.current = undefined; + setIsActive(false); + setTerminalCount((current) => current + 1); + } + })(); + }, [broker, config.delayMs, prompt]); + + const cancel = useCallback(() => { + activeSession.current?.cancel(); + }, []); + + const simulateCrash = useCallback(() => { + if (snapshotRef.current.role === 'leader') { + void broker.stop(); + setRequestStatus('owner stopped'); + } + }, [broker]); + + const openPeer = useCallback(() => { + const url = new URL(window.location.href); + url.searchParams.set('namespace', config.namespace); + url.searchParams.set('capacity', String(capacityDraft)); + window.open(url, '_blank', 'noopener'); + }, [capacityDraft, config.namespace]); + + return ( +
+
+
+ + TabLoom +
+
+ + Protocol v + {snapshot.config.protocolVersion} + +
+ Epoch {snapshot.epoch} +
+ + Fencing epoch: {snapshot.epoch} + + + Broker: {snapshot.readiness} + +
+ +
+ + +
+ + setEvents([])} /> + + + {chunkCount} + {terminalCount} + {snapshot.knownPeers.length} + + {snapshot.role === 'leader' + ? snapshot.tabId + : (snapshot.leaderId ?? '')} + + +
+ ); +} + +function readDemoConfig(): DemoConfig { + const search = new URLSearchParams(window.location.search); + return { + capacity: boundedInteger(search.get('capacity'), 1, 16, 8), + delayMs: boundedInteger(search.get('delay'), 0, 2_000, 45), + namespace: sanitizeNamespace(search.get('namespace') ?? 'tabloom-demo'), + }; +} + +function boundedInteger( + value: string | null, + minimum: number, + maximum: number, + fallback: number, +): number { + if (value === null) { + return fallback; + } + const parsed = Number.parseInt(value, 10); + return Number.isInteger(parsed) && parsed >= minimum && parsed <= maximum + ? parsed + : fallback; +} + +function sanitizeNamespace(value: string): string { + const safe = value.replace(/[^a-zA-Z0-9._-]/gu, '').slice(0, 80); + return safe.length === 0 ? 'tabloom-demo' : safe; +} + +function safeMessage(cause: unknown): string { + return cause instanceof TabLoomError + ? cause.message + : 'The broker operation failed.'; +} + +function statusForError(code: TabLoomError['code']): string { + switch (code) { + case 'BACKPRESSURE': + return 'backpressure'; + case 'CANCELLED': + return 'cancelled'; + case 'TIMEOUT': + return 'timed out'; + case 'PROTOCOL_MISMATCH': + return 'protocol mismatch'; + case 'ADAPTER_FAILED': + return 'adapter failed'; + case 'BROKER_STOPPED': + case 'CAPABILITY_UNAVAILABLE': + case 'INVALID_CONFIG': + case 'NO_LEADER': + return 'failed'; + } +} diff --git a/demo/components/Controls.tsx b/demo/components/Controls.tsx new file mode 100644 index 0000000..6c1c676 --- /dev/null +++ b/demo/components/Controls.tsx @@ -0,0 +1,158 @@ +import type { BrokerSnapshot } from '@tabloom'; +import { AlertIcon, SendIcon, ShieldIcon, SlidersIcon } from '../icons.js'; + +interface ControlsProps { + readonly active: boolean; + readonly capacityDraft: number; + readonly error: string | undefined; + readonly output: string; + readonly prompt: string; + readonly requestStatus: string; + readonly snapshot: BrokerSnapshot; + readonly onCancel: () => void; + readonly onCapacityChange: (value: number) => void; + readonly onOpenPeer: () => void; + readonly onPromptChange: (value: string) => void; + readonly onSend: () => void; + readonly onSimulateCrash: () => void; +} + +export function Controls({ + active, + capacityDraft, + error, + output, + prompt, + requestStatus, + snapshot, + onCancel, + onCapacityChange, + onOpenPeer, + onPromptChange, + onSend, + onSimulateCrash, +}: ControlsProps) { + return ( +