Targ Apps Docs
Chroma-t2t

Chroma-t2t

Test-to-test helpers for Chroma apps — snapshot smoke checks, persist round-trips, and a Node test bridge for apps that use Chroma-Fs.

Chroma-t2t (@chroma/t2t, plugin name chroma-t2t) is an optional plugin for development and smoke testing. The name means test-to-test: the same persistence and export/import logic you already unit-test in Node can be exercised again from a running app in the browser or in Chroma Desktop, without duplicating business rules inside the plugin.

In plain words: you keep one set of pure functions for save, load, export, and import. Chroma-t2t wires those functions into quick checks you can run from DevTools (runAll()) or from CI (npm test), so a green Node suite and a green in-app smoke test mean the same thing.

Plugin namechroma-t2t
Package@chroma/t2t
loadPlugins() keyplugins.t2t (loadAs: "t2t")
LicenseGPL-3.0-or-later — © Targ Apps

Chroma-t2t does not replace a full test framework. It complements node --test (or similar) with:

  • Snapshot smoke — confirms named collections in your in-memory snapshot are arrays (shape guard).
  • Persist round-trip — seeds data, exports, resets, re-imports through your adapters, and fails on mismatch.
  • Node bridge — run-tests.mjs and runNodeTests() delegate to the host project's npm test when Node is available.

The plugin never imports your app by itself. You pass an adapter object that delegates to modules such as persist.chr, export.chr, and import.chr.

When to use it

Use Chroma-t2t when your app:

  • Persists structured state (often via Chroma-Fs and a JSON snapshot).
  • Already has or wants pure export/import functions testable without the DOM.
  • Needs a fast sanity check after UI work in chroma dev or Desktop develop mode.

Skip it for apps with no persistence, or when npm test alone is enough and you never smoke-test in the host.

Install the plugin

  1. Add the plugin name to chroma.json:

    {
      "name": "my-app",
      "mode": "dynamic",
      "plugins": ["chroma-fs", "chroma-t2t"]
    }
  2. Vendor the plugin into your project:

    chroma install          # copies first-party plugins to ~/.chroma/plugins/
    chroma new my-app       # or copy plugins/chroma-t2t/ from a template
  3. Confirm plugins/chroma-t2t/chroma.plugin.json exists and lists bootstrap: "bootstrapT2t".

chroma build copies plugins/ into dist/. For production zips you may remove chroma-t2t from plugins if you do not want test hooks in shipped builds.

Step-by-step: wire t2t in your app

1. Keep persistence logic pure

Split DOM-free modules that Node tests can import:

ResponsibilityTypical module
In-memory cache, hydrate, flushsrc/lib/persist.chr
Build backup JSONsrc/lib/export.chr
Parse, validate, apply importsrc/lib/import.chr

Keeping these modules free of DOM code lets the same export/import logic run under Node tests and in the in-app smoke checks.

2. Implement PersistAdapters

Chroma-t2t expects one object with the functions below. Names must match; behavior is yours.

AdapterRole
resetClear in-memory persist state (tests only).
createMemoryStorageIn-memory Chroma-Fs–shaped storage for isolated round-trips.
hydrateasync ({ storage }) => … — attach storage to persist layer.
setPersistedWrite a collection key in the sync cache.
flushasync () => … — persist pending writes.
getSnapshotReturn the full snapshot object.
buildExportPayloadObject to serialize for backup.
serializeExport(payload) => string
parseImport(text) => { ok, data?, error? }
validateImport(data) => { valid, error? }
applyImport(data) => void

Collect them in one module, for example plugins/chroma-t2t/adapters.chr, that imports from src/lib/persist.chr, export.chr, and import.chr.

// plugins/chroma-t2t/adapters.chr
import {
  createMemoryStorage,
  flushPersist,
  getSnapshot,
  hydratePersist,
  resetPersistForTests,
  setPersisted,
} from "../../src/lib/persist.chr";
import { buildExportPayload, serializeExportPayload } from "../../src/lib/export.chr";
import {
  applyImportPayload,
  parseImportText,
  validateImportPayload,
} from "../../src/lib/import.chr";

export const persistAdapters = {
  reset: resetPersistForTests,
  createMemoryStorage,
  hydrate: hydratePersist,
  setPersisted,
  flush: flushPersist,
  getSnapshot,
  buildExportPayload,
  serializeExport: serializeExportPayload,
  parseImport: parseImportText,
  validateImport: validateImportPayload,
  applyImport: applyImportPayload,
};

export const COLLECTION_KEYS = ["items", "tags"];

export const defaultSeed = {
  items: [{ id: "1", title: "Smoke test" }],
};

export function verifyRoundTrip(snapshot) {
  if (!snapshot.items?.length) throw new Error("items missing after round-trip");
}

3. Bootstrap from the plugin entry

The generic loader calls bootstrapT2t from plugins/chroma-t2t/index.js when the plugin is listed. Pass your adapters inside that file (you override the stock index.js), or call bootstrapT2t with options from a thin wrapper you own.

Option A — override the plugin entry (recommended for real apps):

// plugins/chroma-t2t/index.js
import { createPersistRoundTrip, createSnapshotSmoke } from "./helpers.js";
import {
  COLLECTION_KEYS,
  defaultSeed,
  persistAdapters,
  verifyRoundTrip,
} from "./adapters.chr";

export async function bootstrapT2t(options = {}) {
  const assertPersistRoundTrip = createPersistRoundTrip(persistAdapters, {
    seed: defaultSeed,
    verify: verifyRoundTrip,
  });
  const smoke = createSnapshotSmoke(persistAdapters.getSnapshot, COLLECTION_KEYS);

  const api = {
    assertPersistRoundTrip,
    smokeSnapshot: smoke,
    runAll: async () => {
      smoke();
      await assertPersistRoundTrip();
      return { ok: true };
    },
  };

  if (options.exposeGlobal !== false && typeof globalThis !== "undefined") {
    globalThis.__chromaT2t = api;
  }

  return api;
}

export const plugin = {
  name: "chroma-t2t",
  hooks: { bootstrap: bootstrapT2t },
};
export default plugin;

Option B — stock @chroma/t2t API (pass options into bootstrapT2t):

import { bootstrapT2t } from "../plugins/chroma-t2t/index.js";
import { persistAdapters, COLLECTION_KEYS, defaultSeed, verifyRoundTrip } from "./t2t-wire.chr";

await bootstrapT2t({
  persist: {
    adapters: persistAdapters,
    seed: defaultSeed,
    verify: verifyRoundTrip,
  },
  snapshot: {
    getSnapshot: persistAdapters.getSnapshot,
    collectionKeys: COLLECTION_KEYS,
  },
});

If you use Option B and list chroma-t2t in chroma.json, avoid double bootstrap: either patch index.js once or import helpers only and omit the plugin from plugins (not typical).

4. Load plugins from main.chr

// src/main.chr
import { loadPlugins } from "../plugins/loader.js";
import { render } from "../pkg/chroma.js";
import { App } from "./App.chr";

await hydrateYourPersistLayer(); // your app — before render
const plugins = await loadPlugins();
// plugins.t2t is set when bootstrap completed

render(App, document.getElementById("app"));

5. Run smoke checks in the host

Start the app:

chroma dev
# or chroma dev --no-desktop for a browser tab

Open DevTools on the app frame and run:

await globalThis.__chromaT2t.runAll();

On success you get { ok: true, results: { smoke, persist, node? } } from the stock API, or { ok: true } from a minimal custom runAll.

Run individual checks:

globalThis.__chromaT2t.smokeSnapshot();
await globalThis.__chromaT2t.assertPersistRoundTrip();

6. Run the Node suite in CI

From the project root:

npm test
# or explicitly via the plugin bridge:
node plugins/chroma-t2t/node/run-tests.mjs

Set CHROMA_T2T_PROJECT_ROOT or CHROMA_T2T_TEST_COMMAND if the runner should target a non-default root or command.

If your tests import .chr modules, run the bridge with a Node loader that understands the .chr extension so those files load under node --test.

What the round-trip does

assertPersistRoundTrip (in helpers.js) runs this sequence against your adapters:

  1. reset() → createMemoryStorage() → hydrate({ storage })
  2. Apply seed via setPersisted for each key → flush()
  3. serializeExport(buildExportPayload()) → export string
  4. reset() → hydrate with the same in-memory storage
  5. parseImport → validateImport → applyImport → flush()
  6. Optional verify(getSnapshot()) — throw to fail

The round-trip uses createMemoryStorage(), not your live IndexedDB or Desktop filesystem. It proves export/import and persist logic stay consistent; it does not by itself prove that data survives an app restart on disk. See Portable vs Executable below.

API reference

ExportPurpose
bootstrapT2t(options)Builds the API; by default sets globalThis.__chromaT2t
createTestApi(options)Same as bootstrap without attaching global
assertPersistRoundTrip(adapters, options)One-shot round-trip
createPersistRoundTrip(adapters, defaults)Returns a reusable assertPersistRoundTrip closure
smokeSnapshot(snapshot, collectionKeys)Asserts each key is an array
createSnapshotSmoke(getSnapshot, keys)Binds getter + keys
runNodeTests(options)Spawns npm test in Node; skipped in the browser
runAll(runOptions?)Runs smoke + persist; optional includeNodeTests: true

bootstrapT2t options

FieldMeaning
exposeGlobalDefault true — attach API to globalThis
globalKeyDefault "__chromaT2t"
persist.adaptersPersistAdapters object (required for round-trip)
persist.seedKey/value pairs written before export
persist.verify(snapshot) => void — throw on failure
snapshot.getSnapshotGetter for smoke test
snapshot.collectionKeysArray field names that must be arrays
node.projectRootCwd for runNodeTests
node.commandDefault "npm test"
node.scriptDocumented path to run-tests.mjs

Stock runAll() throws if both smoke and persist are unconfigured.

Worked example: Node test without the plugin

You can import helpers directly in node --test (same logic as DevTools):

// test/lib/roundtrip.test.js
import { describe, it, beforeEach } from "node:test";
import assert from "node:assert/strict";
import { assertPersistRoundTrip } from "../../plugins/chroma-t2t/helpers.js";
import { persistAdapters, defaultSeed, verifyRoundTrip } from "../../plugins/chroma-t2t/adapters.chr";

describe("persist round-trip", () => {
  beforeEach(() => persistAdapters.reset());

  it("export/import matches seed", async () => {
    const result = await assertPersistRoundTrip(persistAdapters, {
      seed: defaultSeed,
      verify: verifyRoundTrip,
    });
    assert.equal(result.ok, true);
  });
});

Portable (Web) vs Executable (Chroma Desktop)

Chroma-t2t loads in both runtime modes. The plugin is browser ESM; DevTools access works in a normal tab and inside the Desktop iframe.

TopicPortable (Web)Executable (Chroma Desktop)
Plugin loadloadPlugins() in the pageSame in the iframe (127.0.0.1 origin)
__chromaT2t.runAll()DevTools on the tabDevTools on the iframe (inspect the app frame)
Smoke + in-memory round-tripSame behaviorSame behavior — does not touch real disk
Live Chroma-Fs backendUsually IndexedDBOften filesystem bridge when backend: "filesystem"
runNodeTests() / runAll({ includeNodeTests: true })Skipped in browser (skipped: true)Skipped in iframe — run npm test on the host machine
Restart persistenceVerify manually in the browser profileVerify manually after closing Desktop (see below)

Design for both modes: runtime code may call resolveOpenStorageConfig() (or similar) so Chroma-Fs picks IndexedDB in a tab and the filesystem bridge in Desktop. Chroma-t2t intentionally uses in-memory storage for automated round-trips so results do not depend on which backend is active in DevTools.

Manual checks Desktop (and web) still need

Automated t2t checks do not replace:

  • Confirming getPersistBackend() (or your equivalent) reports the expected backend after real usage.
  • Creating data, restarting the host, and confirming the UI still shows it.

After real data is created in Desktop develop mode:

getPersistBackend(); // expect chroma-fs / filesystem when configured
await __chromaT2t.runAll(); // in-memory export/import still passes

IndexedDB in a browser dev tab and IndexedDB (or filesystem data) in Desktop develop mode use different origins — do not expect shared data when switching hosts (Runtime modes).

Development workflow tip

For the fastest UI reload loop, use chroma dev --no-desktop even if you ship Desktop. Run __chromaT2t.runAll() in whichever host you are debugging; run npm test in CI regardless of mode.

runNodeTests behavior

In Node, runNodeTests spawns npm test (or options.command) with inherited stdio. In the browser or Desktop iframe:

const result = await globalThis.__chromaT2t.runNodeTests();
// { ok: false, skipped: true, reason: "runNodeTests requires Node.js — ..." }

Use node plugins/chroma-t2t/node/run-tests.mjs from the project root when you want the bridge script without opening the app.

Manifest

{
  "name": "chroma-t2t",
  "package": "@chroma/t2t",
  "entry": "index.js",
  "loadAs": "t2t",
  "capabilities": ["testing", "dev-tools"],
  "hooks": {
    "bootstrap": "bootstrapT2t"
  }
}

Validate with the shared plugin schema.

Next

  • Plugins — loader, hooks, vendoring
  • Runtime modes — Portable vs Executable terminology
  • chroma-t2t by mode — quick Portable vs Executable matrix row
  • Chroma-Fs — storage backends round-trips usually mirror
  • CLI — chroma install, chroma new, chroma build

On this page