@tjakoen/grain 0.1.24 → 0.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -150,3 +150,59 @@ test("direct verb (control click, no message) → executed without consulting th
150
150
  expect(called).toBe(false); // the human already decided — no model turn
151
151
  expect(archived).toEqual(["ITM-1"]);
152
152
  });
153
+
154
+
155
+ test("unsupported registered actions reject instead of reporting success", async () => {
156
+ const field = { id: "name", kind: "field" as const, accepts: ["field.set" as const] };
157
+ const r = makeModelReasoner({ model: model(""), manifest: () => buildManifest("loop", [field], { surfaces: ["name"], readable: [] }) });
158
+ const { tools, ops } = recordingTools();
159
+ const d = await r.decide(intent({ action: "field.set", surface: "name", payload: { value: "Ada" } }), tools);
160
+ expect(d.ok).toBe(false);
161
+ expect(ops).toEqual([]);
162
+ });
163
+
164
+ test("cancellation while the model completes prevents the structural mutation", async () => {
165
+ let cancelled = false;
166
+ const r = makeModelReasoner({ model: { complete: async () => { cancelled = true; return '{"action":"item.archive","target":"item:ITM-1"}'; } }, manifest });
167
+ const { tools, archived } = recordingTools();
168
+ tools.cancelled = () => cancelled;
169
+ const d = await r.decide(intent({ payload: { text: "archive it" } }), tools);
170
+ expect(d.ok).toBe(false);
171
+ expect(archived).toEqual([]);
172
+ });
173
+
174
+ test("an already cancelled direct intent emits nothing and makes no mutation", async () => {
175
+ const r = makeModelReasoner({ model: model(""), manifest });
176
+ const { tools, ops, archived } = recordingTools();
177
+ tools.cancelled = () => true;
178
+ expect((await r.decide(intent({ action: "item.archive", surface: "item:ITM-1" }), tools)).ok).toBe(false);
179
+ expect(ops).toEqual([]);
180
+ expect(archived).toEqual([]);
181
+ });
182
+
183
+
184
+ test("cancellation during reply delay prevents later tokens and navigation", async () => {
185
+ const nav = { id: "screen", kind: "screen", accepts: ["navigate" as const] };
186
+ const r = makeModelReasoner({ model: model('{"action":"navigate","target":"screen","payload":{"href":"/notes"},"reply":"Going"}'),
187
+ thinkMs: 1, manifest: () => buildManifest("loop", [nav], { surfaces: ["screen"], readable: [] }) });
188
+ let cancelled = false;
189
+ const { tools, ops } = recordingTools();
190
+ tools.cancelled = () => cancelled;
191
+ tools.delay = async () => { cancelled = true; };
192
+ expect((await r.decide(intent({ payload: { text: "go" } }), tools)).ok).toBe(false);
193
+ expect(ops.some(op => op.op === "navigate" || (op.op === "type" && op.commit === "pending") )).toBe(false);
194
+ });
195
+
196
+
197
+ test("the generic prompt omits unsupported handlers and rejects a proposed unsupported move visibly", async () => {
198
+ const field = { id: "name", kind: "field", accepts: ["field.set" as const] };
199
+ let prompt = "";
200
+ const r = makeModelReasoner({ model: { complete: async text => { prompt = text; return '{"action":"field.set","target":"name","payload":{"value":"Ada"}}'; } },
201
+ manifest: () => buildManifest("loop", [...targets, field], { surfaces: ["name"], readable: [] }) });
202
+ const { tools } = recordingTools();
203
+ const result = await r.decide(intent({ payload: { text: "fill my name" } }), tools);
204
+ expect(prompt).not.toContain("field.set");
205
+ expect(result.ok).toBe(false);
206
+ expect(result.ops).toHaveLength(1);
207
+ expect(result.ops[0]).toMatchObject({ op: "replace" });
208
+ });
@@ -52,6 +52,7 @@ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
52
52
  for (const ch of text) {
53
53
  if (tools.cancelled()) break;
54
54
  if (thinkMs > 0) await tools.delay(TYPE_MS);
55
+ if (tools.cancelled()) break;
55
56
  tools.emit(typeToken(surface, ch));
56
57
  }
57
58
  tools.emit(settleOp(surface));
@@ -61,6 +62,11 @@ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
61
62
  * human-facing reply into `replyTarget` (a chat bubble body, or the reflection line). `navigate` is
62
63
  * emitted LAST — it's terminal for the page, so the reply is seen first. */
63
64
  async function execute(move: ValidatedMove, tools: ReasonTools, replyTarget: string | null): Promise<Decision> {
65
+ if (tools.cancelled()) return { ok: false, reason: "cancelled", ops: [] };
66
+ const unsupported = (): Decision => ({ ok: false,
67
+ reason: `unsupported action ${move.action} in the generic model reasoner`,
68
+ ops: replyTarget ? [replaceBodyOp(replyTarget, "I cannot perform that action here.", "committed")] : [],
69
+ });
64
70
  const structural: RenderOp[] = [];
65
71
  let terminal: RenderOp | null = null;
66
72
 
@@ -75,14 +81,20 @@ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
75
81
  break;
76
82
  }
77
83
  // action null (reply-only) or a reply-shaped verb: the effect IS the reply, streamed below.
78
- default: break;
84
+ case null: break;
85
+ case "demo.run": case "say.stream": case "say.set":
86
+ if (replyTarget && move.reply) break;
87
+ return unsupported();
88
+ default: return unsupported();
79
89
  }
80
90
 
91
+ if (tools.cancelled()) return { ok: false, reason: "cancelled", ops: [] };
81
92
  for (const op of structural) tools.emit(op);
82
93
  if (replyTarget) {
83
94
  if (move.reply) await stream(replyTarget, move.reply, tools);
84
95
  else tools.emit(settleOp(replyTarget)); // never leave an opened bubble blank
85
96
  }
97
+ if (tools.cancelled()) return { ok: false, reason: "cancelled", ops: [] };
86
98
  if (terminal) tools.emit(terminal);
87
99
 
88
100
  return { ok: true, ops: [], reply: move.reply }; // ops all emitted inline (streaming pattern)
@@ -90,7 +102,10 @@ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
90
102
 
91
103
  /** The agentic entry: a human message → the model picks + we execute one move. */
92
104
  async function decideFromMessage(intent: Intent, tools: ReasonTools, message: string): Promise<Decision> {
93
- const m = manifest();
105
+ const live = manifest();
106
+ const supported = new Set(["note.append", "note.replace", "navigate", "item.archive", "say.set", "say.stream", "demo.run"]);
107
+ const m = { ...live, actions: live.actions.filter(action => supported.has(action.name)),
108
+ targets: live.targets.map(target => ({ id: target.id, kind: target.kind, accepts: target.accepts.filter(action => supported.has(action)) })) };
94
109
 
95
110
  // chat.send shows the human's message, then opens an AI bubble to stream the reply into. say.set
96
111
  // writes straight back into the reflection surface it targeted (no chat bubble).
@@ -117,6 +132,7 @@ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
117
132
  try { raw = await model.complete(buildReasonerPrompt(manifestToText(m), message)); }
118
133
  catch (e) { return fail("The model didn't respond — try again.", `model.complete threw: ${String(e)}`); }
119
134
 
135
+ if (tools.cancelled()) return { ok: false, reason: "cancelled", ops: [] };
120
136
  const parsed = parseModelMove(raw);
121
137
  if (!parsed.ok) return fail("I couldn't read that decision.", parsed.reason);
122
138
  const valid = validateMove(parsed.move, m);
@@ -127,6 +143,7 @@ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
127
143
 
128
144
  return {
129
145
  async decide(intent: Intent, tools: ReasonTools): Promise<Decision> {
146
+ if (tools.cancelled()) return { ok: false, reason: "cancelled", ops: [] };
130
147
  const message = String(intent.payload?.text ?? "").trim();
131
148
 
132
149
  if ((intent.action === "chat.send" || intent.action === "say.set") && message)
package/ai/model.test.ts CHANGED
@@ -146,3 +146,11 @@ test("pipeline: fake model → parse → validate yields a safe move", async ()
146
146
  const valid = validateMove(parsed.move, manifest);
147
147
  expect(valid).toEqual({ ok: true, move: { action: "note.append", target: "notepad", payload: { text: "remember the milk" }, reply: undefined } });
148
148
  });
149
+
150
+
151
+ test("malformed model property types are rejected before validation executes them", () => {
152
+ for (const value of [{ reply: 42 }, { action: [] }, { target: false }, { payload: [] }, { payload: "bad" }]) {
153
+ expect(parseModelMove(JSON.stringify(value)).ok).toBe(false);
154
+ expect(validateMove(value as never, manifest).ok).toBe(false);
155
+ }
156
+ });
package/ai/model.ts CHANGED
@@ -99,6 +99,8 @@ export function parseModelMove(raw: string): { ok: true; move: ModelMove } | { o
99
99
  catch { return { ok: false, reason: "model returned malformed JSON" }; }
100
100
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
101
101
  return { ok: false, reason: "model output is not a JSON object" };
102
+ const shape = modelMoveShape(parsed);
103
+ if (shape) return { ok: false, reason: shape };
102
104
  return { ok: true, move: parsed as ModelMove };
103
105
  }
104
106
 
@@ -124,6 +126,18 @@ function extractJsonObject(raw: string): string | null {
124
126
  return null;
125
127
  }
126
128
 
129
+ function modelMoveShape(value: unknown): string | null {
130
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "model move must be an object";
131
+ const move = value as Record<string, unknown>;
132
+ for (const key of ["action", "target", "reply"] as const) {
133
+ if (move[key] !== undefined && !(key === "action" && move[key] === null) && typeof move[key] !== "string")
134
+ return `model ${key} must be a string${key === "action" ? " or null" : ""}`;
135
+ }
136
+ if (move.payload !== undefined && (!move.payload || typeof move.payload !== "object" || Array.isArray(move.payload)))
137
+ return "model payload must be an object";
138
+ return null;
139
+ }
140
+
127
141
  // ── validating the move against the contract + the live manifest ─────────────────────────────────
128
142
  /** Turn an UNTRUSTED ModelMove into a ValidatedMove or an informative rejection. This is the safety
129
143
  * boundary: the model can PROPOSE anything, but only moves that are legal in the vocabulary AND
@@ -140,6 +154,8 @@ export function validateMove(
140
154
  move: ModelMove,
141
155
  manifest: Manifest,
142
156
  ): { ok: true; move: ValidatedMove } | { ok: false; reason: string } {
157
+ const shape = modelMoveShape(move);
158
+ if (shape) return { ok: false, reason: shape };
143
159
  const action = move.action ?? null;
144
160
 
145
161
  // reply-only: the model chose to talk, not act.
@@ -139,10 +139,14 @@ body:has(.app-shell) { container-type: inline-size; container-name: shell-frame;
139
139
  @container shell-frame (max-width: 768px) {
140
140
  .app-shell {
141
141
  grid-template-columns: minmax(0, 1fr);
142
- grid-template-areas: "window" "topbar" "main" "console" "status";
143
- grid-template-rows: auto auto minmax(0, 1fr) auto auto;
142
+ /* the last row only reserves room for the bottom sheet's peeking head (sidebar-panel.css),
143
+ so the sheet never covers the end of <main>. The console strip and status bar are
144
+ dropped here: on a phone they stacked 75px of chrome under the sheet for no new reading. */
145
+ grid-template-areas: "window" "topbar" "main" "sheet";
146
+ grid-template-rows: auto auto minmax(0, 1fr) 2.75rem;
144
147
  }
145
148
  .app-shell__aside { display: none; }
149
+ .app-shell > .app-shell__console, .app-shell > .app-shell__status { display: none; } /* two classes: status-bar.css sorts later */
146
150
  .app-shell[data-rail-collapsed="true"] { --shell-rail: 15rem; } /* collapse-width is desktop-only */
147
151
  /* two classes ON PURPOSE: a composed rail (e.g. side-rail) may carry its own `position:
148
152
  relative` (the icon gutter), and the CSS bundle sorts side-rail AFTER app-shell — at equal
@@ -191,3 +195,15 @@ body[data-viewport="mobile"] { --shell-viewport-w: 24.4rem; }
191
195
  .app-shell__console { view-transition-name: shell-console; }
192
196
  .app-shell__window { view-transition-name: shell-window; }
193
197
  .app-shell__status { view-transition-name: shell-status; }
198
+ /* the chrome SNAPS to its new state rather than morphing. The browser's default for a named
199
+ element is to tween its box and cross-fade its two snapshots, so a tab strip that lost a tab,
200
+ or a window that gained the aside, slid visibly on every navigation. Only <main> fades. */
201
+ ::view-transition-group(shell-rail), ::view-transition-group(shell-topbar),
202
+ ::view-transition-group(shell-aside), ::view-transition-group(shell-console),
203
+ ::view-transition-group(shell-window), ::view-transition-group(shell-status),
204
+ ::view-transition-new(shell-rail), ::view-transition-new(shell-topbar),
205
+ ::view-transition-new(shell-aside), ::view-transition-new(shell-console),
206
+ ::view-transition-new(shell-window), ::view-transition-new(shell-status) { animation: none; }
207
+ ::view-transition-old(shell-rail), ::view-transition-old(shell-topbar),
208
+ ::view-transition-old(shell-aside), ::view-transition-old(shell-console),
209
+ ::view-transition-old(shell-window), ::view-transition-old(shell-status) { display: none; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tjakoen/grain",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "description": "GRAIN — an AI-interaction design system where every surface is operable by both a human and an AI through one shared vocabulary.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/scripts/tabs.js CHANGED
@@ -123,5 +123,9 @@
123
123
  // refresh: re-resolve labels (e.g. after an island fills the data-tab-source tree lazily)
124
124
  window.grain.tabs = { open: () => [...list], close: closeTab, closeAll, refresh: render };
125
125
  }
126
- if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
126
+ // Loaded as a classic script right after the strip, it renders before the first paint, which a
127
+ // view transition captures; that keeps the stored tabs from popping in a frame late. Loaded any
128
+ // later (defer, module, end of body), the strip is parsed and this simply runs.
129
+ if (document.readyState !== "loading" || document.querySelector("[data-open-tabs]")) init();
130
+ else document.addEventListener("DOMContentLoaded", init);
127
131
  })();
package/styles/global.css CHANGED
@@ -6,7 +6,7 @@
6
6
  would break the spell (DESIGN-SYSTEM §6). */
7
7
  @view-transition { navigation: auto; }
8
8
  @media (prefers-reduced-motion: reduce) { @view-transition { navigation: none; } }
9
- ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 0.3s; }
9
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 0.15s; }
10
10
 
11
11
  * { box-sizing: border-box; }
12
12