Interactive Edge & Web Platform Lab

Reactive Prompt Cells

A spreadsheet-inspired declarative <ai-prompt> Custom Element workbench that replaces opaque imperative effect() closures with inspectable DOM dependency attributes, explicit cost and recalculation policies, content-addressed prompt caching, human edit pinning with conflict isolation, and keyed Collection IVM.

Problem & Hypothesis

Imperative effect() wiring hides dependency graphs inside closures, leaks listeners across mount/unmount cycles, triggers unbounded model calls on every keystroke, and overwrites manual edits. Encoding prompt dependencies and gates (auto, debounce, manual, frozen, switch/exhaust) as <ai-prompt> Custom Elements exposes topology in DevTools, gates token spend, and isolates edits in a conflict state.

Confirm / Falsify Signals

Confirm: Detaching an <ai-prompt> aborts active fetches via disconnectedCallback() with 0 listener leaks, identical hashes hit cache, and upstream changes preserve pinned edits. Falsify: HTML attributes become unwieldy for nested schemas or deeply branching array rows compared to keyed JS IVM collections.

What To Try First

Click Run Cache Hit Sequence or Run Pin & Conflict Demo below, or switch to Tab 2 and edit one row in the Feature Matrix to compare keyed IVM against full-table recomputes.

3 Things To Try

Direct actions that execute against the live reactive graph and log every wire frame below.

1. Verify Cache Hit Skips Runner

Mutates #topic to a new string, waits for completion, then reverts to the prior topic to verify data-cache="hit" with 0 network calls.

2. Pin Edit & Trigger Conflict

Pins a human override on #cell-outline, changes upstream #topic, and opens the conflict banner preserving both values.

3. Isolate 1-Row IVM Update

Switches to the Launch Studio and updates Row 2 only, highlighting recomputed on Row 2 + Rollup while sibling rows stay cached.

Detecting LanguageModel...
Runner Calls: 0 Cache Hits: 0 Aborts: 0 Frozen Blocks: 0 Listeners: 0 Est. Tokens: 0

Upstream Inputs

Values read directly from DOM inputs declared in watch="#topic, #tone".

1-Click Verification Scenarios

Each test exercises the real <ai-prompt> elements below and records the observed state transitions.

    Cell 1: #cell-outline

    watch: #topic, #tone idle cache: none 0 tok

    Cell 2: #cell-draft

    watch: #cell-outline, #tone idle cache: none 0 tok

    Live DOM Attribute Inspector

    Reads real DOM attributes directly off the mounted <ai-prompt> elements.
    Element ID data-state aria-busy mode policy watch data-hash data-cache data-listeners
    HTTP Wire & Execution Stream Inspector 0 wire frames
    Initializing reactive graph...
    Content-Addressed Cache Entries (PromptCache) 0 entries
    Cache is empty.
    Live Declarative <ai-prompt> DOM Snapshot Live Attributes
    Loading DOM snapshot...
    Reactive Prompt Cell Architecture Flow Flow from DOM attributes (watch, mode, policy) to content-addressed cache lookup, execution gate, human pin and conflict resolution, and keyed Collection IVM row propagation. 1. DOM Attributes watch="#topic, #tone" mode="auto|debounce|manual" policy="switch|exhaust|concat" 2. Content Cache fnv64(resolvedPrompt, config) HIT -> ready (0 network) MISS -> check mode gate 3. Gate & Runner manual -> stale | frozen -> block LanguageModel OR /api/cell-run AbortSignal + NDJSON stream 4. Pin & Conflict pinnedValue + candidateValue keepPinned | acceptCandidate mergeCandidate -> downstream 5. Keyed Collection IVM (Feature Matrix Table) Row 1 [hash unchanged: cached] | Row 2 [edited: recomputed] | Row 3 [hash unchanged: cached] -> Incremental Rollup disconnectedCallback(): AbortController.abort() cancels in-flight fetch/session and detaches all DOM listeners (0 leaks)
    Figure 1. Declarative DOM attributes bind directly to CellGraphEngine, content-addressed cache lookups, human-pin conflict gates, and keyed row IVM.
    How This Is Set Up

    Implementation & Custom Element Contract

    Imperative computed() and effect() closures hide prompt dependency edges inside JavaScript memory, leak event listeners across mount/unmount cycles, and re-run unbounded inference calls on every keystroke. Declarative <ai-prompt> attributes expose the DAG in DOM markup while content-addressed caching and explicit conflict states gate token spend.

    Imperative effect() closures (baseline)
    // Imperative nested computed() + manual effect cleanup
    const outlinePrompt = computed(() => `Outline ${topic.value} (${tone.value})`);
    
    const stopOutline = effect(() => {
      const controller = new AbortController();
      // Unbounded token re-runs on every input; no hash cache
      runPrompt(outlinePrompt.value, { signal: controller.signal })
        .then((res) => {
          // Silently overwrites manual user edits in DOM output
          draftOutput.textContent = res.text;
        });
      return () => controller.abort();
    });
    // Must invoke stopOutline() manually on unmount to avoid leaked listeners
    Declarative <ai-prompt> cells (this lab)
    <!-- Declarative <ai-prompt> cell with explicit gate & policy -->
    <ai-prompt
      id="cell-draft"
      watch="#cell-outline, #tone"
      policy="switch"
      mode="manual"
      prompt="Expand outline: {{cell-outline}} ({{tone}})"
    ></ai-prompt>
    
    // Content-addressed cache + human edit pinning via element API
    await draftCell.pin("Human-verified introduction paragraph.");
    // Upstream change moves state to "conflict" instead of clobbering
    await draftCell.resolveConflict("mergeCandidate", mergedText);
    // Or keepPinned / acceptCandidate with zero silent overwrites
    Complete Page Setup: HTML Markup, Cell Registry & Edge Stream Wiring

    Live <ai-prompt> tags in public/index.html, cell/pin/IVM configuration from public/lib/cell-engine.js and public/lib/ai-prompt-element.js, and POST /api/cell-run streaming in public/app.js and src/worker.ts.

    <!-- 1. Page HTML Setup (public/index.html) -->
    <input id="studio-product" value="EdgeCell Studio v2" />
    <input id="studio-audience" value="Platform & AI systems engineers" />
    <select id="studio-tone"><option value="direct architectural">direct architectural</option></select>
    <output id="matrix"></output>
    <ai-prompt
      id="cell-brief"
      label="Executive Brief"
      watch="#studio-product, #studio-audience, #studio-budget, #studio-tone, #matrix"
      mode="auto"
      policy="switch"
      prompt="Write an Executive Launch Brief.
    Product: {{studio-product}}
    Audience: {{studio-audience}}
    Budget: {{studio-budget}}
    Tone: {{studio-tone}}
    Feature Matrix: {{matrix}}"
    ></ai-prompt>
    <script type="module" src="/app.js"></script>
    
    // 2. Cell, Pinning & IVM Schema Config (public/lib/ai-prompt-element.js + public/lib/cell-engine.js)
    static observedAttributes = ['watch', 'policy', 'mode', 'debounce', 'prompt', 'model', 'system', 'frozen'];
    engine.registerCell({
      id: 'cell-brief',
      label: 'Executive Brief',
      template: this.#resolvePromptTemplate(),
      deps: ['studio-product', 'studio-audience', 'studio-budget', 'studio-tone', 'matrix'],
      mode: 'auto',       // 'auto' | 'debounce' | 'manual' | 'frozen'
      policy: 'switch',   // 'switch' | 'exhaust' | 'concat'
      debounceMs: 350,
      model: 'worker-edge',
      pinned: false, pinnedValue: '', baseHash: '', candidateValue: '', candidateHash: '',
    });
    // Content-addressed cache key + KeyedCollectionIVM row signature:
    const hash = hashPromptConfig(resolvedPrompt, { mode: cell.mode, policy: cell.policy, model: cell.model });
    const rowHash = hashPromptConfig(`row(${orderedFields}) ctx(${orderedContext})`, { kind: 'ivm-row', collectionId: 'matrix' });
    
    // 3. Page Bootstrap & /api/cell-run Edge Wiring (public/app.js + src/worker.ts)
    const cache = new PromptCache();
    const engine = new CellGraphEngine({ runner: unifiedRunner, cache });
    const collection = new KeyedCollectionIVM({ id: 'matrix', cache, rowRunner });
    engine.attachCollection(collection);
    AiPromptElement.setDefaultEngine(engine);
    for (const el of document.querySelectorAll('ai-prompt')) el.connectEngine(engine, document);
    await engine.evaluateAll();
    // unifiedRunner falls back from LanguageModel to POST /api/cell-run NDJSON with AbortSignal:
    const response = await fetch('/api/cell-run', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cellId: ctx.cellId, resolvedPrompt: ctx.prompt, hash: ctx.hash, mode, policy }),
      signal: ctx.signal,
    });
    // src/worker.ts: if (url.pathname === '/api/cell-run') return await handleCellRun(request);
    Core Plumbing Required Today (Browser + Edge / Protocol Contract)
    // public/lib/ai-prompt-element.js — Lifecycle teardown aborts active runs & listeners
    connectedCallback() {
      this.#connected = true;
      activeElements.add(this);
      this.#setupBindings(); // Registers target.addEventListener(..., { signal })
    }
    disconnectedCallback() {
      this.#connected = false;
      activeElements.delete(this);
      this.#teardownBindings(true);
    }
    #teardownBindings(abortActiveRun) {
      if (abortActiveRun && this.#engine) this.#engine.abortCell(this.cellId, 'disconnected');
      if (this.#listenerAbortController) this.#listenerAbortController.abort('disconnected');
      if (this.#unsubscribeEngine) this.#unsubscribeEngine();
    }
    
    // public/lib/cell-engine.js — Gate frozen/pinned/manual states & PromptCache lookup
    if (cell.frozen || cell.mode === 'frozen') { cell.state = 'frozen'; return; }
    if (cell.pinned && resolved.hash !== cell.baseHash) { cell.state = 'conflict'; /* keep output */ }
    if (cell.mode === 'manual') { cell.state = 'stale'; return; }
    const cached = this.cache.get(resolved.hash);
    if (cached) return this.#applyCacheHit(cell, resolved, cached, false, skipPropagate);
    What disappears

    Hidden JavaScript closure graphs, manual removeEventListener teardown tracking, duplicate inference calls on undo or revert, and silent overwrites of pinned human edits.

    What becomes explicit

    Inspectable watch selector edges, recalculation gates (auto, debounce, manual, frozen), concurrency policies (switch, exhaust, concat), fnv1a64 cache hits, and keepPinned/acceptCandidate/mergeCandidate conflict resolution.

    Platform gaps remaining

    HTML has no native <ai-prompt> element or declarative dependency scheduler; Custom Elements must implement AbortController listener lifecycles, PromptCache memoization, and Worker NDJSON adapters in userland JavaScript.