Skip to content

Commit bec4519

Browse files
committed
Merge branch 'wt/sdk-fu' into claude/epic-dirac-pn3a5s
2 parents 165ca14 + ac160ec commit bec4519

39 files changed

Lines changed: 1706 additions & 188 deletions

‎CHANGELOG.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,49 @@
1+
## Unreleased
2+
3+
**Generative UI with a design system, recorded and replayed.**
4+
5+
- `UiSession(designSystem:)` allows the design system's components under the session's trust profile
6+
(`TrustProfile.withComponents`): with the default `TrustProfile.agent` every call to one was
7+
`capability_not_allowed`, so a model's design-system UI never applied.
8+
- A session's theme names (`"color": "primaryBackground"`, `"style": "sectionTitle"`) resolve in its own nodes in
9+
light mode: `ThemedSource` started with no names and was only given the theme when the mode changed, so they
10+
resolved in dark only (components' names did resolve).
11+
- A component call that streams in after its parent shows (a pending child that arrives as a call, or a set that
12+
changes a node's type to one) renders as its definition: its parent places its children again
13+
(`NodeBox._becameCall`). It drew as the empty box of an unknown type.
14+
- The stream replay (`tool/stream/replay.sh`) replays a recording with the design system its meta names (or
15+
`--design-system`), in light or `--theme dark`, and reports `designSystem` (component calls rendered and not,
16+
core controls the design system replaces) in `metrics.json`. `examples/stream_chat/tool/record.dart
17+
--design-system ssui` records with one (prompt, `ui_docs`, per-op validation and retries), `record_all.sh` gains
18+
`--design-system <id>` and `--only ssui`, and the live summary has the design system per cell and its components
19+
against the raw controls it replaces.
20+
21+
**Fixes.**
22+
23+
- Gauges, charts and barcodes drawn with the theme's colours (the ones they leave unset, `indicator_theme.dart`)
24+
repaint when the theme changes at run time (`setThemeMode`, the platform's brightness under `system`): the box
25+
notes it depends on the theme (`RenderTree.dependOnTheme`) and a theme change (`ComponentRegistry.theme`,
26+
`themeChanged`) re-applies it. Before, only nodes naming theme colours re-applied, so an unstyled gauge kept the
27+
old mode's colours.
28+
- The render command with no `--screen` no longer renders a canvas only ever opened as a modal as a screen of its
29+
own, whether the `openModal` is on a page or inside a component (the site's or its design system's).
30+
- An image whose path a binding builds (`"bind": {"decoration.fills[0].image.url": "images/${id}.jpg"}`), relative
31+
to the site, is read from the site's files when it is drawn: the app's tree reads site images through
32+
`SiteImageLoader` (the loader's file URL, else its bytes), and a raster image whose URL has no scheme is fetched by
33+
the tree's loader instead of `NetworkImage`. Literal paths were already resolved when the layout loads.
34+
- A theme's `fontFamily` is the default family of every text, as it is the controls' (Flutter: the `DefaultTextStyle`
35+
an app's theme gives): a text node with no family (and no `defaultTextStyle` above it naming one) is drawn in it,
36+
in a site (`CodelesslyWidget`) and in a session (`CodelesslyView`). `RenderTree.textDefault` holds it under every
37+
node's inherited default text style. Before, controls took the theme's font and text nodes the platform's. No
38+
parity golden or render test changed.
39+
- The render command waits for its own font fetches still in flight before its runtime checks: a family asked for by
40+
name late (named by a binding, so no layout lists it, its file slow to read) was measured in the fallback, so
41+
`text_clipped` was reported for text the PNG drew in the real font. `DirectoryFontFetcher.debugLatency` simulates a
42+
slow source in tests.
43+
- A `dateTimeInput`, `datePicker` or `timePicker` whose width hugs takes its content's width (`IntrinsicWidth`), as a
44+
`textField` and a `dropdown` already did: in a wrapping row it took the row's whole width, and in a plain row it
45+
failed (an unbounded `InputDecorator`). A picker's field reads its constraints only when its height fills.
46+
147
## 30.1.0
248

349
**No special cases left** (with codelessly_api's unreleased removal of the last 21 one-look fields, each now a

‎examples/stream_chat/README.md‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,18 +89,41 @@ sends the brief's follow-up edit (`.followup.jsonl`). `.summary.json` has the nu
8989
environment only: nothing writes it, and the files hold no request headers. Without the key the command exits
9090
with status 2 and says so.
9191

92+
### With a design system
93+
94+
```sh
95+
ANTHROPIC_API_KEY=<key> dart run tool/record.dart --ui flights --model claude-haiku-5-5 --design-system ssui --followup \
96+
--out ../../tool/stream/streams/live/flights@claude-haiku-5-5.compact.ssui.r1.jsonl
97+
```
98+
99+
`--design-system <id-or-folder>` (an id of the SDK's `design_systems/`, `ssui` → `../../design_systems/ssui`; a
100+
design system folder; or a bundle `.json`; compact prompt only) records the UI as `DESIGN_SYSTEM` makes it in the
101+
app: the system prompt is generated from the design system, `ui_docs` answers its documents and components, and each
102+
op of the generation, its retries and its follow-up is validated as `UiSession(designSystem:)` applies it (its
103+
components are node types the agent may call, its token names are the theme's colours and text styles), so the
104+
retry protocol sends back what is wrong with the design system in view. Each recording's meta has `designSystem`
105+
(`id`, `name`, `version`); the summary counts `designSystemComponents` (nodes that call its components) and
106+
`replacedControls` (nodes of a core control it replaces: a raw `filledButton` where its `Button` was meant). The
107+
replay reads the design system from the meta (`lib/src/record_check.dart` is the check, tested offline in
108+
`test/record_check_test.dart`).
109+
92110
## The live matrix
93111

94112
```sh
95113
ANTHROPIC_API_KEY=<key> tool/record_all.sh # everything; --repeats 2 per card and page cell
96114
ANTHROPIC_API_KEY=<key> tool/record_all.sh --only apps --app-repeats 2
115+
ANTHROPIC_API_KEY=<key> tool/record_all.sh --only ssui # SSUI: 15 use cases, flights, weather x haiku, sonnet
97116
tool/record_all.sh --dry-run # the cells and commands, no request
98117
```
99118

100119
Cells: the two cards (flights, weather) on `claude-haiku-5-5`, `claude-sonnet-5-5` and `claude-opus-5-5`, each
101120
with `--prompt compact` and `--prompt full` and the follow-up; the two page briefs on haiku and sonnet (compact);
102121
the six app briefs on sonnet and opus (compact, scripts on; `--app-repeats`, default 1), haiku once each, and
103-
sudoku and basketball once with scripts off. Recordings go to `../../tool/stream/streams/live/<date>/`, replays
122+
sudoku and basketball once with scripts off. `--only ssui`: the fifteen use cases, flights and weather on haiku and
123+
sonnet, compact, once each, with their follow-ups, made with the SSUI design system (`<ui>@<model>.compact.ssui.r1`).
124+
`--design-system <id>` makes every cell use that design system (cells with `--prompt full` are skipped); the table
125+
then has the design system per cell, its components against the raw controls it replaces, and calls the replay did
126+
not render as their definition. Recordings go to `../../tool/stream/streams/live/<date>/`, replays
104127
(video, contact sheet, metrics, and for apps the scripted "works when used" interaction of
105128
`tool/stream/interactions/<ui>.json`) to `../../tool/stream/out/live/<date>/`, and one table to
106129
`summary.md` / `summary.json` there: per cell the time to first token, first paint and first text, complete,

‎examples/stream_chat/lib/src/llm.dart‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -513,10 +513,11 @@ String userMessage(String brief, String kind) => switch (kind) {
513513
api.TrustProfile profileFor(String kind, {bool scripts = true}) =>
514514
kind == 'app' && scripts ? api.TrustProfile.agentApps : api.TrustProfile.agent;
515515

516-
/// The tools for [variant] and [profile] over the core catalog: compact
517-
/// tools with ui_docs, or the full schemas.
518-
List<Map<String, Object?>> uiToolsFor(PromptVariant variant, {api.TrustProfile? profile}) => api.uiTools(
519-
(profile ?? api.TrustProfile.agent).restrict(api.Catalog.core),
516+
/// The tools for [variant] and [profile] over the core catalog (with
517+
/// [designSystem]'s components when there is one): compact tools with
518+
/// ui_docs, or the full schemas.
519+
List<Map<String, Object?>> uiToolsFor(PromptVariant variant, {api.TrustProfile? profile, api.DesignSystem? designSystem}) => api.uiTools(
520+
_allowed(profile ?? api.TrustProfile.agent, designSystem).restrict(designSystem?.catalogOver(api.Catalog.core) ?? api.Catalog.core),
520521
compact: variant == PromptVariant.compact,
521522
docs: variant == PromptVariant.compact,
522523
);
@@ -551,9 +552,15 @@ Object? answerLookup(
551552
}) {
552553
final p = profile ?? api.TrustProfile.agent;
553554
final catalog = designSystem?.catalogOver(api.Catalog.core) ?? api.Catalog.core;
555+
final allowed = _allowed(p, designSystem);
554556
return switch (tool) {
555557
'ui_docs' => api.docsTopic('${input['topic'] ?? ''}', profile: p, designSystem: designSystem),
556-
'ui_read' => api.readUi(document, input, rev: rev, catalog: p.restrict(catalog)),
558+
'ui_read' => api.readUi(document, input, rev: rev, catalog: allowed.restrict(catalog)),
557559
_ => {'error': 'No tool "$tool".'},
558560
};
559561
}
562+
563+
/// [profile] with [designSystem]'s components allowed, as
564+
/// `UiSession(designSystem:)` has it.
565+
api.TrustProfile _allowed(api.TrustProfile profile, api.DesignSystem? designSystem) =>
566+
designSystem == null ? profile : profile.withComponents(designSystem.components);
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
// What tool/record.dart does with a recorded turn, offline: the ops of a
2+
// ui_apply tool input applied as a session applies a stream (strict
3+
// validation per op against the catalog, the design system's components
4+
// and its tokens; the end of the stream; the lints of a finished UI), and
5+
// the design system a recording is made with, found by id or folder.
6+
// Pure Dart with dart:io: the record command and the tests use it, the app
7+
// does not.
8+
import 'dart:convert';
9+
import 'dart:io';
10+
11+
import 'package:codelessly_api/core.dart';
12+
import 'package:codelessly_api/validate.dart';
13+
14+
/// The design system [idOrPath] names: a design system folder (with a
15+
/// `design_system.json`), a bundle (`.json`, `tool/design_system_bundle.dart`),
16+
/// or an id, looked up as a folder of [designSystems] (the SDK's
17+
/// `design_systems/`, `../../design_systems` from this example) and then as
18+
/// a bundled asset (`assets/design_systems/<id>.json`). Throws a
19+
/// [StateError] that says what was tried when none is found or it does not
20+
/// load cleanly.
21+
Future<DesignSystem> loadDesignSystem(String idOrPath, {String designSystems = '../../design_systems'}) async {
22+
final tried = <String>[];
23+
for (final dir in [idOrPath, '$designSystems/$idOrPath']) {
24+
tried.add(dir);
25+
if (!File('$dir/${DesignSystemManifest.fileName}').existsSync()) continue;
26+
final problems = <String>[];
27+
final ds = await DesignSystem.load((ref) async {
28+
final f = File('$dir/$ref');
29+
return f.existsSync() ? f.readAsStringSync() : null;
30+
}, problems: problems);
31+
if (problems.isNotEmpty) throw StateError('The design system at $dir does not load cleanly: ${problems.join('; ')}');
32+
return ds;
33+
}
34+
for (final file in [idOrPath, 'assets/design_systems/$idOrPath.json']) {
35+
tried.add(file);
36+
if (file.endsWith('.json') && File(file).existsSync()) return DesignSystem.fromJson(jsonDecode(File(file).readAsStringSync()));
37+
}
38+
throw StateError('No design system "$idOrPath" (tried ${tried.join(', ')}).');
39+
}
40+
41+
/// What the recording's meta says about [ds]: its id, name and version.
42+
Map<String, Object?> designSystemMeta(DesignSystem ds) => {'id': ds.id, 'name': ds.name, 'version': ds.manifest.version};
43+
44+
/// How much of [doc] is made of [ds]: nodes whose type is one of its
45+
/// components, and nodes of a base control type it `replaces` (a raw
46+
/// `filledButton` where its `Button` was meant). A measure of whether a
47+
/// model used the design system.
48+
({int components, int replaced}) designSystemUsage(LayoutDocument doc, DesignSystem ds) {
49+
final replaces = ds.manifest.replaces.toSet();
50+
var components = 0, replaced = 0;
51+
for (final n in doc.nodes.values) {
52+
if (ds.components[n.type] != null) components++;
53+
if (replaces.contains(n.type)) replaced++;
54+
}
55+
return (components: components, replaced: replaced);
56+
}
57+
58+
/// The catalog a UI made with [ds] decodes with: the core catalog with its
59+
/// components' declarations.
60+
Catalog catalogFor(DesignSystem? ds) => ds?.catalogOver(Catalog.core) ?? Catalog.core;
61+
62+
/// The ops of [toolInput] applied to [doc] as a session applies a stream:
63+
/// one by one (incomplete), strictly validated (against [designSystem]'s
64+
/// components and tokens when there is one), then the end of the stream and
65+
/// the lints.
66+
CheckedTurn checkToolInput(LayoutDocument doc, String toolInput,
67+
{required TrustProfile profile, required bool protect, required int rev, GlyphCoverage? coverage, DesignSystem? designSystem}) {
68+
final before = doc;
69+
final catalog = catalogFor(designSystem);
70+
// As UiSession(designSystem:) does: its components are types the agent may call.
71+
final allowed = designSystem == null ? profile : profile.withComponents(designSystem.components);
72+
final decoder = OpStreamDecoder();
73+
final streamed = decoder.add(toolInput);
74+
final end = decoder.close();
75+
final diagnostics = <EditDiagnostic>[...end.diagnostics];
76+
final applied = <int>{}, rejected = <int>{};
77+
final appliedOps = <EditOp>[];
78+
final check = strictEditCheck(ValidateOptions(components: designSystem?.components, theme: designSystem?.tokens));
79+
for (final s in streamed) {
80+
final r = applyOps(doc, [s.op],
81+
catalog: catalog, profile: allowed, check: check, incomplete: true, protectRoots: protect && before.roots.isNotEmpty);
82+
for (final d in r.diagnostics) {
83+
diagnostics.add(d.atOp(s.index));
84+
}
85+
if (r.applied.isNotEmpty) {
86+
applied.add(s.index);
87+
appliedOps.add(s.op);
88+
doc = r.document;
89+
} else {
90+
rejected.add(s.index);
91+
}
92+
}
93+
for (final d in end.diagnostics) {
94+
if (d.error && d.op >= 0) rejected.add(d.op);
95+
}
96+
diagnostics.addAll(endOfStream(doc));
97+
final lints = uiLints(doc, hasGlyph: coverage);
98+
diagnostics.addAll(lints);
99+
final result = EditResult(
100+
document: doc,
101+
applied: applied.difference(rejected).toList()..sort(),
102+
rejected: rejected.toList()..sort(),
103+
appliedOps: appliedOps,
104+
inverse: const [],
105+
diagnostics: diagnostics,
106+
pending: pendingIds(doc),
107+
rev: rev,
108+
revisions: const EditRevisions(),
109+
changed: const {},
110+
);
111+
return CheckedTurn(result, streamed.length, end, lints.length, designSystem);
112+
}
113+
114+
/// One turn's ops as checked by [checkToolInput].
115+
class CheckedTurn {
116+
CheckedTurn(this.result, this.ops, this.end, this.lints, this.designSystem);
117+
final EditResult result;
118+
final int ops;
119+
final OpStreamEnd end;
120+
final int lints;
121+
final DesignSystem? designSystem;
122+
LayoutDocument get document => result.document;
123+
124+
/// Rejected, pending or linted: worth a retry.
125+
bool get needsFix => result.errors.isNotEmpty || result.pending.isNotEmpty || lints > 0;
126+
127+
/// What goes back to the model as the ui_apply tool result.
128+
Map<String, Object?> toolResult(int rev) {
129+
final j = result.toModelJson();
130+
if (lints > 0 && !j.containsKey('next')) j['next'] = fixInstruction(rev: rev, pending: result.pending);
131+
return j;
132+
}
133+
134+
Map<String, Object?> counts() {
135+
final ds = designSystem;
136+
final usage = ds == null ? null : designSystemUsage(document, ds);
137+
return {
138+
'ops': ops,
139+
'opsApplied': result.applied.length,
140+
'opsRejected': result.rejected.length,
141+
'opsRecoveredFromMalformed': end.recovered,
142+
'jsonRepairs': end.repairs,
143+
'pending': result.pending.length,
144+
'errors': [for (final d in result.errors) '${d.code} ${d.path}'],
145+
'lints': [for (final d in result.warnings) if (const {'empty_button', 'low_contrast', 'missing_glyph'}.contains(d.code)) '${d.code} ${d.nodeId}'],
146+
'warnings': result.warnings.length,
147+
'nodes': document.nodes.length,
148+
'scripts': (document.extra['scripts'] as List?)?.length ?? 0,
149+
'scriptChars': [for (final s in (document.extra['scripts'] as List?) ?? const []) '${(s as Map)['source'] ?? ''}'.length].fold<int>(0, (a, b) => a + b),
150+
if (usage != null) 'designSystemComponents': usage.components,
151+
if (usage != null) 'replacedControls': usage.replaced,
152+
};
153+
}
154+
}

‎examples/stream_chat/lib/src/sources.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ class LlmStreamSource implements StreamSource {
140140
apiKey: apiKey,
141141
model: model,
142142
systemPrompt: systemPromptFor(variant, full: systemPrompt, designSystem: designSystem),
143-
tools: uiToolsFor(variant));
143+
tools: uiToolsFor(variant, designSystem: designSystem));
144144

145145
final UiModel _model;
146146

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// What tool/record.dart checks a recorded turn with, offline (no request):
2+
// with --design-system the ops are applied as UiSession(designSystem:)
3+
// applies them (its components are types the agent may call, its token
4+
// names are colours and text styles), and the counts say how much of the UI
5+
// is the design system's.
6+
import 'dart:convert';
7+
import 'dart:io';
8+
9+
import 'package:codelessly_api/core.dart';
10+
import 'package:flutter_test/flutter_test.dart';
11+
import 'package:stream_chat/src/record_check.dart';
12+
13+
/// The ui_apply input of the SDK's hand-written SSUI recording (the replay
14+
/// test's fixture).
15+
String _ssuiCard() => File('../../test/tool/fixtures/replay/ssui_card.jsonl')
16+
.readAsLinesSync()
17+
.skip(1)
18+
.map((l) => (jsonDecode(l) as Map)['delta'] as String)
19+
.join();
20+
21+
void main() {
22+
test('--design-system ssui finds the SDK\'s design system folder, and the meta names its id and version', () async {
23+
final ds = await loadDesignSystem('ssui');
24+
expect(ds.id, 'ssui');
25+
expect(designSystemMeta(ds), {'id': 'ssui', 'name': 'Soft SaaS UI', 'version': '1.0.0'});
26+
expect((await loadDesignSystem('../../design_systems/ssui')).components.definitions.length, ds.components.definitions.length);
27+
expect(() => loadDesignSystem('nope'), throwsStateError);
28+
});
29+
30+
test('a UI made of SSUI components and tokens passes the per-op check with SSUI, and is counted as SSUI\'s', () async {
31+
final ds = await loadDesignSystem('ssui');
32+
final checked = checkToolInput(LayoutDocument(catalog: catalogFor(ds)), _ssuiCard(),
33+
profile: TrustProfile.agent, protect: false, rev: 1, designSystem: ds);
34+
expect(checked.result.errors, isEmpty, reason: '${checked.result.errors}');
35+
expect(checked.needsFix, isFalse);
36+
expect(checked.counts(), containsPair('designSystemComponents', 4));
37+
expect(checked.counts(), containsPair('replacedControls', 0));
38+
});
39+
40+
test('the same UI without the design system is rejected, so a retry would be asked for', () {
41+
final checked = checkToolInput(LayoutDocument(), _ssuiCard(), profile: TrustProfile.agent, protect: false, rev: 1);
42+
expect(checked.result.errors.map((d) => d.code), containsAll(['capability_not_allowed', 'unknown_theme_name']));
43+
expect(checked.needsFix, isTrue);
44+
expect(checked.counts().containsKey('designSystemComponents'), isFalse);
45+
});
46+
47+
test('a base control the design system replaces is counted as such', () async {
48+
final ds = await loadDesignSystem('ssui');
49+
final ops = jsonEncode({
50+
'ops': [
51+
{'op': 'roots', 'roots': ['c']},
52+
{'op': 'set', 'id': 'c', 'node': {'type': 'canvas', 'slots': {'body': 'ok'}, 'layout': {'width': 390, 'height': 100}}},
53+
{
54+
'op': 'set',
55+
'id': 'ok',
56+
'node': {'type': 'filledButton', 'props': {'label': 'OK'}, 'layout': {'width': 80, 'height': 32}},
57+
},
58+
],
59+
});
60+
final checked = checkToolInput(LayoutDocument(catalog: catalogFor(ds)), ops, profile: TrustProfile.agent, protect: false, rev: 1, designSystem: ds);
61+
expect(checked.counts(), containsPair('designSystemComponents', 0));
62+
expect(checked.counts(), containsPair('replacedControls', 1));
63+
});
64+
}

0 commit comments

Comments
 (0)